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

function preload() {
    game.load.tilemap('ClassicMap', '../assets/RoyalPac-mapV2.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '../assets/TileSet.png');
    game.load.image('star', '../assets/star.png');
    game.load.spritesheet('pacman','../assets/pacman_test.png',25,25,13);
}

var map;
var layer;
var player;
var pac;
var tiles;
var tileset;
var cursors;

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Création Map
    map = game.add.tilemap('ClassicMap', 'tiles');
    map.addTilesetImage('TileSet', 'tiles');
    layer = map.createLayer('Calque de Tile 1');
    layer.resizeWorld();

    map.setCollision(2);
    map.setCollision(1);

    game.physics.arcade.collide(player, layer);
    player = game.add.sprite(375,375,'pacman');

    game.physics.enable(player);
    // echo("je veux merge");
    player.body.collideWorldBounds = true;
    // player.scale.setTo(0.95,0.95);
    //player.body.collideWorldBounds = true;
    //player.body.setSize(23, 23, 0, 0);
    player.animations.add('left', [6, 5, 4], 10, true);
    player.animations.add('right', [9, 8, 7], 10, true);
    player.animations.add('down', [3, 2, 1], 10, true);
    player.animations.add('up', [12, 11, 10], 10, true);

    var m_un = new monster(game,200,300);

    game.add.existing(m_un);
    pac = new pacman(game,layer,200,200);
    game.add.existing(pac);

    game.physics.arcade.collide(pac, layer);

    game.physics.enable(pac);
    cursors = game.input.keyboard.createCursorKeys();
}

function canGo(direction, player, layer, map){
    //player.body.velocity.x = 0;
    //player.body.velocity.y = 0;
    if (direction == 'down') {
        return((map.getTileWorldXY(player.position.x + 24, player.position.y + 25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y +25, 25, 25, layer).index == 136)); //down
    }
    if (direction == 'up') {
        return((map.getTileWorldXY(player.position.x + 24, player.position.y - 1, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y - 1, 25, 25, layer).index == 136)); //up
    }
    if (direction == 'right'){
        return((map.getTileWorldXY(player.position.x + 25, player.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x + 25, player.position.y, 25, 25, layer).index == 136)); //right
    }
    if (direction == 'left') {
        return((map.getTileWorldXY(player.position.x - 1, player.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x - 1, player.position.y, 25, 25, layer).index == 136)); //left
    }
}

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

  if (canGo('left',player,layer,map) || canGo('right',player,layer,map) || canGo('up',player,layer,map) || canGo('down',player,layer,map)) {
    console.log("ça paaaasse !");
    console.log("LeftTile = " + map.getTileWorldXY(player.position.x -25, player.position.y, 25, 25, layer).index);
    console.log("RightTile = " + map.getTileWorldXY(player.position.x +25, player.position.y, 25, 25, layer).index);
    console.log("UpTile = " + map.getTileWorldXY(player.position.x, player.position.y -25, 25, 25, layer).index);
    console.log("DownTile = " + map.getTileWorldXY(player.position.x +24, player.position.y +25, 25, 25, layer).index);
  }
    var caPasse = canGo('left',player,layer,map) + canGo('right',player,layer,map) + canGo('up',player,layer,map) + canGo('down',player,layer,map);
    if (caPasse) {
        console.log("caPasse = true");
    }
    else {
        console.log("caPasse = false");
    }
  //Actuellement ne fonctionne presque correctement qu'à gauche, les autres directions c'est un peu random
  if (cursors.left.isDown){
      //  Move to the left
      if (canGo('left',player,layer,map)){
        player.body.velocity.x = -25;
        player.body.velocity.y = 0;
        player.animations.play('left');
        pacman.direction = 'left';
      }
  }
  if (cursors.right.isDown){
      //  Move to the right
      if (canGo('right',player,layer,map)){
        player.body.velocity.x = 25;
        player.body.velocity.y = 0;
        player.animations.play('right');
        pacman.direction = 'right';
      }
  }
  if (cursors.up.isDown){
      //  Move up
      if (canGo('up',player,layer,map)){
        player.body.velocity.y = -25;
        player.body.velocity.x = 0;
        player.animations.play('up');
        pacman.direction = 'up';
      }
  }
  if (cursors.down.isDown){
      //  Move down
      if (canGo('down',player,layer,map)){
        player.body.velocity.y = 25;
        player.body.velocity.x = 0;
        player.animations.play('down');
        pacman.direction = 'down';
      }
  }

}

pacman = function(game,layer,x,y){
  Phaser.Sprite.call(this,game,x,y,'pacman');
  this.speed_x = 30;
  this.speed_y = 0;
  this.x = x;
  this.y = y;
  this.relativeSpeed = 0;
  this.layer = layer;
  this.game = game;
  this.waitingVerticalMovement = true;
  this.waitingHorizontalMovement = false;

  console.log(this.game);
}
pacman.prototype = Object.create(Phaser.Sprite.prototype);
pacman.prototype.constructor = pacman;

pacman.prototype.create = function(){
  this.animations.add('left', [6, 5, 4], 10, true);
  this.animations.add('right', [9, 8, 7], 10, true);
  this.animations.add('down', [3, 2, 1], 10, true);
  this.animations.add('up', [12, 11, 10], 10, true);
}

pacman.prototype.canGo = function(direction, layer, map){
  if (direction == 'down') {
      return((map.getTileWorldXY(this.position.x + 24, this.position.y + 25, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x, this.position.y +25, 25, 25, layer).index == 136)); //down
  }
  if (direction == 'up') {
      return((map.getTileWorldXY(this.position.x + 24, this.position.y - 1, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x, this.position.y - 1, 25, 25, layer).index == 136)); //up
  }
  if (direction == 'right'){
      return((map.getTileWorldXY(this.position.x + 25, this.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x + 25, this.position.y, 25, 25, layer).index == 136)); //right
  }
  if (direction == 'left') {
      return((map.getTileWorldXY(this.position.x - 1, this.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x - 1, this.position.y, 25, 25, layer).index == 136)); //left
  }
}

pacman.prototype.update = function(){
    this.body.velocity.x = this.speed_x;
    this.body.velocity.y = this.speed_y;
    console.log(this.body.x);
    console.log(this.body.y);
    this.relativeSpeed = Math.abs(this.body.x - this.x);

    if (this.canGo("up",layer,map) && this.waitingVerticalMovement) {
      this.speed_x = 0;

      console.log(Math.floor(this.body.x));
      this.body.x = Math.floor(this.body.x);
      this.body.y = Math.floor(this.body.y);
      this.speed_y = -30;

      this.waitingVerticalMovement = false;
      this.waitingHorizontalMovement = true;

    }
    if (this.canGo("left",layer,map) && this.waitingHorizontalMovement) {
      this.speed_y = 0;

      console.log(Math.floor(this.body.x));
      this.body.x = Math.floor(this.body.x);
      this.body.y = Math.floor(this.body.y);
      this.speed_x = -30;

      this.waitingVerticalMovement = true;
      this.waitingHorizontalMovement = false;

    }

    //mise à jour des coordonnées de l'objet
    this.y = this.body.y;
    this.x = this.body.x;
}

monster = function(game,x,y){
  Phaser.Sprite.call(this,game,x,y,'star');
}
//monster herite des methodes et prop de Phaser.Sprite
monster.prototype = Object.create(Phaser.Sprite.prototype);
//monster et le constructeur de la classe monster
//monster est une classe fille de Phaser.Sprite
monster.prototype.constructor = monster;

monster.prototype.create = function(){
  game.physics.enable(this);
  game.physics.arcade.collide(this, layer);
}

monster.prototype.update = function(){
  //console.log("hello");
}

//bat les couilles wallah déconne pas
<commit_msg>Enfin<commit_after>
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update
});

function preload() {
    game.load.tilemap('ClassicMap', '../assets/RoyalPac-mapV2.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '../assets/TileSet.png');
    game.load.image('star', '../assets/star.png');
    game.load.spritesheet('pacman','../assets/pacman_test.png',25,25,13);
}

var map;
var layer;
var player;
var pac;
var tiles;
var tileset;
var cursors;

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //Création Map
    map = game.add.tilemap('ClassicMap', 'tiles');
    map.addTilesetImage('TileSet', 'tiles');
    layer = map.createLayer('Calque de Tile 1');
    layer.resizeWorld();

    map.setCollision(2);
    map.setCollision(1);

    game.physics.arcade.collide(player, layer);
    player = game.add.sprite(375,375,'pacman');

    game.physics.enable(player);
    player.body.collideWorldBounds = true;
    // player.scale.setTo(0.95,0.95);
    //player.body.collideWorldBounds = true;
    //player.body.setSize(23, 23, 0, 0);
    player.animations.add('left', [6, 5, 4], 10, true);
    player.animations.add('right', [9, 8, 7], 10, true);
    player.animations.add('down', [3, 2, 1], 10, true);
    player.animations.add('up', [12, 11, 10], 10, true);

    var m_un = new monster(game,200,300);

    game.add.existing(m_un);
    pac = new pacman(game,layer,200,200);
    game.add.existing(pac);

    game.physics.arcade.collide(pac, layer);

    game.physics.enable(pac);
    cursors = game.input.keyboard.createCursorKeys();
}

function canGo(direction, player, layer, map){
    //player.body.velocity.x = 0;
    //player.body.velocity.y = 0;
    if (direction == 'down') {
        return((map.getTileWorldXY(player.position.x + 24, player.position.y + 25, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y +25, 25, 25, layer).index == 136)); //down
    }
    if (direction == 'up') {
        return((map.getTileWorldXY(player.position.x + 24, player.position.y - 1, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x, player.position.y - 1, 25, 25, layer).index == 136)); //up
    }
    if (direction == 'right'){
        return((map.getTileWorldXY(player.position.x + 25, player.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x + 25, player.position.y, 25, 25, layer).index == 136)); //right
    }
    if (direction == 'left') {
        return((map.getTileWorldXY(player.position.x - 1, player.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(player.position.x - 1, player.position.y, 25, 25, layer).index == 136)); //left
    }
}

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

  if (canGo('left',player,layer,map) || canGo('right',player,layer,map) || canGo('up',player,layer,map) || canGo('down',player,layer,map)) {
    console.log("ça paaaasse !");
    console.log("LeftTile = " + map.getTileWorldXY(player.position.x -25, player.position.y, 25, 25, layer).index);
    console.log("RightTile = " + map.getTileWorldXY(player.position.x +25, player.position.y, 25, 25, layer).index);
    console.log("UpTile = " + map.getTileWorldXY(player.position.x, player.position.y -25, 25, 25, layer).index);
    console.log("DownTile = " + map.getTileWorldXY(player.position.x +24, player.position.y +25, 25, 25, layer).index);
  }
    var caPasse = canGo('left',player,layer,map) + canGo('right',player,layer,map) + canGo('up',player,layer,map) + canGo('down',player,layer,map);
    if (caPasse) {
        console.log("caPasse = true");
    }
    else {
        console.log("caPasse = false");
    }
  //Actuellement ne fonctionne presque correctement qu'à gauche, les autres directions c'est un peu random
  if (cursors.left.isDown){
      //  Move to the left
      if (canGo('left',player,layer,map)){
        player.body.velocity.x = -25;
        player.body.velocity.y = 0;
        player.animations.play('left');
        pacman.direction = 'left';
      }
  }
  if (cursors.right.isDown){
      //  Move to the right
      if (canGo('right',player,layer,map)){
        player.body.velocity.x = 25;
        player.body.velocity.y = 0;
        player.animations.play('right');
        pacman.direction = 'right';
      }
  }
  if (cursors.up.isDown){
      //  Move up
      if (canGo('up',player,layer,map)){
        player.body.velocity.y = -25;
        player.body.velocity.x = 0;
        player.animations.play('up');
        pacman.direction = 'up';
      }
  }
  if (cursors.down.isDown){
      //  Move down
      if (canGo('down',player,layer,map)){
        player.body.velocity.y = 25;
        player.body.velocity.x = 0;
        player.animations.play('down');
        pacman.direction = 'down';
      }
  }

}

pacman = function(game,layer,x,y){
  Phaser.Sprite.call(this,game,x,y,'pacman');
  this.speed_x = 30;
  this.speed_y = 0;
  this.x = x;
  this.y = y;
  this.relativeSpeed = 0;
  this.layer = layer;
  this.game = game;
  this.waitingVerticalMovement = true;
  this.waitingHorizontalMovement = false;

  console.log(this.game);
}
pacman.prototype = Object.create(Phaser.Sprite.prototype);
pacman.prototype.constructor = pacman;

pacman.prototype.create = function(){
  this.animations.add('left', [6, 5, 4], 10, true);
  this.animations.add('right', [9, 8, 7], 10, true);
  this.animations.add('down', [3, 2, 1], 10, true);
  this.animations.add('up', [12, 11, 10], 10, true);
}

pacman.prototype.canGo = function(direction, layer, map){
  if (direction == 'down') {
      return((map.getTileWorldXY(this.position.x + 24, this.position.y + 25, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x, this.position.y +25, 25, 25, layer).index == 136)); //down
  }
  if (direction == 'up') {
      return((map.getTileWorldXY(this.position.x + 24, this.position.y - 1, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x, this.position.y - 1, 25, 25, layer).index == 136)); //up
  }
  if (direction == 'right'){
      return((map.getTileWorldXY(this.position.x + 25, this.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x + 25, this.position.y, 25, 25, layer).index == 136)); //right
  }
  if (direction == 'left') {
      return((map.getTileWorldXY(this.position.x - 1, this.position.y + 24, 25, 25, layer).index == 136) && (map.getTileWorldXY(this.position.x - 1, this.position.y, 25, 25, layer).index == 136)); //left
  }
}

pacman.prototype.update = function(){
    this.body.velocity.x = this.speed_x;
    this.body.velocity.y = this.speed_y;
    console.log(this.body.x);
    console.log(this.body.y);
    this.relativeSpeed = Math.abs(this.body.x - this.x);

    if (this.canGo("up",layer,map) && this.waitingVerticalMovement) {
      this.speed_x = 0;

      console.log(Math.floor(this.body.x));
      this.body.x = Math.floor(this.body.x);
      this.body.y = Math.floor(this.body.y);
      this.speed_y = -30;

      this.waitingVerticalMovement = false;
      this.waitingHorizontalMovement = true;

    }
    if (this.canGo("left",layer,map) && this.waitingHorizontalMovement) {
      this.speed_y = 0;

      console.log(Math.floor(this.body.x));
      this.body.x = Math.floor(this.body.x);
      this.body.y = Math.floor(this.body.y);
      this.speed_x = -30;

      this.waitingVerticalMovement = true;
      this.waitingHorizontalMovement = false;

    }

    //mise à jour des coordonnées de l'objet
    this.y = this.body.y;
    this.x = this.body.x;
}

monster = function(game,x,y){
  Phaser.Sprite.call(this,game,x,y,'star');
}
//monster herite des methodes et prop de Phaser.Sprite
monster.prototype = Object.create(Phaser.Sprite.prototype);
//monster et le constructeur de la classe monster
//monster est une classe fille de Phaser.Sprite
monster.prototype.constructor = monster;

monster.prototype.create = function(){
  game.physics.enable(this);
  game.physics.arcade.collide(this, layer);
}

monster.prototype.update = function(){
  //console.log("hello");
}

//bat les couilles wallah déconne pas
<|endoftext|>


<commit_before>/* globals $ */

import * as d3 from './d3';
import D3Chart from './D3Chart';
import stackData from './utils/stackData';
import negativeRegionRect from './utils/negativeRegionRect';

const stack = d3.stack().offset(d3.stackOffsetDiverging);

/**
 * Determines the opacity with which a target line should be drawn.
 */
const targetLineOpacity = (serie) => {
  const value =
    serie.get('target_line_position') === '1' ? serie.present_value() : serie.future_value();

  return value === null ? 0 : 1;
};

/**
 * Creates a unique key for a serie to be used in D3 to link the serie data to the elements rendered
 * in the SVG.
 */
const serieKey = (serie) => {
  return `${serie.key}-${serie.data.x}`;
};

class StackedBar extends D3Chart {
  margins = {
    top: 20,
    bottom: 20,
    left: 20,
    right: 40,
  };

  legendMargin = 20;

  canRenderAsTable() {
    return true;
  }

  isEmpty() {
    return d3.sum(this.prepareData(), (d) => d.y) <= 0;
  }

  draw() {
    [this.width, this.height] = this.dimensions();
    this.seriesHeight = this.height - this.legendMargin;
    this.svg = this.createSVGContainer(this.width, this.seriesHeight, this.margins);

    this.displayLegend();

    const columns = this.getColumns();

    this.x = d3
      .scaleBand()
      .padding(0.4)
      .paddingOuter(0.2)
      .rangeRound([0, this.width - this.margins.left * 2])
      .domain(columns);

    this.barWidth = this.x.bandwidth();

    this.svg
      .selectAll('rect.negative-region')
      .data([0])
      .enter()
      .append('svg:rect')
      .attr('class', 'negative-region');

    // show years
    this.svg
      .selectAll('text.year')
      .data(columns)
      .enter()
      .append('svg:text')
      .attr('class', 'year')
      .text((d) => d)
      .attr('x', (d) => this.x(d))
      .attr('dx', this.barWidth / 2)
      .attr('y', this.seriesHeight + 15)
      .attr('text-anchor', 'middle');

    this.y = d3.scaleLinear().range([this.seriesHeight, 0]).domain([0, 7]);

    this.svg
      .append('g')
      .selectAll('g')
      .data(stackData(this.prepareData(), stack), (d) => d.key)
      .join('g')
      .attr('class', 'serie-group')
      .attr('fill', (d) => this.serieValue(d.key, 'color'))
      .selectAll('rect')
      .data((d) => d, serieKey)
      .join('rect')
      .attr('class', 'serie')
      .attr('x', (d) => this.x(d.data.x))
      .attr('y', this.seriesHeight)
      .attr('width', this.barWidth)
      .attr('height', 0)
      .attr('data-tooltip-title', (d) => this.serieValue(d.key, 'label'));

    // draw a nice axis
    this.yAxis = d3
      .axisRight()
      .scale(this.y)
      .ticks(5)
      .tickSize(-this.width, 10, 0)
      .tickFormat(this.formatValue);
    this.svg
      .append('svg:g')
      .attr('class', 'y_axis inner_grid')
      .attr('transform', `translate(${this.width - 25}, 0)`)
      .call(this.yAxis);

    // target lines
    // An ugly thing in the target lines is the extra attribute called "target
    // line position". If set to 1 then the target line must be shown on the
    // first column only, if 2 only on the 2nd. The CO2 chart is different, too

    return this.svg
      .selectAll('rect.target_line')
      .data(this.model.target_series(), (d) => d.get('gquery_key'))
      .enter()
      .append('svg:rect')
      .attr('class', 'target_line')
      .style('fill', (d) => d.get('color'))
      .attr('height', 2)
      .attr('width', () => this.x.bandwidth() * 1.2)
      .attr('x', (s) => {
        const year = s.get('target_line_position') === '1' ? this.startYear : this.endYear;
        return this.x(year) - this.x.bandwidth() * 0.1;
      })
      .attr('y', 0);
  }

  refresh(animate = true) {
    super.refresh();

    const transition = d3.transition().duration(animate ? 250 : 0);

    const tallest = (this.model.max_series_value() || 0) * 1.05;
    const smallest = Math.min(this.model.min_series_value(), 0);

    this.stackData = stackData;
    this.y = this.y.domain([smallest, tallest]).nice();

    // Animate the y-axis
    this.svg.selectAll('.y_axis').transition(transition).call(this.yAxis.scale(this.y));

    // Make the tick line corresponding with value 0 darker.
    this.svg.selectAll('.y_axis .tick').attr('class', (d) => (d === 0 ? 'tick bold' : 'tick'));

    // If the chart extends below zero, slightly shade the negative region.
    this.svg
      .selectAll('rect.negative-region')
      .data([smallest])
      .transition(transition)
      .attr('height', (d) => this.y(d) - this.y(0))
      .attr('width', this.width - 5)
      .attr('x', 0 - this.margins.left)
      .attr('y', this.y(0));

    this.svg
      .selectAll('g.serie-group')
      .data(stackData(this.prepareData(), stack), (d) => d.key)
      .selectAll('rect.serie')
      .data((d) => d, serieKey)
      .transition(transition)
      .attr('height', (d) => this.y(d[0]) - this.y(d[1]))
      .attr('y', (d) => this.y(d[1]))
      .attr('data-tooltip-text', (d) => this.formatValue(Math.abs(d[1]) - Math.abs(d[0])));

    // Move the target lines
    this.svg
      .selectAll('rect.target_line')
      .data(
        this.model.target_series(),
        (d) => `${d.get('gquery_key')}-${d.get('target_line_position')}`
      )
      .style('opacity', targetLineOpacity)
      .transition(transition)
      .attr('y', (d) => {
        const value =
          d.get('target_line_position') === '1' ? d.safe_present_value() : d.safe_future_value();

        return this.y(value);
      });

    return this.displayLegend();
  }

  getColumns() {
    const years = [this.startYear, this.endYear];

    if (this.model.year_1990_series().length > 0) {
      return [1990, ...years];
    }

    return years;
  }

  displayLegend() {
    $(this.containerSelector()).find('.legend').remove();

    const seriesForLegend = this.prepareLegendItems();
    const legendColumns = seriesForLegend.length > 6 ? 2 : 1;

    return this.drawLegend({
      series: seriesForLegend,
      columns: legendColumns,
    });
  }

  prepareLegendItems() {
    // Prepare legend
    // remove duplicate target series. Required for backwards compatibility.
    // When we'll drop the old charts we should use a single serie as target
    // rather than two.
    //
    // Also checks if series have a significant value i.e. a value larger than
    // 0.0000001 otherwise it doesn't get added to the legend.
    const targetLines = [];
    const seriesForLegend = [];

    for (let series of this.model.series.models) {
      const label = series.get('label');
      const total = Math.abs(series.safe_future_value()) + Math.abs(series.safe_present_value());

      if (series.get('is_target_line')) {
        if (!targetLines.includes(label)) {
          targetLines.push(label);
          seriesForLegend.push(series);
        }
        // otherwise the target line has already been added
      } else if (total > 1e-7) {
        seriesForLegend.push(series);
      }
    }

    return seriesForLegend;
  }

  // the stack layout method expects data to be in a precise format. We could
  // force the values() method but this way is simpler and cleaner.
  prepareData() {
    const series = [];

    this.model.year_1990_series().forEach((s) =>
      series.push({
        x: 1990,
        y: s.safe_present_value(),
        id: s.get('gquery_key'),
      })
    );

    this.model.non_target_series().forEach((s) => {
      series.push({
        x: this.startYear,
        y: s.safe_present_value(),
        id: s.get('gquery_key'),
      });

      series.push({
        x: this.endYear,
        y: s.safe_future_value(),
        id: s.get('gquery_key'),
      });
    });

    return series;
  }
}

export default StackedBar;
<commit_msg>Use negativeRegionRect in StackedBar<commit_after>/* globals $ */

import * as d3 from './d3';
import D3Chart from './D3Chart';
import stackData from './utils/stackData';
import negativeRegionRect from './utils/negativeRegionRect';

const stack = d3.stack().offset(d3.stackOffsetDiverging);

/**
 * Determines the opacity with which a target line should be drawn.
 */
const targetLineOpacity = (serie) => {
  const value =
    serie.get('target_line_position') === '1' ? serie.present_value() : serie.future_value();

  return value === null ? 0 : 1;
};

/**
 * Creates a unique key for a serie to be used in D3 to link the serie data to the elements rendered
 * in the SVG.
 */
const serieKey = (serie) => {
  return `${serie.key}-${serie.data.x}`;
};

class StackedBar extends D3Chart {
  margins = {
    top: 20,
    bottom: 20,
    left: 20,
    right: 40,
  };

  legendMargin = 20;

  canRenderAsTable() {
    return true;
  }

  isEmpty() {
    return d3.sum(this.prepareData(), (d) => d.y) <= 0;
  }

  draw() {
    [this.width, this.height] = this.dimensions();
    this.seriesHeight = this.height - this.legendMargin;
    this.svg = this.createSVGContainer(this.width, this.seriesHeight, this.margins);

    this.displayLegend();

    const columns = this.getColumns();

    this.x = d3
      .scaleBand()
      .padding(0.4)
      .paddingOuter(0.2)
      .rangeRound([0, this.width - this.margins.left * 2])
      .domain(columns);

    this.y = d3.scaleLinear().range([this.seriesHeight, 0]).domain([0, 7]);

    this.barWidth = this.x.bandwidth();

    // Add a "negative region" which shades area of the chart representing values below zero.
    const [negativeRect, updateNegativeRect] = negativeRegionRect(this.width - 5, this.y, {
      x: -this.margins.left,
    });

    this.updateNegativeRegion = updateNegativeRect;
    this.svg.node().append(negativeRect);

    // show years
    this.svg
      .selectAll('text.year')
      .data(columns)
      .enter()
      .append('svg:text')
      .attr('class', 'year')
      .text((d) => d)
      .attr('x', (d) => this.x(d))
      .attr('dx', this.barWidth / 2)
      .attr('y', this.seriesHeight + 15)
      .attr('text-anchor', 'middle');

    this.svg
      .append('g')
      .selectAll('g')
      .data(stackData(this.prepareData(), stack), (d) => d.key)
      .join('g')
      .attr('class', 'serie-group')
      .attr('fill', (d) => this.serieValue(d.key, 'color'))
      .selectAll('rect')
      .data((d) => d, serieKey)
      .join('rect')
      .attr('class', 'serie')
      .attr('x', (d) => this.x(d.data.x))
      .attr('y', this.seriesHeight)
      .attr('width', this.barWidth)
      .attr('height', 0)
      .attr('data-tooltip-title', (d) => this.serieValue(d.key, 'label'));

    // draw a nice axis
    this.yAxis = d3
      .axisRight()
      .scale(this.y)
      .ticks(5)
      .tickSize(-this.width, 10, 0)
      .tickFormat(this.formatValue);
    this.svg
      .append('svg:g')
      .attr('class', 'y_axis inner_grid')
      .attr('transform', `translate(${this.width - 25}, 0)`)
      .call(this.yAxis);

    // target lines
    // An ugly thing in the target lines is the extra attribute called "target
    // line position". If set to 1 then the target line must be shown on the
    // first column only, if 2 only on the 2nd. The CO2 chart is different, too

    this.svg
      .selectAll('rect.target_line')
      .data(this.model.target_series(), (d) => d.get('gquery_key'))
      .enter()
      .append('svg:rect')
      .attr('class', 'target_line')
      .style('fill', (d) => d.get('color'))
      .attr('height', 2)
      .attr('width', () => this.x.bandwidth() * 1.2)
      .attr('x', (s) => {
        const year = s.get('target_line_position') === '1' ? this.startYear : this.endYear;
        return this.x(year) - this.x.bandwidth() * 0.1;
      })
      .attr('y', 0);
  }

  refresh(animate = true) {
    super.refresh();

    const transition = d3.transition().duration(animate ? 250 : 0);

    const tallest = (this.model.max_series_value() || 0) * 1.05;
    const smallest = Math.min(this.model.min_series_value(), 0);

    this.stackData = stackData;
    this.y = this.y.domain([smallest, tallest]).nice();

    // Animate the y-axis
    this.svg.selectAll('.y_axis').transition(transition).call(this.yAxis.scale(this.y));

    // Make the tick line corresponding with value 0 darker.
    this.svg.selectAll('.y_axis .tick').attr('class', (d) => (d === 0 ? 'tick bold' : 'tick'));

    // If the chart extends below zero, slightly shade the negative region.
    this.updateNegativeRegion(this.y);

    this.svg
      .selectAll('g.serie-group')
      .data(stackData(this.prepareData(), stack), (d) => d.key)
      .selectAll('rect.serie')
      .data((d) => d, serieKey)
      .transition(transition)
      .attr('height', (d) => this.y(d[0]) - this.y(d[1]))
      .attr('y', (d) => this.y(d[1]))
      .attr('data-tooltip-text', (d) => this.formatValue(Math.abs(d[1]) - Math.abs(d[0])));

    // Move the target lines
    this.svg
      .selectAll('rect.target_line')
      .data(
        this.model.target_series(),
        (d) => `${d.get('gquery_key')}-${d.get('target_line_position')}`
      )
      .style('opacity', targetLineOpacity)
      .transition(transition)
      .attr('y', (d) => {
        const value =
          d.get('target_line_position') === '1' ? d.safe_present_value() : d.safe_future_value();

        return this.y(value);
      });

    return this.displayLegend();
  }

  getColumns() {
    const years = [this.startYear, this.endYear];

    if (this.model.year_1990_series().length > 0) {
      return [1990, ...years];
    }

    return years;
  }

  displayLegend() {
    $(this.containerSelector()).find('.legend').remove();

    const seriesForLegend = this.prepareLegendItems();
    const legendColumns = seriesForLegend.length > 6 ? 2 : 1;

    return this.drawLegend({
      series: seriesForLegend,
      columns: legendColumns,
    });
  }

  prepareLegendItems() {
    // Prepare legend
    // remove duplicate target series. Required for backwards compatibility.
    // When we'll drop the old charts we should use a single serie as target
    // rather than two.
    //
    // Also checks if series have a significant value i.e. a value larger than
    // 0.0000001 otherwise it doesn't get added to the legend.
    const targetLines = [];
    const seriesForLegend = [];

    for (let series of this.model.series.models) {
      const label = series.get('label');
      const total = Math.abs(series.safe_future_value()) + Math.abs(series.safe_present_value());

      if (series.get('is_target_line')) {
        if (!targetLines.includes(label)) {
          targetLines.push(label);
          seriesForLegend.push(series);
        }
        // otherwise the target line has already been added
      } else if (total > 1e-7) {
        seriesForLegend.push(series);
      }
    }

    return seriesForLegend;
  }

  // the stack layout method expects data to be in a precise format. We could
  // force the values() method but this way is simpler and cleaner.
  prepareData() {
    const series = [];

    this.model.year_1990_series().forEach((s) =>
      series.push({
        x: 1990,
        y: s.safe_present_value(),
        id: s.get('gquery_key'),
      })
    );

    this.model.non_target_series().forEach((s) => {
      series.push({
        x: this.startYear,
        y: s.safe_present_value(),
        id: s.get('gquery_key'),
      });

      series.push({
        x: this.endYear,
        y: s.safe_future_value(),
        id: s.get('gquery_key'),
      });
    });

    return series;
  }
}

export default StackedBar;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');
var PythonShell = require('python-shell');

// ENABLE CORS
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    bodyParser.json();
    next();
});

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string
// app.use(bodyParser.text());
app.use(bodyParser.text({ type: '*/xml' }));
app.use(bodyParser.text({ type: 'text/*' }));

app.head("/", function(req, res, next) {
    res.headers = req.headers;
    res.header("max-age", "0");
    res.send();
});

app.get("/", function(req, res, next) {
    res.send('Hello World!');
});

app.post("/xml2json", function(req, res, next) {
    let result;
    let xml = req.body;
    if (xml) {
        res.setHeader('Content-Type', req.header('Content-Type'));
        result = processXml(xml, res);
    } else {
        res.setHeader('Content-Type', 'application/json');
        result = {'content-type': req.header('Content-Type'), 'error': 'content-type is not xml or text'};
    }
    // res.send(result);
});

function processXml(xml, res) {
    try {
        let pythonpath = process.env.PORT ? 'D:\\Python34\\python.exe' : 'c:\\python27\\python.exe';

        var options = {
            mode: 'text',
            pythonPath: pythonpath,
            pythonOptions: ['-u'],
            scriptPath: '',
            args: ['value1', 'value2', 'value3']
        };

    PythonShell.run('main.py', options, function (err) {
        if (err) throw err;
        console.log('finished');
        res.send("finished");
    });
    } catch (err) {
        res.send("executing python failed");
    }

    // const xsl = fs.readFileSync('./xml2json.xsl', {encoding: 'utf-8'});
    // console.log("xsl: ", xsl);
    // let outputXmlString = xslt(xml, xsl);
    // console.log("xml: ", outputXmlString);
}

app.get("/greet/:name", function(req, res, next) {
    res.send('Hello ' +req.params.name);
});

app.get("/hello.world", function(req, res, next) {
    var json = {
        blabla: 'good'
    };
    res.send(JSON.stringify(json));
});

app.get("/weather", function(req, res, next) {
    var json = {
        weather: 'good'
    };
    // res.send('{ "id": "' + req.params.id + '"}');
    res.send(JSON.stringify(json));
});

app.get("/Weather", function(req, res, next) {
    var json = {
        weather: 'bad'
    };
    // res.send('{ "id": "' + req.params.id + '"}');
    res.send(json);
});

app.get("/sensor/:id", function(req, res, next) {
    var json = {
        id: req.params.id,
        name: 'Allgemein',
        values: [90,88,87,95,92,85,84,20,22,21,22,22,22,19,21,30,33,45,62,59,58,72,82,85,87,90,91,90,91,92]
    };
    res.send(JSON.stringify(json));
});

module.exports = app;

app.listen(process.env.PORT || 4000);<commit_msg>lxml python dependency<commit_after>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');
var PythonShell = require('python-shell');

// ENABLE CORS
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    bodyParser.json();
    next();
});

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string
// app.use(bodyParser.text());
app.use(bodyParser.text({ type: '*/xml' }));
app.use(bodyParser.text({ type: 'text/*' }));

app.head("/", function(req, res, next) {
    res.headers = req.headers;
    res.header("max-age", "0");
    res.send();
});

app.get("/", function(req, res, next) {
    res.send('Hello World!');
});

app.post("/xml2json", function(req, res, next) {
    let result;
    let xml = req.body;
    if (xml) {
        res.setHeader('Content-Type', req.header('Content-Type'));
        result = processXml(xml, res);
    } else {
        res.setHeader('Content-Type', 'application/json');
        result = {'content-type': req.header('Content-Type'), 'error': 'content-type is not xml or text'};
    }
    // res.send(result);
});

function processXml(xml, res) {
    try {
        let pythonpath = process.env.PORT ? 'D:\\Python34\\python.exe' : 'c:\\python27\\python.exe';

        var options = {
            mode: 'text',
            pythonPath: pythonpath,
            pythonOptions: ['-u'],
            scriptPath: '',
            args: ['value1', 'value2', 'value3']
        };

    PythonShell.run('main.py', options, function (err) {
        if (err) {
            res.send(err);
        } else {
            console.log('finished');
            res.send("finished");
        }
    });
    } catch (err) {
        res.send("executing python failed");
    }

    // const xsl = fs.readFileSync('./xml2json.xsl', {encoding: 'utf-8'});
    // console.log("xsl: ", xsl);
    // let outputXmlString = xslt(xml, xsl);
    // console.log("xml: ", outputXmlString);
}

app.get("/greet/:name", function(req, res, next) {
    res.send('Hello ' +req.params.name);
});

app.get("/hello.world", function(req, res, next) {
    var json = {
        blabla: 'good'
    };
    res.send(JSON.stringify(json));
});

app.get("/weather", function(req, res, next) {
    var json = {
        weather: 'good'
    };
    // res.send('{ "id": "' + req.params.id + '"}');
    res.send(JSON.stringify(json));
});

app.get("/Weather", function(req, res, next) {
    var json = {
        weather: 'bad'
    };
    // res.send('{ "id": "' + req.params.id + '"}');
    res.send(json);
});

app.get("/sensor/:id", function(req, res, next) {
    var json = {
        id: req.params.id,
        name: 'Allgemein',
        values: [90,88,87,95,92,85,84,20,22,21,22,22,22,19,21,30,33,45,62,59,58,72,82,85,87,90,91,90,91,92]
    };
    res.send(JSON.stringify(json));
});

module.exports = app;

app.listen(process.env.PORT || 4000);<|endoftext|>


<commit_before>'use strict';

const Promise = require('promise');
const cassandraConnector = require('../../clients/cassandra/CassandraConnector');
const withRunTime = require('../shared').withRunTime;

/**
 * @param {{input: {targetBbox: number[], defaultZoomLevel: number, logo: string, title: string, name: string, defaultLocation: number[], storageConnectionString: string, featuresConnectionString: string, mapzenApiKey: string, fbToken: string, supportedLanguages: string[]}}} args
 * @returns {Promise.<{name: string, properties: {targetBBox: number[], defaultZoomLevel: number, logo: string, title: string, defaultLocation: number[], storageConnectionString: string, featuresConnectionString: string, mapzenApiKey: string, fbToken: string, supportedLanguages: string[]}}>}
 */
function createOrReplaceSite(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, pages: Array<{pageUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, pages: Array<{pageUrl: string, RowKey: string}>}>}
 */
function modifyFacebookPages(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, pages: Array<{pageUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, pages: Array<{pageUrl: string, RowKey: string}>}>}
 */
function removeFacebookPages(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{acctUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{pageUrl: string, RowKey: string}>}>}
 */
function modifyTrustedTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{acctUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{pageUrl: string, RowKey: string}>}>}
 */
function removeTrustedTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}>}
 */
function modifyTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}>}
 */
function removeTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, terms: Array<{RowKey: string, lang: string, filteredTerms: string[]}>}}} args
 * @returns {Promise.<{runTime: string, filters: Array<{filteredTerms: string[], lang: string, RowKey: string}>}>}
 */
function modifyBlacklist(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, terms: Array<{RowKey: string, lang: string, filteredTerms: string[]}>}}} args
 * @returns {Promise.<{runTime: string, filters: Array<{filteredTerms: string[], lang: string, RowKey: string}>}>}
 */
function removeBlacklist(args, res) { // eslint-disable-line no-unused-vars
  return new Promise((resolve, reject) => {
    if (!args.input) return reject('No input specified');
    if (!args.input.terms) return reject('No terms specified');
    if (!args.input.terms.length) return reject('No terms specified');
    const terms = args.input.terms;
    const params = [terms.map( t => { return t.RowKey; } )];
    const update = "delete from fortis.blacklist where id in ?";
    cassandraConnector.executeQuery(update, params)
    .then(rows => {
      resolve({ filters: args.input.terms });
    })
    .catch(reject)
    ;
  });
}

module.exports = {
  createOrReplaceSite: createOrReplaceSite,
  modifyFacebookPages: withRunTime(modifyFacebookPages),
  removeFacebookPages: withRunTime(removeFacebookPages),
  modifyTrustedTwitterAccounts: withRunTime(modifyTrustedTwitterAccounts),
  removeTrustedTwitterAccounts: withRunTime(removeTrustedTwitterAccounts),
  modifyTwitterAccounts: withRunTime(modifyTwitterAccounts),
  removeTwitterAccounts: withRunTime(removeTwitterAccounts),
  modifyBlacklist: withRunTime(modifyBlacklist),
  removeBlacklist: withRunTime(removeBlacklist)
};
<commit_msg>Corrected lint errors.<commit_after>'use strict';

const Promise = require('promise');
const cassandraConnector = require('../../clients/cassandra/CassandraConnector');
const withRunTime = require('../shared').withRunTime;

/**
 * @param {{input: {targetBbox: number[], defaultZoomLevel: number, logo: string, title: string, name: string, defaultLocation: number[], storageConnectionString: string, featuresConnectionString: string, mapzenApiKey: string, fbToken: string, supportedLanguages: string[]}}} args
 * @returns {Promise.<{name: string, properties: {targetBBox: number[], defaultZoomLevel: number, logo: string, title: string, defaultLocation: number[], storageConnectionString: string, featuresConnectionString: string, mapzenApiKey: string, fbToken: string, supportedLanguages: string[]}}>}
 */
function createOrReplaceSite(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, pages: Array<{pageUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, pages: Array<{pageUrl: string, RowKey: string}>}>}
 */
function modifyFacebookPages(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, pages: Array<{pageUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, pages: Array<{pageUrl: string, RowKey: string}>}>}
 */
function removeFacebookPages(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{acctUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{pageUrl: string, RowKey: string}>}>}
 */
function modifyTrustedTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{acctUrl: string, RowKey: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{pageUrl: string, RowKey: string}>}>}
 */
function removeTrustedTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}>}
 */
function modifyTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}}} args
 * @returns {Promise.<{runTime: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}>}
 */
function removeTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, terms: Array<{RowKey: string, lang: string, filteredTerms: string[]}>}}} args
 * @returns {Promise.<{runTime: string, filters: Array<{filteredTerms: string[], lang: string, RowKey: string}>}>}
 */
function modifyBlacklist(args, res) { // eslint-disable-line no-unused-vars
}

/**
 * @param {{input: {site: string, terms: Array<{RowKey: string, lang: string, filteredTerms: string[]}>}}} args
 * @returns {Promise.<{runTime: string, filters: Array<{filteredTerms: string[], lang: string, RowKey: string}>}>}
 */
function removeBlacklist(args, res) { // eslint-disable-line no-unused-vars
  return new Promise((resolve, reject) => {
    if (!args.input) return reject('No input specified');
    if (!args.input.terms) return reject('No terms specified');
    if (!args.input.terms.length) return reject('No terms specified');
    const terms = args.input.terms;
    const params = [terms.map( t => { return t.RowKey; } )];
    const update = 'delete from fortis.blacklist where id in ?';
    cassandraConnector.executeQuery(update, params)
    .then(() => { resolve({ filters: args.input.terms }); })
    .catch(reject)
    ;
  });
}

module.exports = {
  createOrReplaceSite: createOrReplaceSite,
  modifyFacebookPages: withRunTime(modifyFacebookPages),
  removeFacebookPages: withRunTime(removeFacebookPages),
  modifyTrustedTwitterAccounts: withRunTime(modifyTrustedTwitterAccounts),
  removeTrustedTwitterAccounts: withRunTime(removeTrustedTwitterAccounts),
  modifyTwitterAccounts: withRunTime(modifyTwitterAccounts),
  removeTwitterAccounts: withRunTime(removeTwitterAccounts),
  modifyBlacklist: withRunTime(modifyBlacklist),
  removeBlacklist: withRunTime(removeBlacklist)
};
<|endoftext|>


<commit_before>/*global exports */
(function () {
  'use strict';
  function SessionNotFound(sid) {
    this.message = 'Session with session id ' + sid + ' not found.';
    var err = new Error(this.message);
    err.name = this.constructor.name;
    this.stack = err.stack;
  }
  SessionNotFound.prototype = new Error();

  function SessionExpired(sid) {
    this.message = 'Session with session id ' + sid + ' has expired.';
    var err = new Error(this.message);
    err.name = this.constructor.name;
    this.stack = err.stack;
  }
  SessionExpired.prototype = Object.create(SessionNotFound.prototype);

  exports.SessionNotFound = SessionNotFound;
  exports.SessionExpired = SessionExpired;
}());<commit_msg>Fixed session errors.<commit_after>/*global exports */
'use strict';
function SessionNotFound(sid) {
  this.message = 'Session with session id ' + sid + ' not found.';
  this.name = this.constructor.name;
  Error.captureStackTrace(this, SessionNotFound);
}
SessionNotFound.prototype = new Error();
SessionNotFound.prototype.constructor = SessionNotFound;

function SessionExpired(sid) {
  this.message = 'Session with session id ' + sid + ' has expired.';
  this.name = this.constructor.name;
  Error.captureStackTrace(this, SessionExpired);
}
SessionExpired.prototype = Object.create(SessionNotFound.prototype);
SessionExpired.prototype.constructor = SessionExpired;

exports.SessionNotFound = SessionNotFound;
exports.SessionExpired = SessionExpired;<|endoftext|>


<commit_before>'use strict'
/*
* Manages a security system
*/
const Base = require('./Base.js');
const http = require('http');

/*
* State object:

{
    managedSensors: { //The sensors this system in particular is responsible for.
        sensorId: {
            name: "Human readable sensor name"
            tripped: false,
            lastTripped: TIMESTAMP,
            state: {
                ... general state information ...
            }
        },
        ...
    },
    externalSensors: { //Devices managed by other applications, but with their state mirrored here
        sensorId: {
            ... sensor state ...
        }
    },
    armedState: "" // One of 'home', 'away', 'disarmed', or 'asleep'
    alertLevel: 0.1 // Between 0 and 1, recalculated every new sensor update depending on armedState.
    warningThreshold: 0.5 // Level the alert level should get to before a warning happens.
    dangerThreshold: 0.9 // Level the alert level should get to before the situation is dangerous.
    currentAlertState: "" // One of "disarmed," "safe", "warning", "danger"
}
*/
let SecuritySystem = class SecuritySystem extends Base {
  constructor(config) {
    config = Object.assign({
      port: 3033,
      warningThreshold: 0.5,
      dangerThreshold: 0.9
    }, config)

    super(config);

    var server = http.createServer(this.handleRequest.bind(this));
    var port = this._config.port
    server.listen(port, function(err) {
      if (err) {
        return console.log('Error: ', err);
      }

      console.log("Security System server listening on ", port);
    })
  }

  handleRequest(request, response) {
    var body = '';
    var self = this;
    request.on('data', function(chunk) {
      body += chunk;
    }).on('end', function() {
      if (body) {
        var data = JSON.parse(body);
        console.log("here");
        self.log(body);
        let stateUpdate = self._createManagedDeviceUpdateFromRequest(data);

        self.updateState(stateUpdate);
      }
    });

    response.end("Done");
  }

  /*
  * Expect data to be in the form:
  {
      "sensorId": "XXX",
      "sensorName": "Name",
      "tripped": boolean,
      "timestamp": timestamp,
      ...
  }
  */
  _createManagedDeviceUpdateFromRequest(data) {
      var overallStateUpdate = {};
      overallStateUpdate['managedSensors/' + data.sensorId + '/'] = data;
      return overallStateUpdate;
  }
}

module.exports = SecuritySystem;
<commit_msg>trying to get timestamp timezone right<commit_after>'use strict'
/*
* Manages a security system
*/
const Base = require('./Base.js');
const http = require('http');

/*
* State object:

{
    managedSensors: { //The sensors this system in particular is responsible for.
        sensorId: {
            name: "Human readable sensor name"
            tripped: false,
            lastTripped: TIMESTAMP,
            state: {
                ... general state information ...
            }
        },
        ...
    },
    externalSensors: { //Devices managed by other applications, but with their state mirrored here
        sensorId: {
            ... sensor state ...
        }
    },
    armedState: "" // One of 'home', 'away', 'disarmed', or 'asleep'
    alertLevel: 0.1 // Between 0 and 1, recalculated every new sensor update depending on armedState.
    warningThreshold: 0.5 // Level the alert level should get to before a warning happens.
    dangerThreshold: 0.9 // Level the alert level should get to before the situation is dangerous.
    currentAlertState: "" // One of "disarmed," "safe", "warning", "danger"
}
*/
let SecuritySystem = class SecuritySystem extends Base {
  constructor(config) {
    config = Object.assign({
      port: 3033,
      warningThreshold: 0.5,
      dangerThreshold: 0.9
    }, config)

    super(config);

    this.setState({
        warningThreshold: this._config.warningThreshold,
        dangerThreshold: this._config.dangerThreshold
    });

    var server = http.createServer(this.handleRequest.bind(this));
    var port = this._config.port
    server.listen(port, function(err) {
      if (err) {
        return console.log('Error: ', err);
      }

      console.log("Security System server listening on ", port);
    })
  }

  handleRequest(request, response) {
    var body = '';
    var self = this;
    request.on('data', function(chunk) {
      body += chunk;
    }).on('end', function() {
      if (body) {
        var data = JSON.parse(body);
        console.log("here");
        self.log(body);
        let stateUpdate = self._createManagedDeviceUpdateFromRequest(data);

        self.updateState(stateUpdate);
      }
    });

    response.end("Done");
  }

  /*
  * Expect data to be in the form:
  {
      "sensorId": "XXX",
      "sensorName": "Name",
      "tripped": boolean,
      "timestamp": timestamp,
      ...
  }
  */
  _createManagedDeviceUpdateFromRequest(data) {
      var overallStateUpdate = {};
      overallStateUpdate['managedSensors/' + data.sensorId + '/'] = data;
      return overallStateUpdate;
  }
}

module.exports = SecuritySystem;
<|endoftext|>


<commit_before>//Module to Export

module.exports = function () {
    /**
     * Get nearby assault creep, change as needed
     * @returns {*}
     */
    Creep.prototype.getNearByAssault =
        function (role = "assault") {
            return this.pos.findClosestByRange(FIND_MY_CREEPS, {
                filter: function (c) {
                    return c.memory.role == role;
                }
            });
        };
    /**
     * Get the closest creep
     * @returns {*}
     */
    Creep.prototype.getNearByCreep =
        function () {
            return this.pos.findClosestByRange(FIND_MY_CREEPS);
        };
    /**
     * Get nearby enemy creep, or specify a range and return more than one.
     * Also filtering out friendly creeps.
     * @param range
     * @returns {*}
     */
    Creep.prototype.getNearByEnemyCreep =
        function (range) {
            let distance = range || null;
            if (distance !== null) {
                return this.pos.findInRange(FIND_HOSTILE_CREEPS, range, Game.friendlyFilter());
            }
            return this.pos.findClosestByRange(FIND_HOSTILE_CREEPS, Game.friendlyFilter());
        };
    /**
     * Get closest enemy structure.
     * Also filtering friendly structures
     * @returns {*}
     */
    Creep.prototype.getNearByEnemyStructure =
        function () {
            return this.pos.findClosestByRange(FIND_HOSTILE_STRUCTURES, Game.friendlyFilter());
        };
    /**
     * Attack nearby enemy creep.
     * @param target
     */
    Creep.prototype.attackEnemyCreep =
        function (target = null) {
            let myTarget = target || this.getNearByEnemyCreep();
            if (myTarget) {
                if (myTarget.pos != this.pos) {
                    this.moveTo(myTarget.pos.x, myTarget.pos.y);
                } else {
                    this.attack(myTarget);
                }
            }

        };
    /**
     * Attack nearby enemy creep, or specific target.
     * Also move to the target if not with in range.
     * Todo: Need to get this to be a bit smarter. Unused at the moment.
     * @param target
     * @returns {boolean}
     */
    Creep.prototype.attackRangedEnemyCreep =
        function (target = null) {
            let myTarget = target || this.getNearByEnemyCreep();
            if (myTarget) {
                if (myTarget.pos != this.pos) {
                    this.moveTo(myTarget.pos.x, myTarget.pos.y);
                } else {
                    this.rangedAttack(myTarget);
                }
                return true;
            }
            return false;
        };
    /**
     * Attack enemy structure, filtering out friendly structures.
     * @param target
     */
    Creep.prototype.attackEnemyStructure =
        function (target = null) {
            let myTarget = target || this.getNearByEnemyStructure();
            if (myTarget.pos != this.pos) {
                this.moveTo(myTarget.pos.x, myTarget.pos.y);
            } else {
                this.attack(myTarget);
            }

        };
    /**
     * Move creep to flag specified. Change as needed.
     * @param flag
     * @returns {boolean}
     */
    Creep.prototype.moveToFlaggedRoom =
        function (flag) {
            if (flag && flag.pos) {
                /*let creeps = _.filter(flag.room.lookForAt(LOOK_CREEPS,flag.pos), function(c){return !c.my});
                 let struct = _.filter(flag.room.lookForAt(LOOK_STRUCTURES,flag.pos), function(c){return !c.my});

                 if(creeps.length > 1){
                 return false;
                 }*/
                if (flag.pos.roomName != this.pos.roomName) {
                    this.moveTo(flag.pos, {ignoreCreeps: true, ignoreRoads: true}); //, {ignoreCreeps: true}
                    return true;
                } else {
                    //this.moveTo(flag.pos, {ignoreCreeps: true, ignoreRoads: true});
                    //this.moveTo(flag.pos, {ignoreCreeps: true, reusePath: 1, ignoreRoads: true});
                    this.moveTo(flag.pos, {reusePath: 1, ignoreRoads: true});
                    return true;
                }
            }
            return false;
        };
    /**
     * Dump our mineral at the terminal.
     * @returns {boolean}
     */
    Creep.prototype.dumpAtTerminal =
        function () {
            let mineral = this.room.getMineral();

            if (_.sum(this.carry) === 0) {
                //console.log("Not carrying anything");
                this.memory.refillingTerminal = false;
                return false;
            }
            if (!this.memory.refillingTerminal) {
                //console.log("Not filling Terminal");
                return false;
            }

            if (this.room.terminal && this.room.terminal.store[mineral.mineralType] > 0) {
                if (this.room.terminal.transfer(this, mineral.mineralType) != OK) {
                    this.moveTo(this.room.terminal);
                }
                return true;

            }

            var storage = this.room.getStorage();

            var transferMessage = this.transfer(storage, mineral.mineralType);
            if (transferMessage == ERR_NOT_IN_RANGE) {
                this.moveTo(storage);
            }
        };
    /**
     * Collect mineral from storage.
     * Todo: use the deposit from prototype.room.js
     * @returns {boolean}
     */
    Creep.prototype.collectMineralFromStorage =
        function () {
            let mineral = this.room.getMineral();

            if(this.carry[mineral.mineralType] === 0 && this.room.storage.store[mineral.mineralType] > 0){
                if(!this.pos.inRangeTo(this.room.storage.pos, 1)){
                    this.moveTo(this.room.storage);
                    this.memory.refillingTerminal = true;
                    return true;
                }else{
                    this.room.withdrawResource(this, mineral.mineralType);
                    this.memory.refillingTerminal = true;
                    return true;
                }
            }
            //this.memory.refillingTerminal = false;
            return false;
        };
    /**
     * Get this creeps home.
     * @returns {*}
     */
    Creep.prototype.getHome =
        function () {
            return Game.getObjectById(this.memory.home);
        };
    /**
     * Collect energy from storage.
     * Todo: use the withdraw from prototype.room.js
     * @param ignoreRoomStorage
     * @returns {boolean}
     */
    Creep.prototype.collectEnergyFromStorage =
        function (ignoreRoomStorage) {
            var home = this.getHome();
            if (this.carry.energy !== 0) {
                return false;
            }
            var homeLink = home.pos.findClosestByRange(FIND_MY_STRUCTURES, {
                filter: function (structure) {
                    return structure.structureType == STRUCTURE_LINK;
                }
            });
            if (homeLink && homeLink.energy > 0) {
                if (homeLink.pos.getRangeTo(this) > 1) {
                    this.moveTo(homeLink);
                }
                else {
                    let tMessage = homeLink.transferEnergy(this);
                    if (tMessage == OK) {
                        let dropOffEnergy = _.sum(this.carry);
                        this.room.saveUsedEnergy(dropOffEnergy);
                    }
                }
                return true;
            }

            var nearestContainer = this.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: function (structure) {
                    if (structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] > 0) {
                        return true;
                    }
                }
            });

            if (nearestContainer !== null) {
                if (nearestContainer.transfer(this, RESOURCE_ENERGY) != OK) {
                    this.moveTo(nearestContainer);
                }
                return true;
            }

            /*        if (this.room.terminal && this.room.terminal.store[RESOURCE_ENERGY] > 0) {
             if (this.room.terminal.transfer(this, RESOURCE_ENERGY) != OK) {
             this.moveTo(this.room.terminal);
             }
             return true;

             }*/

            if (!ignoreRoomStorage && this.room.storage) {
                let withdrawMessage = this.room.withdrawResource(this, RESOURCE_ENERGY);
                if (withdrawMessage != OK) {
                    this.moveTo(this.room.storage);
                }
                return true;
            }
        };
    /**
     * Collect energy from a container or link.
     * @returns {boolean}
     */
    Creep.prototype.collectEnergyFromDump =
        function () {

            let nearestContainer = this.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: function (structure) {
                    if (structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] > 100) {
                        return true;
                    }
                }
            });

            let nearestLink = this.room.storage.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: function (structure) {
                    if ((structure.structureType == STRUCTURE_LINK) /*&& (structure.energy >= 0)*/) {
                        return true;
                    }
                }
            });

            if (nearestContainer && nearestLink && this.pos.getRangeTo(nearestContainer) < this.pos.getRangeTo(nearestLink) && !Memory.workingLinks[nearestLink.id]) {

                let message = nearestContainer.transfer(this, RESOURCE_ENERGY);
                //console.log(message + ":" + this.name);
                if (message == ERR_NOT_IN_RANGE) {
                    this.moveTo(nearestContainer);
                }

                this.memory.refillingStorage = true;
                return true;
            }

            if (nearestLink || nearestContainer) {
                this.memory.refillingStorage = true;
            }

            if (this.carry.energy !== 0) {
                return false;
            }

            if (nearestLink && nearestLink.energy > 0) {
                let transferMessage = nearestLink.transferEnergy(this);
                //console.log(transferMessage + ":" + this.name);
                if (transferMessage == ERR_NOT_IN_RANGE) {
                    this.moveTo(nearestLink);
                }
                Memory.workingLinks[nearestLink.id] = true;
                return true;
            }
            if (nearestContainer) {
                if (nearestContainer.transfer(this, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    this.moveTo(nearestContainer);
                }
                return true;
            }
            this.memory.refillingStorage = false;

            return false;
        };
    /**
     * Deposit energy into the storage.
     * Todo: use the deposit from prototype.room.js
     * @returns {boolean}
     */
    Creep.prototype.dumpEnergyAtStorage =
        function () {
            if (this.carry.energy === 0) {
                return false;
            }
            if (!this.memory.refillingStorage) {
                return false;
            }

            if (_.sum(this.room.storage.store) < this.room.storage.storeCapacity) {
                let transferMessage = this.room.depositResource(this, RESOURCE_ENERGY);
                //console.log(transferMessage + ": " + this.name);
                if (transferMessage == ERR_NOT_IN_RANGE) {
                    this.moveTo(this.room.storage);
                }
            }
        };
    /**
     * Save our last position in the our memory.
     */
    Creep.prototype.setLastPosition =
        function () {
            this.memory.lastPosition = this.pos;
        };
    /**
     * Return if re have moved.
     * @returns {boolean}
     */
    Creep.prototype.didWeMove =
        function () {
            return this.memory.lastPosition == this.pos;
        };
    /**
     * Find my nearby creeps.
     * Used for navigating around another creep.
     * @returns {Array}
     */
    Creep.prototype.findMyNearByCreeps =
        function () {
            return _.filter(this.pos.findInRange(this.pos, 1, FIND_MY_CREEPS),
                function (c) {
                    return c.id != this.id;
                }
            );
        };
    /**
     * Move around another creep if we haven't moved.
     * Todo: get this working.
     *
     * Work in progress. Untested!!!
     *
     * @param pos
     * @returns {*}
     */
    Creep.prototype.moveMe =
        function (pos) {
            let statusMoved = this.moveTo(pos);
            if (statusMoved == OK) {
                this.setLastPosition();
            } else {
                if (this.didWeMove()) {
                    let nextPos = this.getNextPathPos();
                    let creepNotMoved = _.filter(this.findMyNearByCreeps(),
                        function (c) {
                            return c.pos == nextPos;
                        }
                    );
                    creepNotMoved.moveTo(this.pos);
                    statusMoved = this.moveTo(creepNotMoved);
                }
            }
            return statusMoved;
        };
};<commit_msg>Added todo for getNearByCreep function<commit_after>//Module to Export

module.exports = function () {
    /**
     * Get nearby assault creep, change as needed
     * @returns {*}
     */
    Creep.prototype.getNearByAssault =
        function (role = "assault") {
            return this.pos.findClosestByRange(FIND_MY_CREEPS, {
                filter: function (c) {
                    return c.memory.role == role;
                }
            });
        };
    /**
     * Get the closest creep
     * @returns {*}
     */
    Creep.prototype.getNearByCreep =
        function () {
            // TODO make this either exclude the 'this' creep or do something else.
            return this.pos.findClosestByRange(FIND_MY_CREEPS);
        };
    /**
     * Get nearby enemy creep, or specify a range and return more than one.
     * Also filtering out friendly creeps.
     * @param range
     * @returns {*}
     */
    Creep.prototype.getNearByEnemyCreep =
        function (range) {
            let distance = range || null;
            if (distance !== null) {
                return this.pos.findInRange(FIND_HOSTILE_CREEPS, range, Game.friendlyFilter());
            }
            return this.pos.findClosestByRange(FIND_HOSTILE_CREEPS, Game.friendlyFilter());
        };
    /**
     * Get closest enemy structure.
     * Also filtering friendly structures
     * @returns {*}
     */
    Creep.prototype.getNearByEnemyStructure =
        function () {
            return this.pos.findClosestByRange(FIND_HOSTILE_STRUCTURES, Game.friendlyFilter());
        };
    /**
     * Attack nearby enemy creep.
     * @param target
     */
    Creep.prototype.attackEnemyCreep =
        function (target = null) {
            let myTarget = target || this.getNearByEnemyCreep();
            if (myTarget) {
                if (myTarget.pos != this.pos) {
                    this.moveTo(myTarget.pos.x, myTarget.pos.y);
                } else {
                    this.attack(myTarget);
                }
            }

        };
    /**
     * Attack nearby enemy creep, or specific target.
     * Also move to the target if not with in range.
     * Todo: Need to get this to be a bit smarter. Unused at the moment.
     * @param target
     * @returns {boolean}
     */
    Creep.prototype.attackRangedEnemyCreep =
        function (target = null) {
            let myTarget = target || this.getNearByEnemyCreep();
            if (myTarget) {
                if (myTarget.pos != this.pos) {
                    this.moveTo(myTarget.pos.x, myTarget.pos.y);
                } else {
                    this.rangedAttack(myTarget);
                }
                return true;
            }
            return false;
        };
    /**
     * Attack enemy structure, filtering out friendly structures.
     * @param target
     */
    Creep.prototype.attackEnemyStructure =
        function (target = null) {
            let myTarget = target || this.getNearByEnemyStructure();
            if (myTarget.pos != this.pos) {
                this.moveTo(myTarget.pos.x, myTarget.pos.y);
            } else {
                this.attack(myTarget);
            }

        };
    /**
     * Move creep to flag specified. Change as needed.
     * @param flag
     * @returns {boolean}
     */
    Creep.prototype.moveToFlaggedRoom =
        function (flag) {
            if (flag && flag.pos) {
                /*let creeps = _.filter(flag.room.lookForAt(LOOK_CREEPS,flag.pos), function(c){return !c.my});
                 let struct = _.filter(flag.room.lookForAt(LOOK_STRUCTURES,flag.pos), function(c){return !c.my});

                 if(creeps.length > 1){
                 return false;
                 }*/
                if (flag.pos.roomName != this.pos.roomName) {
                    this.moveTo(flag.pos, {ignoreCreeps: true, ignoreRoads: true}); //, {ignoreCreeps: true}
                    return true;
                } else {
                    //this.moveTo(flag.pos, {ignoreCreeps: true, ignoreRoads: true});
                    //this.moveTo(flag.pos, {ignoreCreeps: true, reusePath: 1, ignoreRoads: true});
                    this.moveTo(flag.pos, {reusePath: 1, ignoreRoads: true});
                    return true;
                }
            }
            return false;
        };
    /**
     * Dump our mineral at the terminal.
     * @returns {boolean}
     */
    Creep.prototype.dumpAtTerminal =
        function () {
            let mineral = this.room.getMineral();

            if (_.sum(this.carry) === 0) {
                //console.log("Not carrying anything");
                this.memory.refillingTerminal = false;
                return false;
            }
            if (!this.memory.refillingTerminal) {
                //console.log("Not filling Terminal");
                return false;
            }

            if (this.room.terminal && this.room.terminal.store[mineral.mineralType] > 0) {
                if (this.room.terminal.transfer(this, mineral.mineralType) != OK) {
                    this.moveTo(this.room.terminal);
                }
                return true;

            }

            var storage = this.room.getStorage();

            var transferMessage = this.transfer(storage, mineral.mineralType);
            if (transferMessage == ERR_NOT_IN_RANGE) {
                this.moveTo(storage);
            }
        };
    /**
     * Collect mineral from storage.
     * Todo: use the deposit from prototype.room.js
     * @returns {boolean}
     */
    Creep.prototype.collectMineralFromStorage =
        function () {
            let mineral = this.room.getMineral();

            if(this.carry[mineral.mineralType] === 0 && this.room.storage.store[mineral.mineralType] > 0){
                if(!this.pos.inRangeTo(this.room.storage.pos, 1)){
                    this.moveTo(this.room.storage);
                    this.memory.refillingTerminal = true;
                    return true;
                }else{
                    this.room.withdrawResource(this, mineral.mineralType);
                    this.memory.refillingTerminal = true;
                    return true;
                }
            }
            //this.memory.refillingTerminal = false;
            return false;
        };
    /**
     * Get this creeps home.
     * @returns {*}
     */
    Creep.prototype.getHome =
        function () {
            return Game.getObjectById(this.memory.home);
        };
    /**
     * Collect energy from storage.
     * Todo: use the withdraw from prototype.room.js
     * @param ignoreRoomStorage
     * @returns {boolean}
     */
    Creep.prototype.collectEnergyFromStorage =
        function (ignoreRoomStorage) {
            var home = this.getHome();
            if (this.carry.energy !== 0) {
                return false;
            }
            var homeLink = home.pos.findClosestByRange(FIND_MY_STRUCTURES, {
                filter: function (structure) {
                    return structure.structureType == STRUCTURE_LINK;
                }
            });
            if (homeLink && homeLink.energy > 0) {
                if (homeLink.pos.getRangeTo(this) > 1) {
                    this.moveTo(homeLink);
                }
                else {
                    let tMessage = homeLink.transferEnergy(this);
                    if (tMessage == OK) {
                        let dropOffEnergy = _.sum(this.carry);
                        this.room.saveUsedEnergy(dropOffEnergy);
                    }
                }
                return true;
            }

            var nearestContainer = this.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: function (structure) {
                    if (structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] > 0) {
                        return true;
                    }
                }
            });

            if (nearestContainer !== null) {
                if (nearestContainer.transfer(this, RESOURCE_ENERGY) != OK) {
                    this.moveTo(nearestContainer);
                }
                return true;
            }

            /*        if (this.room.terminal && this.room.terminal.store[RESOURCE_ENERGY] > 0) {
             if (this.room.terminal.transfer(this, RESOURCE_ENERGY) != OK) {
             this.moveTo(this.room.terminal);
             }
             return true;

             }*/

            if (!ignoreRoomStorage && this.room.storage) {
                let withdrawMessage = this.room.withdrawResource(this, RESOURCE_ENERGY);
                if (withdrawMessage != OK) {
                    this.moveTo(this.room.storage);
                }
                return true;
            }
        };
    /**
     * Collect energy from a container or link.
     * @returns {boolean}
     */
    Creep.prototype.collectEnergyFromDump =
        function () {

            let nearestContainer = this.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: function (structure) {
                    if (structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] > 100) {
                        return true;
                    }
                }
            });

            let nearestLink = this.room.storage.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: function (structure) {
                    if ((structure.structureType == STRUCTURE_LINK) /*&& (structure.energy >= 0)*/) {
                        return true;
                    }
                }
            });

            if (nearestContainer && nearestLink && this.pos.getRangeTo(nearestContainer) < this.pos.getRangeTo(nearestLink) && !Memory.workingLinks[nearestLink.id]) {

                let message = nearestContainer.transfer(this, RESOURCE_ENERGY);
                //console.log(message + ":" + this.name);
                if (message == ERR_NOT_IN_RANGE) {
                    this.moveTo(nearestContainer);
                }

                this.memory.refillingStorage = true;
                return true;
            }

            if (nearestLink || nearestContainer) {
                this.memory.refillingStorage = true;
            }

            if (this.carry.energy !== 0) {
                return false;
            }

            if (nearestLink && nearestLink.energy > 0) {
                let transferMessage = nearestLink.transferEnergy(this);
                //console.log(transferMessage + ":" + this.name);
                if (transferMessage == ERR_NOT_IN_RANGE) {
                    this.moveTo(nearestLink);
                }
                Memory.workingLinks[nearestLink.id] = true;
                return true;
            }
            if (nearestContainer) {
                if (nearestContainer.transfer(this, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    this.moveTo(nearestContainer);
                }
                return true;
            }
            this.memory.refillingStorage = false;

            return false;
        };
    /**
     * Deposit energy into the storage.
     * Todo: use the deposit from prototype.room.js
     * @returns {boolean}
     */
    Creep.prototype.dumpEnergyAtStorage =
        function () {
            if (this.carry.energy === 0) {
                return false;
            }
            if (!this.memory.refillingStorage) {
                return false;
            }

            if (_.sum(this.room.storage.store) < this.room.storage.storeCapacity) {
                let transferMessage = this.room.depositResource(this, RESOURCE_ENERGY);
                //console.log(transferMessage + ": " + this.name);
                if (transferMessage == ERR_NOT_IN_RANGE) {
                    this.moveTo(this.room.storage);
                }
            }
        };
    /**
     * Save our last position in the our memory.
     */
    Creep.prototype.setLastPosition =
        function () {
            this.memory.lastPosition = this.pos;
        };
    /**
     * Return if re have moved.
     * @returns {boolean}
     */
    Creep.prototype.didWeMove =
        function () {
            return this.memory.lastPosition == this.pos;
        };
    /**
     * Find my nearby creeps.
     * Used for navigating around another creep.
     * @returns {Array}
     */
    Creep.prototype.findMyNearByCreeps =
        function () {
            return _.filter(this.pos.findInRange(this.pos, 1, FIND_MY_CREEPS),
                function (c) {
                    return c.id != this.id;
                }
            );
        };
    /**
     * Move around another creep if we haven't moved.
     * Todo: get this working.
     *
     * Work in progress. Untested!!!
     *
     * @param pos
     * @returns {*}
     */
    Creep.prototype.moveMe =
        function (pos) {
            let statusMoved = this.moveTo(pos);
            if (statusMoved == OK) {
                this.setLastPosition();
            } else {
                if (this.didWeMove()) {
                    let nextPos = this.getNextPathPos();
                    let creepNotMoved = _.filter(this.findMyNearByCreeps(),
                        function (c) {
                            return c.pos == nextPos;
                        }
                    );
                    creepNotMoved.moveTo(this.pos);
                    statusMoved = this.moveTo(creepNotMoved);
                }
            }
            return statusMoved;
        };
};
<|endoftext|>


<commit_before>/* jshint strict: false, sub: true */
/* global print */
'use strict';

////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2018 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2018, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

const functionsDocumentation = {
  'wal_cleanup': 'wal file cleanup tests'
};

const _ = require('lodash');
const tu = require('@arangodb/testutils/test-utils');

// const BLUE = require('internal').COLORS.COLOR_BLUE;
const CYAN = require('internal').COLORS.COLOR_CYAN;
// const GREEN = require('internal').COLORS.COLOR_GREEN;
const RED = require('internal').COLORS.COLOR_RED;
const RESET = require('internal').COLORS.COLOR_RESET;
// const YELLOW = require('internal').COLORS.COLOR_YELLOW;

const download = require('internal').download;

const testPaths = {
  'walCleanup': [tu.pathForTesting('client/wal_cleanup')]
};

////////////////////////////////////////////////////////////////////////////////
/// @brief TEST: wal cleanup
////////////////////////////////////////////////////////////////////////////////

function walCleanup (options) {
  print(CYAN + 'WAL cleanup tests...' + RESET);
  let testCases = tu.scanTestPaths(testPaths.walCleanup, options);

  let opts = _.clone(options);
  opts.extraArgs['rocksdb.wal-file-timeout-initial'] = '3';
  opts.cluster = true;

  let rc = tu.performTests(opts, testCases, 'wal_cleanup', tu.runInArangosh, {
    'server.authentication': 'false',
    'rocksdb.wal-file-timeout-initial': '3'
  });
  options.cleanup = options.cleanup && opts.cleanup;
  return rc;
}

exports.setup = function (testFns, defaultFns, opts, fnDocs, optionsDoc, allTestPaths) {
  Object.assign(allTestPaths, testPaths);
  testFns['wal_cleanup'] = walCleanup;

  defaultFns.push('wal_cleanup');

  for (var attrname in functionsDocumentation) { fnDocs[attrname] = functionsDocumentation[attrname]; }
};
<commit_msg>adjust testsuite to new invocation mechanisms (#16352)<commit_after>/* jshint strict: false, sub: true */
/* global print */
'use strict';

////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2018 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2018, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

const functionsDocumentation = {
  'wal_cleanup': 'wal file cleanup tests'
};

const _ = require('lodash');
const tu = require('@arangodb/testutils/test-utils');

// const BLUE = require('internal').COLORS.COLOR_BLUE;
const CYAN = require('internal').COLORS.COLOR_CYAN;
// const GREEN = require('internal').COLORS.COLOR_GREEN;
const RED = require('internal').COLORS.COLOR_RED;
const RESET = require('internal').COLORS.COLOR_RESET;
// const YELLOW = require('internal').COLORS.COLOR_YELLOW;

const download = require('internal').download;

const testPaths = {
  'wal_cleanup': [tu.pathForTesting('client/wal_cleanup')]
};

////////////////////////////////////////////////////////////////////////////////
/// @brief TEST: wal cleanup
////////////////////////////////////////////////////////////////////////////////

function walCleanup (options) {
  print(CYAN + 'WAL cleanup tests...' + RESET);
  let testCases = tu.scanTestPaths(testPaths.wal_cleanup, options);

  let opts = _.clone(options);
  opts.extraArgs['rocksdb.wal-file-timeout-initial'] = '3';
  opts.cluster = true;

  let rc = new tu.runInArangoshRunner(opts,
                                      'wal_cleanup', {
                                        'server.authentication': 'false',
                                        'rocksdb.wal-file-timeout-initial': '3'
                                      }).run(testCases);
  options.cleanup = options.cleanup && opts.cleanup;
  return rc;
}

exports.setup = function (testFns, defaultFns, opts, fnDocs, optionsDoc, allTestPaths) {
  Object.assign(allTestPaths, testPaths);
  testFns['wal_cleanup'] = walCleanup;

  defaultFns.push('wal_cleanup');

  for (var attrname in functionsDocumentation) { fnDocs[attrname] = functionsDocumentation[attrname]; }
};
<|endoftext|>


<commit_before>'use strict';

const apiResult = require('../../../helpers/apiResult');
const applicationsAsync = require('../../../helpers/collections').applications;

exports.get = async (request, extensions, config) => {
	const applications = await applicationsAsync(config);

	const applicationDoc = await applications.findIdAsync(request.params.id);

	if (applicationDoc == null)
		return apiResult(400, 'application is not found');

	// 対象アプリケーションの所有者かどうかをチェック
	if (applicationDoc.document.creatorId.toString() !== request.user._id.toString())
		return apiResult(400, 'you do not own this application');

	if (applicationDoc.document.keyCode == null)
		return apiResult(400, 'application_key has not been generated yet');

	const key = await applicationDoc.getApplicationKeyAsync();

	return apiResult(200, 'success', {'application_key': key});
};

exports.post = async (request, extensions, config) => {
	const applications = await applicationsAsync(config);

	const applicationDoc = await applications.findIdAsync(request.params.id);

	if (applicationDoc == null)
		return apiResult(400, 'application is not found');

	// 対象アプリケーションの所有者かどうかをチェック
	if (applicationDoc.document.creatorId.toString() !== request.user._id.toString())
		return apiResult(400, 'you do not own this application');

	const key = await applicationDoc.generateApplicationKeyAsync();

	return apiResult(200, 'success', {'application_key': key});
};
<commit_msg>fix comment<commit_after>'use strict';

const apiResult = require('../../../helpers/apiResult');
const applicationsAsync = require('../../../helpers/collections').applications;

exports.get = async (request, extensions, config) => {
	const applications = await applicationsAsync(config);

	const applicationDoc = await applications.findIdAsync(request.params.id);

	if (applicationDoc == null)
		return apiResult(400, 'application is not found');

	// 対象アプリケーションの所有者かどうか
	if (applicationDoc.document.creatorId.toString() !== request.user._id.toString())
		return apiResult(400, 'you do not own this application');

	if (applicationDoc.document.keyCode == null)
		return apiResult(400, 'application_key has not been generated yet');

	const key = await applicationDoc.getApplicationKeyAsync();

	return apiResult(200, 'success', {'application_key': key});
};

exports.post = async (request, extensions, config) => {
	const applications = await applicationsAsync(config);

	const applicationDoc = await applications.findIdAsync(request.params.id);

	if (applicationDoc == null)
		return apiResult(400, 'application is not found');

	// 対象アプリケーションの所有者かどうか
	if (applicationDoc.document.creatorId.toString() !== request.user._id.toString())
		return apiResult(400, 'you do not own this application');

	const key = await applicationDoc.generateApplicationKeyAsync();

	return apiResult(200, 'success', {'application_key': key});
};
<|endoftext|>


<commit_before>$('body').scrollspy({
    target: '.bs-docs-sidebar',
    offset: 40
});
<commit_msg>Add JS char counter for Tweet content<commit_after>$('body').scrollspy({
    target: '.bs-docs-sidebar',
    offset: 40
});

a https://wiki.selfhtml.org/wiki/JavaScript/Objekte/RegExp https://encrypted.google.com/search?hl=de&q=javascript%20regex%20whitespace%20slash%20match

Ein Text mit einem Link und 28 Zeichen delta http://without-systemd.org/wiki/index.php/Main_Page wird richtig berechnet nehme ich an. Aber wird er auch korrekt abgeschnitten?
Ein Text mit einem Link und 28 Zeichen delta ....................... wird richtig berechnet nehme ich an. Aber wird er auch korrekt abgeschnitten?

if ($('textarea#content').length > 0) {
	var regex = new RegExp('https?://[^\\s]*', 'g');
	var subst = new Array(24).join('.');

	$('label[for="content"]').append('
(0 of 140 chars)
');

	$('textarea#content').on('input propertychange', function() {
		var content = $(this).val().replace(regex, subst);
		var length = $(this).val().length - content.length;

		$(this).val($(this).val().substring(0, 140 + length));
		$('span#charcount').html($(this).val().replace(regex, subst).length);
	});
}
<|endoftext|>


<commit_before>module.exports = function () {
    StructureSpawn.prototype.createCustomCreep =
    function(energy, roleName) {
        var numberOfParts = Math.floor(energy / 350);
        var body = [];
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
        return this.createCreep(body, undefined, {role: roleName, working: false });
    };

};
<commit_msg>WORK WORK CARRY MOVE MOVE MOVE<commit_after>module.exports = function () {
    StructureSpawn.prototype.createCustomCreep =
    function(energy, roleName) {
        var numberOfParts = Math.floor(energy / 350);
        var body = [];
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
        return this.createCreep(body, undefined, {role: roleName, working: false });
    };

};
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Custom bindings for the Bluetooth API.

var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();
var sendRequest = require('sendRequest').sendRequest;

// Use custom bindings to create an undocumented event listener that will
// receive events about device discovery and call the event listener that was
// provided with the request to begin discovery.
chromeHidden.registerCustomHook('experimental.bluetooth', function(api) {
  var apiFunctions = api.apiFunctions;

  chromeHidden.bluetooth = {};
  chromeHidden.bluetooth.handler = null;
  chromeHidden.bluetooth.onDeviceDiscovered =
      new chrome.Event("experimental.bluetooth.onDeviceDiscovered");

  function deviceDiscoveredListener(device) {
    if (chromeHidden.bluetooth.handler != null)
      chromeHidden.bluetooth.handler(device);
  }
  chromeHidden.bluetooth.onDeviceDiscovered.addListener(
      deviceDiscoveredListener);

  apiFunctions.setHandleRequest('startDiscovery', function() {
    var args = arguments;
    if (args.length > 0 && args[0] && args[0].deviceCallback) {
      chromeHidden.bluetooth.handler = args[0].deviceCallback;
    }
    sendRequest(this.name, args, this.definition.parameters);
  });
  apiFunctions.setHandleRequest('stopDiscovery', function() {
    chromeHidden.bluetooth.handler = null;
    sendRequest(this.name, args, this.definition.parameters);
  });
});
<commit_msg>Fix a misnamed parameter.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Custom bindings for the Bluetooth API.

var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();
var sendRequest = require('sendRequest').sendRequest;

// Use custom bindings to create an undocumented event listener that will
// receive events about device discovery and call the event listener that was
// provided with the request to begin discovery.
chromeHidden.registerCustomHook('experimental.bluetooth', function(api) {
  var apiFunctions = api.apiFunctions;

  chromeHidden.bluetooth = {};
  chromeHidden.bluetooth.handler = null;
  chromeHidden.bluetooth.onDeviceDiscovered =
      new chrome.Event("experimental.bluetooth.onDeviceDiscovered");

  function deviceDiscoveredListener(device) {
    if (chromeHidden.bluetooth.handler != null)
      chromeHidden.bluetooth.handler(device);
  }
  chromeHidden.bluetooth.onDeviceDiscovered.addListener(
      deviceDiscoveredListener);

  apiFunctions.setHandleRequest('startDiscovery', function() {
    var args = arguments;
    if (args.length > 0 && args[0] && args[0].deviceCallback) {
      chromeHidden.bluetooth.handler = args[0].deviceCallback;
    }
    sendRequest(this.name, args, this.definition.parameters);
  });
  apiFunctions.setHandleRequest('stopDiscovery', function() {
    chromeHidden.bluetooth.handler = null;
    sendRequest(this.name, arguments, this.definition.parameters);
  });
});
<|endoftext|>


<commit_before>import _ from 'lodash';

export default class User {
  constructor(obj) {
    if (this.invalidArguments(obj)) return;
    this._id = obj.id;
    this._email = obj.email;
    this._token = obj.token;
    this.store();
  }

  store() {
    const obj = {
      id: this._id,
      email: this._email,
      token: this._token,
    };
    localStorage.setItem('user', JSON.stringify(obj));
  }

  restore() {
    const anyJson = localStorage.getItem('user');
    if (!anyJson) return;
    const obj = JSON.parse(anyJson);
    this._id = _.get(obj, 'id', null);
    this._email = _.get(obj, 'email', null);
    this._token = _.get(obj, 'token', null);
    return this;
  }

  invalidArguments(obj) {
    const id = _.get(obj, 'id', null);
    const email = _.get(obj, 'email', null);
    const token = _.get(obj, 'token', null);
    return _.isNil(id) || _.isNil(email) || _.isNil(token);
  }

  get id() {
    return this._id;
  }

  get email() {
    return this._email;
  }

  get token() {
    return this._token;
  }

  static currentUserToken() {
    const anyJson = localStorage.getItem('user');
    if (!anyJson) return null;
    const obj = JSON.parse(anyJson);
    return _.get(obj, 'token', null);
  }
}
<commit_msg>Refactoring<commit_after>import _ from 'lodash';

const invalidArguments = obj => {
  const id = _.get(obj, 'id', null);
  const email = _.get(obj, 'email', null);
  const token = _.get(obj, 'token', null);
  return _.isNil(id) || _.isNil(email) || _.isNil(token);
};

export default class User {
  constructor(obj) {
    if (invalidArguments(obj)) return;
    this._id = obj.id;
    this._email = obj.email;
    this._token = obj.token;
    this.store();
  }

  store() {
    const obj = {
      id: this._id,
      email: this._email,
      token: this._token,
    };
    localStorage.setItem('user', JSON.stringify(obj));
  }

  restore() {
    const anyJson = localStorage.getItem('user');
    if (!anyJson) return;
    const obj = JSON.parse(anyJson);
    this._id = _.get(obj, 'id', null);
    this._email = _.get(obj, 'email', null);
    this._token = _.get(obj, 'token', null);
    return this;
  }

  get id() {
    return this._id;
  }

  get email() {
    return this._email;
  }

  get token() {
    return this._token;
  }

  static currentUserToken() {
    const anyJson = localStorage.getItem('user');
    if (!anyJson) return null;
    const obj = JSON.parse(anyJson);
    return _.get(obj, 'token', null);
  }
}
<|endoftext|>