<commit_before>/* ----------- GLOBAL VARIABLES --------------- */

var CURRENT_LIFES = 5;      // number of current lifes
var CURRENT_KEYS = 0;       // number of current keys
var HAS_BLUE_GEM = true;    // has picked the blue gem
var HAS_GREEN_GEM = true;   // has picked the green gem
var CURRENT_LEVEL = 1;      // level of the screen

// Put the variables on screen in the menu
document.getElementById('numberLifes').innerHTML = CURRENT_LIFES.toString();
document.getElementById('numberKeys').innerHTML = CURRENT_KEYS.toString();
document.getElementById('numberLevel').innerHTML = CURRENT_LEVEL.toString();
if (HAS_BLUE_GEM) {
    document.getElementById('hasGems').innerHTML += "";
}
if (HAS_GREEN_GEM) {
    document.getElementById('hasGems').innerHTML += "";
}

/* -------------- OBSTACLES & ITEMS ---------------- */

// Implement the Items class, with the stuff to pick up
var Items = function(x,y,sprite,item) {
    this.x = x;
    this.y = y;
    this.sprite = 'images/' + sprite + '.png';
    this.item = item;
}
// Draw the items on the screen
Items.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

if (CURRENT_LEVEL === 1) {

    /* --------- LEVEL 1 CANVAS ------------ */

    // Build the house, put the trees and the rocks
    var allObstacles = [];
    allObstacles[0] = new Items(303, 45, 'window-tall', 'house');
    allObstacles[1] = new Items(404, 60, 'door-tall-closed', 'door');
    allObstacles[2] = new Items(505, 45, 'window-tall', 'house');
    allObstacles[3] = new Items(303, -40, 'roof-south-west', 'house');
    allObstacles[4] = new Items(404, -40, 'roof-south', 'house');
    allObstacles[5] = new Items(505, -40, 'roof-south-east', 'house');

    allObstacles[6] = new Items(101, 224, 'tree-ugly', 'house');
    allObstacles[7] = new Items(303, 307, 'tree-ugly', 'house');
    allObstacles[8] = new Items(606, 141, 'tree-ugly', 'house');
    allObstacles[9] = new Items(606, 224, 'tree-ugly', 'house');
    allObstacles[10] = new Items(0, -25, 'tree-short', 'house');
    allObstacles[11] = new Items(101, -25, 'tree-short', 'house');
    allObstacles[12] = new Items(202, -25, 'tree-short', 'house');
    allObstacles[13] = new Items(606, -25, 'tree-short', 'house');
    allObstacles[14] = new Items(707, -25, 'tree-short', 'house');
    allObstacles[15] = new Items(808, -25, 'tree-short', 'house');

    allObstacles[16] = new Items(505, 470, 'rock', 'house');
    allObstacles[17] = new Items(707, 224, 'rock', 'house');

    // Create the items
    var allItems = [];
    allItems[0] = new Items(707, 131, 'key', 'key');
    allItems[1] = new Items(101, 131, 'key', 'key');
    allItems[2] = new Items(0, 465, 'heart', 'life');

} else if (CURRENT_LEVEL === 2) {

    /* --------- LEVEL 2 CANVAS ------------ */

    // Build the house, put the trees and the rocks
    var allObstacles = [];
    allObstacles[0] = new Items(0, 45, 'wood-block', 'house');
    allObstacles[1] = new Items(101, 60, 'door-tall-closed', 'door');
    allObstacles[2] = new Items(202, 45, 'wood-block', 'house');
    allObstacles[3] = new Items(0, -40, 'roof-south-west', 'house');
    allObstacles[4] = new Items(101, -40, 'roof-south', 'house');
    allObstacles[5] = new Items(202, -40, 'roof-south-east', 'house');

    allObstacles[6] = new Items(101, 224, 'tree-ugly', 'tree');
    allObstacles[7] = new Items(101, 307, 'tree-ugly', 'tree');
    allObstacles[8] = new Items(707, 141, 'tree-ugly', 'tree');
    allObstacles[9] = new Items(707, 224, 'tree-ugly', 'tree');
    allObstacles[10] = new Items(808, 224, 'tree-ugly', 'tree');
    allObstacles[11] = new Items(303, 470, 'tree-tall', 'tree');
    allObstacles[12] = new Items(404, 470, 'tree-tall', 'tree');
    allObstacles[13] = new Items(404, 141, 'tree-tall', 'tree');
    allObstacles[14] = new Items(404, 556, 'tree-tall', 'tree');
    allObstacles[15] = new Items(505, 556, 'tree-tall', 'tree');

    allObstacles[16] = new Items(505, 390, 'rock', 'rock');
    allObstacles[17] = new Items(303, 556, 'rock', 'rock');

    // Create the items
    var allItems = [];
    allItems[0] = new Items(808, 131, 'key', 'key');
    allItems[1] = new Items(0, 297, 'key', 'key');
    allItems[2] = new Items(606, 48, 'heart', 'life');
    allItems[3] = new Items(202, 465, 'chest-closed', 'chest');

}

/* -------------- ENEMY ---------------- */

// Enemies our player must avoid
var Enemy = function(x, y) {
    // Setting the Enemy initial location
    this.x = x;
    this.y = y;
    this.right = this.x + 101;
    this.bottom = this.y + 83;

    // Setting the speed, random and different for each bug.
    this.speed = Math.floor(Math.random() * 450 + 1);
    console.log(Math.floor(Math.random() * 450 +1));

    // Loading the image by setting this.sprite to the appropriate image
    this.sprite = 'images/enemy-bug.png';
}

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // Updates the Enemy location
    this.x += this.speed * dt;

    // If the Enemy goes off screen, we reset the position to start again
    if (this.x > 909) {
        this.x = Math.random() * -1200;
    }
}

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// Place all enemy objects in an array called allEnemies
var allEnemies = [];
var enemyHeight = [146,229,312,395,478];
// Create 10 enemies, 2 for each row, with a random initial location
for (var i = 0; i < 10; i++) {
    allEnemies.push(new Enemy(-(Math.floor(Math.random() * 400 + 100)), enemyHeight[i % 5]));
}

/* -------------- PLAYER ---------------- */

// Implement the Player class
var Player = function(x,y) {
    // Setting the Player initial location
    this.x = x;
    this.y = y;
    this.right = this.x + 101;
    this.bottom = this.y + 83;

    // Loading the image by setting this.sprite
    this.sprite = 'images/char-boy.png';
}

// Update the player's position
Player.prototype.update = function() {
    this.x = this.x;
    this.y = this.y;
    checkCollisions(this.x, this.y);
    checkObstacles(this.x, this.y);
}

// Draw the player on the screen
Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// handleInput method receives the user input with parameter 'allowedKeys'
// The Player moves accordingly to that input
Player.prototype.handleInput = function(allowedKeys) {
    switch(allowedKeys) {

        // left key moves player to the west
        case 'left':
            // we check to avoid player moving off-screen
            if (this.x > 0) {
                this.x -= 101;
                break;
            }

        // up key moves player to the north
        case 'up':
            //we check to avoid player moving off-screen
            if (this.y > 0) {
                this.y -= 83;
                break;
            } else { // if player is in the water, we reset the game
                player.reset();
            }

        // right key moves player to the east
        case 'right':
            // we check to avoid player moving off-screen
            if (this.x < 808) {
                this.x += 101;
                break;
            }

        // down key moves player to the south
        case 'down':
            // we check to avoid player moving off-screen
            if (this.y < 575) {
                this.y += 83;
                break;
            }
    }
}

// Reset the player's position when it collides with a bug
Player.prototype.reset = function() {
    CURRENT_LIFES = CURRENT_LIFES - 1;
    document.getElementById('numberLifes').innerHTML = CURRENT_LIFES.toString();
    if (CURRENT_LEVEL === 2) {  // I should put this in variables...
        this.x = 808;
        this.y = 575;
    } else {
        this.x = 404;
        this.y = 575;
    }
}

// Place the player object in a variable called player
var player;
if (CURRENT_LEVEL === 2) {  // put this in variables...
    player = new Player(808,575);
} else {
    player = new Player(404,575);
}

/* ------------ COLLISIONS & ITEMS ------------ */

// Function to check if the player collides with a bug or an item
var checkCollisions = function(playerX, playerY) {

    // Calculate the central Rectangle to avoid the blank space
    var Rectangle = function (left, top) {
	   this.left = left + 35;
	   this.top = top + 20;
	   this.right = this.left + 65;
	   this.bottom = this.top + 62;
    };

    // Check to see if the rectangles overlap
    function checkCollision(player, obstacle) {
	   return !(player.left > obstacle.right || player.right < obstacle.left || player.top > obstacle.bottom || player.bottom < obstacle.top);
    };

    var playerRectangle = new Rectangle(player.x, player.y);

    // Check collision with enemy bugs, to reset position
    for (var i = 0; i < allEnemies.length; i++) {
        var enemyRectangle = new Rectangle(allEnemies[i].x, allEnemies[i].y);
        if (checkCollision(playerRectangle, enemyRectangle)) {

            player.reset();
        }
    }

    // Check collision with items, to it pick up
    for (var i = 0; i < allItems.length; i++) {
        var itemRectangle = new Rectangle(allItems[i].x, allItems[i].y);
        if (checkCollision(playerRectangle, itemRectangle)) {

            switch(allItems[i].item) {
                case 'key':
                    CURRENT_KEYS = CURRENT_KEYS + 1;
                    document.getElementById('numberKeys').innerHTML = CURRENT_KEYS.toString();
                    allItems.splice(i,1);
                    break;

                case 'life':
                    CURRENT_LIFES = CURRENT_LIFES + 1;
                    document.getElementById('numberLifes').innerHTML = CURRENT_LIFES.toString();
                    allItems.splice(i,1);
                    break;
            }
        }
    }
}

// Function to check if the player collides with an obstacle, in which case it shouldn't be able to go over?
var checkObstacles = function (playerX, playerY) {

    // Calculate the central Rectangle to avoid the blank space
    var Rectangle = function (left, top) {
	   this.left = left;
	   this.top = top;
	   this.right = this.left + 101;
	   this.bottom = this.top + 83;
    };

    // Check to see if the rectangles overlap
    function checkCollision(player, obstacle) {
	   return !(player.left > obstacle.right || player.right < obstacle.left || player.top > obstacle.bottom || player.bottom < obstacle.top);
    };

    var playerRectangle = new Rectangle(player.x, player.y);

    // Check collision with nature (trees and rocks)
    for (var i = 0; i < allObstacles.length; i++) {
        var obstacleRectangle = new Rectangle(allObstacles[i].x, allObstacles[i].y);
        if (checkCollision(playerRectangle, obstacleRectangle)) {

            // Player has found an obstacle that can't be crossed over
            switch(allObstacles[i].item) {
                case 'tree':
                    if (HAS_GREEN_GEM === false) {

                        break;
                    }

                case 'water':
                    if (HAS_BLUE_GEM === false) {

                        break;
                    }

                case 'rock', 'house':
                    player.speed = 0;
                    break;

                case 'door':
                    if (CURRENT_KEYS > 0) {
                        // opens door and changes level
                        CURRENT_LEVEL = CURRENT_LEVEL + 1;
                        break;

                    } else {

                        break;
                    }
            }
        }
    }
}

/* ---------------- KEYBOARD INPUT --------------- */

// This listens for key presses and sends the keys to your Player.handleInput() method
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});
<commit_msg>New global variables<commit_after>/* ----------- GLOBAL VARIABLES --------------- */

var CURRENT_LIFES = 5;      // number of current lifes
var CURRENT_KEYS = 0;       // number of current keys
var HAS_BLUE_GEM = true;    // has picked the blue gem
var HAS_GREEN_GEM = true;   // has picked the green gem
var CURRENT_LEVEL = 1;      // level of the screen
var HERO = "char-boy";      // choosen hero
var DIFFICULTY = 0;         // choosen level of difficulty

// Put the variables on screen in the menu
document.getElementById('numberLifes').innerHTML = CURRENT_LIFES.toString();
document.getElementById('numberKeys').innerHTML = CURRENT_KEYS.toString();
document.getElementById('numberLevel').innerHTML = CURRENT_LEVEL.toString();
if (HAS_BLUE_GEM) {
    document.getElementById('hasGems').innerHTML += "";
}
if (HAS_GREEN_GEM) {
    document.getElementById('hasGems').innerHTML += "";
}

/* -------------- OBSTACLES & ITEMS ---------------- */

// Implement the Items class, with the stuff to pick up
var Items = function(x,y,sprite,item) {
    this.x = x;
    this.y = y;
    this.sprite = 'images/' + sprite + '.png';
    this.item = item;
}
// Draw the items on the screen
Items.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

if (CURRENT_LEVEL === 2) {

    /* --------- LEVEL 2 CANVAS ------------ */

    // Build the house, put the trees and the rocks
    var allObstacles = [];
    allObstacles[0] = new Items(0, 45, 'wood-block', 'house');
    allObstacles[1] = new Items(101, 60, 'door-tall-closed', 'door');
    allObstacles[2] = new Items(202, 45, 'wood-block', 'house');
    allObstacles[3] = new Items(0, -40, 'roof-south-west', 'house');
    allObstacles[4] = new Items(101, -40, 'roof-south', 'house');
    allObstacles[5] = new Items(202, -40, 'roof-south-east', 'house');

    allObstacles[6] = new Items(101, 224, 'tree-ugly', 'tree');
    allObstacles[7] = new Items(101, 307, 'tree-ugly', 'tree');
    allObstacles[8] = new Items(707, 141, 'tree-ugly', 'tree');
    allObstacles[9] = new Items(707, 224, 'tree-ugly', 'tree');
    allObstacles[10] = new Items(808, 224, 'tree-ugly', 'tree');
    allObstacles[11] = new Items(303, 470, 'tree-tall', 'tree');
    allObstacles[12] = new Items(404, 470, 'tree-tall', 'tree');
    allObstacles[13] = new Items(404, 141, 'tree-tall', 'tree');
    allObstacles[14] = new Items(404, 556, 'tree-tall', 'tree');
    allObstacles[15] = new Items(505, 556, 'tree-tall', 'tree');

    allObstacles[16] = new Items(505, 390, 'rock', 'rock');
    allObstacles[17] = new Items(303, 556, 'rock', 'rock');

    // Create the items
    var allItems = [];
    allItems[0] = new Items(808, 131, 'key', 'key');
    allItems[1] = new Items(0, 297, 'key', 'key');
    allItems[2] = new Items(606, 48, 'heart', 'life');
    allItems[3] = new Items(202, 465, 'chest-closed', 'chest');

} else if (CURRENT_LEVEL === 3) {

} else if (CURRENT_LEVEL === 4) {

} else {

    /* --------- LEVEL 1 CANVAS ------------ */

    // Build the house, put the trees and the rocks
    var allObstacles = [];
    allObstacles[0] = new Items(303, 45, 'window-tall', 'house');
    allObstacles[1] = new Items(404, 60, 'door-tall-closed', 'door');
    allObstacles[2] = new Items(505, 45, 'window-tall', 'house');
    allObstacles[3] = new Items(303, -40, 'roof-south-west', 'house');
    allObstacles[4] = new Items(404, -40, 'roof-south', 'house');
    allObstacles[5] = new Items(505, -40, 'roof-south-east', 'house');

    allObstacles[6] = new Items(101, 224, 'tree-ugly', 'house');
    allObstacles[7] = new Items(303, 307, 'tree-ugly', 'house');
    allObstacles[8] = new Items(606, 141, 'tree-ugly', 'house');
    allObstacles[9] = new Items(606, 224, 'tree-ugly', 'house');
    allObstacles[10] = new Items(0, -25, 'tree-short', 'house');
    allObstacles[11] = new Items(101, -25, 'tree-short', 'house');
    allObstacles[12] = new Items(202, -25, 'tree-short', 'house');
    allObstacles[13] = new Items(606, -25, 'tree-short', 'house');
    allObstacles[14] = new Items(707, -25, 'tree-short', 'house');
    allObstacles[15] = new Items(808, -25, 'tree-short', 'house');

    allObstacles[16] = new Items(505, 470, 'rock', 'house');
    allObstacles[17] = new Items(707, 224, 'rock', 'house');

    // Create the items
    var allItems = [];
    allItems[0] = new Items(707, 131, 'key', 'key');
    allItems[1] = new Items(101, 131, 'key', 'key');
    allItems[2] = new Items(0, 465, 'heart', 'life');

}

/* -------------- ENEMY ---------------- */

// Enemies our player must avoid
var Enemy = function(x, y) {
    // Setting the Enemy initial location
    this.x = x;
    this.y = y;
    this.right = this.x + 101;
    this.bottom = this.y + 83;

    // Setting the speed, random and different for each bug.
    this.speed = Math.floor(Math.random() * 450 + 1);
    console.log(Math.floor(Math.random() * 450 +1));

    // Loading the image by setting this.sprite to the appropriate image
    this.sprite = 'images/enemy-bug.png';
}

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // Updates the Enemy location
    this.x += this.speed * dt;

    // If the Enemy goes off screen, we reset the position to start again
    if (this.x > 909) {
        this.x = Math.random() * -1200;
    }
}

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// Place all enemy objects in an array called allEnemies
var allEnemies = [];
var enemyHeight = [146,229,312,395,478];
// Create 10 enemies, 2 for each row, with a random initial location
for (var i = 0; i < 10; i++) {
    allEnemies.push(new Enemy(-(Math.floor(Math.random() * 400 + 100)), enemyHeight[i % 5]));
}

/* -------------- PLAYER ---------------- */

// Implement the Player class
var Player = function(x,y) {
    // Setting the Player initial location
    this.x = x;
    this.y = y;
    this.right = this.x + 101;
    this.bottom = this.y + 83;

    // Loading the image by setting this.sprite
    this.sprite = 'images/' + HERO + '.png';
}

// Update the player's position
Player.prototype.update = function() {
    this.x = this.x;
    this.y = this.y;
    checkCollisions(this.x, this.y);
    checkObstacles(this.x, this.y);
}

// Draw the player on the screen
Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// handleInput method receives the user input with parameter 'allowedKeys'
// The Player moves accordingly to that input
Player.prototype.handleInput = function(allowedKeys) {
    switch(allowedKeys) {

        // left key moves player to the west
        case 'left':
            // we check to avoid player moving off-screen
            if (this.x > 0) {
                this.x -= 101;
                break;
            }

        // up key moves player to the north
        case 'up':
            //we check to avoid player moving off-screen
            if (this.y > 0) {
                this.y -= 83;
                break;
            } else { // if player is in the water, we reset the game
                player.reset();
            }

        // right key moves player to the east
        case 'right':
            // we check to avoid player moving off-screen
            if (this.x < 808) {
                this.x += 101;
                break;
            }

        // down key moves player to the south
        case 'down':
            // we check to avoid player moving off-screen
            if (this.y < 575) {
                this.y += 83;
                break;
            }
    }
}

// Reset the player's position when it collides with a bug
Player.prototype.reset = function() {
    CURRENT_LIFES = CURRENT_LIFES - 1;
    document.getElementById('numberLifes').innerHTML = CURRENT_LIFES.toString();
    if (CURRENT_LEVEL === 2) {  // I should put this in variables...
        this.x = 808;
        this.y = 575;
    } else {
        this.x = 404;
        this.y = 575;
    }
}

// Place the player object in a variable called player
var player;
if (CURRENT_LEVEL === 2) {  // put this in variables...
    player = new Player(808,575);
} else {
    player = new Player(404,575);
}

/* ------------ COLLISIONS & ITEMS ------------ */

// Function to check if the player collides with a bug or an item
var checkCollisions = function(playerX, playerY) {

    // Calculate the central Rectangle to avoid the blank space
    var Rectangle = function (left, top) {
	   this.left = left + 35;
	   this.top = top + 20;
	   this.right = this.left + 65;
	   this.bottom = this.top + 62;
    };

    // Check to see if the rectangles overlap
    function checkCollision(player, obstacle) {
	   return !(player.left > obstacle.right || player.right < obstacle.left || player.top > obstacle.bottom || player.bottom < obstacle.top);
    };

    var playerRectangle = new Rectangle(player.x, player.y);

    // Check collision with enemy bugs, to reset position
    for (var i = 0; i < allEnemies.length; i++) {
        var enemyRectangle = new Rectangle(allEnemies[i].x, allEnemies[i].y);
        if (checkCollision(playerRectangle, enemyRectangle)) {

            player.reset();
        }
    }

    // Check collision with items, to it pick up
    for (var i = 0; i < allItems.length; i++) {
        var itemRectangle = new Rectangle(allItems[i].x, allItems[i].y);
        if (checkCollision(playerRectangle, itemRectangle)) {

            switch(allItems[i].item) {
                case 'key':
                    CURRENT_KEYS = CURRENT_KEYS + 1;
                    document.getElementById('numberKeys').innerHTML = CURRENT_KEYS.toString();
                    allItems.splice(i,1);
                    break;

                case 'life':
                    CURRENT_LIFES = CURRENT_LIFES + 1;
                    document.getElementById('numberLifes').innerHTML = CURRENT_LIFES.toString();
                    allItems.splice(i,1);
                    break;
            }
        }
    }
}

// Function to check if the player collides with an obstacle, in which case it shouldn't be able to go over?
var checkObstacles = function (playerX, playerY) {

    // Calculate the central Rectangle to avoid the blank space
    var Rectangle = function (left, top) {
	   this.left = left;
	   this.top = top;
	   this.right = this.left + 101;
	   this.bottom = this.top + 83;
    };

    // Check to see if the rectangles overlap
    function checkCollision(player, obstacle) {
	   return !(player.left > obstacle.right || player.right < obstacle.left || player.top > obstacle.bottom || player.bottom < obstacle.top);
    };

    var playerRectangle = new Rectangle(player.x, player.y);

    // Check collision with nature (trees and rocks)
    for (var i = 0; i < allObstacles.length; i++) {
        var obstacleRectangle = new Rectangle(allObstacles[i].x, allObstacles[i].y);
        if (checkCollision(playerRectangle, obstacleRectangle)) {

            // Player has found an obstacle that can't be crossed over
            switch(allObstacles[i].item) {
                case 'tree':
                    if (HAS_GREEN_GEM === false) {

                        break;
                    }

                case 'water':
                    if (HAS_BLUE_GEM === false) {

                        break;
                    }

                case 'rock', 'house':
                    player.speed = 0;
                    break;

                case 'door':
                    if (CURRENT_KEYS > 0) {
                        // opens door and changes level
                        CURRENT_LEVEL = CURRENT_LEVEL + 1;
                        break;

                    } else {

                        break;
                    }
            }
        }
    }
}

/* ---------------- KEYBOARD INPUT --------------- */

// This listens for key presses and sends the keys to your Player.handleInput() method
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});

<|endoftext|>


<commit_before>import {
  join,
  block,
  wrap,
  indent
} from '../utilities/printing.js';

import { camelCase } from 'change-case';

import {
  visit,
  visitWithTypeInfo,
  TypeInfo,
  GraphQLEnumType
} from 'graphql';

import { propertiesFromSelectionSet, typeNameFromGraphQLType } from './mapping'

export function generateSource(schema, document) {
  const typeInfo = new TypeInfo(schema);

  let typesUsed = [];
  let queryDefinitions = [];

  visit(document, visitWithTypeInfo(typeInfo, {
    leave: {
      Name: node => node.value,
      Document: node => node.definitions,
      OperationDefinition: ({ loc, name, operation, variableDefinitions, selectionSet }) => {
        queryDefinitions.push({ name, operation, source: sourceAt(loc), variableDefinitions, selectionSet });
      },
      VariableDefinition: node => {
        const type = typeInfo.getInputType();
        typesUsed.push(type);
        return { name: node.variable, type: type };
      },
      Variable: node => node.name,
      SelectionSet: ({ selections }) => selections,
      Field: ({ kind, alias, name, arguments: args, directives, selectionSet }) => {
        const type = typeInfo.getType();
        typesUsed.push(type);
        return { kind, alias, name, type: type, selectionSet: selectionSet ? selectionSet : undefined }
      }
    }
  }));

  const typeDefinitions = typesUsed.map(type => typeDeclarationForGraphQLType(type));
  const classDefinitions = queryDefinitions.map(query => classDefinitionFromQuery(query));

  return join([
    '//  This file was automatically generated and should not be edited.\n\n',
    importDeclarations() + '\n',
    wrap('\n', join(typeDefinitions, '\n\n'), '\n'),
    wrap('\n', join(classDefinitions, '\n\n'), '\n')
  ]);
}

function sourceAt(location) {
  return location.source.body.slice(location.start, location.end);
}

function escapedString(string) {
  return string.replace(/"/g, '\\"');
}

function multilineString(string) {
  const lines = string.split('\n');
  return lines.map((line, index) => {
    const isLastLine = index != lines.length - 1;
    return `"${escapedString(line)}"` + (isLastLine ? ' +' : '');
  }).join('\n');
}

function importDeclarations() {
  return 'import Apollo';
}

function typeDeclarationForGraphQLType(type) {
  if (type instanceof GraphQLEnumType) {
    return enumerationDeclaration(type);
  }
}

function enumerationDeclaration(type) {
  const { name, description } = type;
  const values = type.getValues();

  const caseDeclarations = values.map(value =>
    `case ${camelCase(value.name)} = "${value.value}"${wrap(' /// ', value.description)}`
  );

  return join([
    description && `/// ${description}\n`,
    `public enum ${name}: String `,
    block(caseDeclarations),
    '\n\n',
    `extension ${name}: JSONDecodable, JSONEncodable {}`
  ]);
}

function classDefinitionFromQuery({ source, name, variableDefinitions, selectionSet }) {
  const properties = propertiesFromSelectionSet(selectionSet);

  return `public class ${name}Query: GraphQLQuery ` +
    block([
      wrap('', instancePropertyDeclarations(variableDefinitions), '\n'),
      initializerDeclaration(variableDefinitions),
      wrap('\n', operationDefinition(source)),
      wrap('\n', variablesProperty(variableDefinitions)),
      wrap('\n', structDeclaration({ name: "Data", properties }))]);
}

function instancePropertyDeclarations(variableDefinitions = []) {
  return join(variableDefinitions.map(variable => {
    return `public let ${variable.name}: ${typeNameFromGraphQLType(variable.type)}`;
  }), '\n');
}

function initializerDeclaration(variableDefinitions = []) {
  const initializationParameters = join(variableDefinitions.map(variable => {
    return `${variable.name}: ${typeNameFromGraphQLType(variable.type)}`;
  }), ', ');

  const propertyInitializations = variableDefinitions.map(variable => {
    return `self.${variable.name} = ${variable.name}`;
  });

  return `public init(${initializationParameters}) ` + block(propertyInitializations);
}

function variablesProperty(variableDefinitions = []) {
  if (variableDefinitions.length < 1) return null;

  const variablesMap = wrap(`return [`, join(variableDefinitions.map(variable => {
    return `"${variable.name}": ${variable.name}`;
  }), ', '), `]`);

  return 'public var variables: GraphQLMap? ' + block([variablesMap]);
}

function operationDefinition(source) {
  return `public let operationDefinition =
  ${indent(multilineString(source))}`
}

function structDeclaration({ name, properties = [] }) {
  const propertyDeclarations = properties.map(propertyDeclaration);

  const initializerDeclaration = `public init(map: GraphQLMap) throws ` +
    block(properties.map(property =>
      `${property.name} = try map.${ property.isList ? 'list' : 'value' }(forKey: "${property.fieldName}")`));

  const compositeProperties = properties.filter(property => property.isComposite);
  const nestedStructDeclarations = compositeProperties.map(property => wrap('\n', structDeclaration(property.typeDeclaration)) );

  return `public struct ${name}: GraphQLMapConvertible ` +
    block([
      wrap('', join(propertyDeclarations, '\n'), '\n'),
      initializerDeclaration,
      join(nestedStructDeclarations, '\n')
    ]);
}

function propertyDeclaration({ name, typeName }) {
  return `public let ${name}: ${typeName}`;
}
<commit_msg>Force upper camel case for generated query class names<commit_after>import {
  join,
  block,
  wrap,
  indent
} from '../utilities/printing.js';

import { camelCase, pascalCase } from 'change-case';

import {
  visit,
  visitWithTypeInfo,
  TypeInfo,
  GraphQLEnumType
} from 'graphql';

import { propertiesFromSelectionSet, typeNameFromGraphQLType } from './mapping'

export function generateSource(schema, document) {
  const typeInfo = new TypeInfo(schema);

  let typesUsed = [];
  let queryDefinitions = [];

  visit(document, visitWithTypeInfo(typeInfo, {
    leave: {
      Name: node => node.value,
      Document: node => node.definitions,
      OperationDefinition: ({ loc, name, operation, variableDefinitions, selectionSet }) => {
        queryDefinitions.push({ name, operation, source: sourceAt(loc), variableDefinitions, selectionSet });
      },
      VariableDefinition: node => {
        const type = typeInfo.getInputType();
        typesUsed.push(type);
        return { name: node.variable, type: type };
      },
      Variable: node => node.name,
      SelectionSet: ({ selections }) => selections,
      Field: ({ kind, alias, name, arguments: args, directives, selectionSet }) => {
        const type = typeInfo.getType();
        typesUsed.push(type);
        return { kind, alias, name, type: type, selectionSet: selectionSet ? selectionSet : undefined }
      }
    }
  }));

  const typeDefinitions = typesUsed.map(type => typeDeclarationForGraphQLType(type));
  const classDefinitions = queryDefinitions.map(query => classDefinitionFromQuery(query));

  return join([
    '//  This file was automatically generated and should not be edited.\n\n',
    importDeclarations() + '\n',
    wrap('\n', join(typeDefinitions, '\n\n'), '\n'),
    wrap('\n', join(classDefinitions, '\n\n'), '\n')
  ]);
}

function sourceAt(location) {
  return location.source.body.slice(location.start, location.end);
}

function escapedString(string) {
  return string.replace(/"/g, '\\"');
}

function multilineString(string) {
  const lines = string.split('\n');
  return lines.map((line, index) => {
    const isLastLine = index != lines.length - 1;
    return `"${escapedString(line)}"` + (isLastLine ? ' +' : '');
  }).join('\n');
}

function importDeclarations() {
  return 'import Apollo';
}

function typeDeclarationForGraphQLType(type) {
  if (type instanceof GraphQLEnumType) {
    return enumerationDeclaration(type);
  }
}

function enumerationDeclaration(type) {
  const { name, description } = type;
  const values = type.getValues();

  const caseDeclarations = values.map(value =>
    `case ${camelCase(value.name)} = "${value.value}"${wrap(' /// ', value.description)}`
  );

  return join([
    description && `/// ${description}\n`,
    `public enum ${name}: String `,
    block(caseDeclarations),
    '\n\n',
    `extension ${name}: JSONDecodable, JSONEncodable {}`
  ]);
}

function classDefinitionFromQuery({ source, name, variableDefinitions, selectionSet }) {
  const className = `${pascalCase(name)}Query`;
  const properties = propertiesFromSelectionSet(selectionSet);

  return `public class ${className}: GraphQLQuery ` +
    block([
      wrap('', instancePropertyDeclarations(variableDefinitions), '\n'),
      initializerDeclaration(variableDefinitions),
      wrap('\n', operationDefinition(source)),
      wrap('\n', variablesProperty(variableDefinitions)),
      wrap('\n', structDeclaration({ name: "Data", properties }))]);
}

function instancePropertyDeclarations(variableDefinitions = []) {
  return join(variableDefinitions.map(variable => {
    return `public let ${variable.name}: ${typeNameFromGraphQLType(variable.type)}`;
  }), '\n');
}

function initializerDeclaration(variableDefinitions = []) {
  const initializationParameters = join(variableDefinitions.map(variable => {
    return `${variable.name}: ${typeNameFromGraphQLType(variable.type)}`;
  }), ', ');

  const propertyInitializations = variableDefinitions.map(variable => {
    return `self.${variable.name} = ${variable.name}`;
  });

  return `public init(${initializationParameters}) ` + block(propertyInitializations);
}

function variablesProperty(variableDefinitions = []) {
  if (variableDefinitions.length < 1) return null;

  const variablesMap = wrap(`return [`, join(variableDefinitions.map(variable => {
    return `"${variable.name}": ${variable.name}`;
  }), ', '), `]`);

  return 'public var variables: GraphQLMap? ' + block([variablesMap]);
}

function operationDefinition(source) {
  return `public let operationDefinition =
  ${indent(multilineString(source))}`
}

function structDeclaration({ name, properties = [] }) {
  const propertyDeclarations = properties.map(propertyDeclaration);

  const initializerDeclaration = `public init(map: GraphQLMap) throws ` +
    block(properties.map(property =>
      `${property.name} = try map.${ property.isList ? 'list' : 'value' }(forKey: "${property.fieldName}")`));

  const compositeProperties = properties.filter(property => property.isComposite);
  const nestedStructDeclarations = compositeProperties.map(property => wrap('\n', structDeclaration(property.typeDeclaration)) );

  return `public struct ${name}: GraphQLMapConvertible ` +
    block([
      wrap('', join(propertyDeclarations, '\n'), '\n'),
      initializerDeclaration,
      join(nestedStructDeclarations, '\n')
    ]);
}

function propertyDeclaration({ name, typeName }) {
  return `public let ${name}: ${typeName}`;
}
<|endoftext|>


<commit_before>(function () {
  'use strict';

  moj.Modules.FormErrors = {
    init: function() {
      this.bindEvents();
      this.loadTemplates();
    },

    bindEvents: function() {
      $('button[type="submit"]', $('form')).on('click',  $.proxy(this.postToFormErrors, this));
    },

    postToFormErrors: function(e) {
      this.clearErrors();
      this.$form = $(e.currentTarget).closest('form');
      if (this.$form.length) {
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
          type: 'OPTIONS',
          url: '',
          contentType: 'application/x-www-form-urlencoded',
          data: this.$form.serialize()
        }).done(
          $.proxy(this.onAjaxSuccess, this)
        ).fail(
          $.proxy(this.onAjaxError, this)
        );
      }
    },

    onAjaxSuccess: function (errors) {
      if (!$.isEmptyObject(errors)) {
        this.loadErrors(errors);
        $('html, body').animate({
            scrollTop: $('.alert-error:visible:first').offset().top - 50
        }, 300);
      } else {
        this.$form.submit();
      }
    },

    onAjaxError: function () {
      this.$form.submit();
    },

    formatErrors: function (errors) {
      var errorFields = {};

      (function fieldName (errorsObj, prefix) {
        prefix = (typeof prefix === 'undefined')? '': prefix + '-';
        for (var key in errorsObj) {
          var field = prefix + key;
          if ($.isArray(errorsObj[key])) {
            errorFields[field] = errorsObj[key];
          } else {
            fieldName(errorsObj[key], field);
          }
        }
      })(errors);

      return errorFields;
    },

    loadErrors: function (errors) {
      var errorFields = this.formatErrors(errors);

      for (var id in errorFields) {
        $('#field-' + id).addClass('m-error');

        $('#field-label-' + id)
          .addClass('m-error')
          .after(this.fieldError({errors: errorFields[id]}));
      }

      this.$form.prepend(this.mainFormError());
    },

    loadTemplates: function () {
      this.mainFormError = _.template($('#mainFormError').html());
      this.fieldError = _.template($('#fieldError').html());
    },

    clearErrors: function () {
      $('.form-row.field-error').remove();
      $('.alert.alert-error').remove();
      $('.m-error').removeClass('m-error');
    }
  };
}());
<commit_msg>FE: Support subfields in form errors JS<commit_after>(function () {
  'use strict';

  moj.Modules.FormErrors = {
    init: function() {
      this.bindEvents();
      this.loadTemplates();
    },

    bindEvents: function() {
      $('button[type="submit"]', $('form')).on('click',  $.proxy(this.postToFormErrors, this));
    },

    postToFormErrors: function(e) {
      this.clearErrors();
      this.$form = $(e.currentTarget).closest('form');
      if (this.$form.length) {
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
          type: 'OPTIONS',
          url: '',
          contentType: 'application/x-www-form-urlencoded',
          data: this.$form.serialize()
        }).done(
          $.proxy(this.onAjaxSuccess, this)
        ).fail(
          $.proxy(this.onAjaxError, this)
        );
      }
    },

    onAjaxSuccess: function (errors) {
      if (!$.isEmptyObject(errors)) {
        this.loadErrors(errors);
        $('html, body').animate({
            scrollTop: $('.alert-error:visible:first').offset().top - 50
        }, 300);
      } else {
        this.$form.submit();
      }
    },

    onAjaxError: function () {
      this.$form.submit();
    },

    formatErrors: function (errors) {
      var errorFields = {};

      (function fieldName (errorsObj, prefix) {
        prefix = (typeof prefix === 'undefined')? '': prefix + '-';
        for (var key in errorsObj) {
          var field = prefix + key;
          if ($.isArray(errorsObj[key])) {
            errorFields[field] = errorsObj[key];
          } else {
            fieldName(errorsObj[key], field);
          }
        }
      })(errors);

      return errorFields;
    },

    loadErrors: function (errors) {
      var errorFields = this.formatErrors(errors);
      var self = this;

      function addErrors(errors, fieldName) {
        if (_.isString(errors[0])) {
          $('#field-' + fieldName).addClass('m-error');
          $('#field-label-' + fieldName)
            .addClass('m-error')
            .after(self.fieldError({ errors: errors }));
        } else if(_.isObject(errors[0]) && !_.isArray(errors[0])) {
          // Multiple forms (e.g. properties)
          _.each(errors, function(errors, i) {
            _.each(errors, function(subformErrors, subformFieldName) {
              addErrors(subformErrors, fieldName + '-' + i + '-' + subformFieldName);
            });
          });
        } else {
          _.each(errors, function(subformErrors) {
            addErrors(subformErrors[1], fieldName + '-' + subformErrors[0]);
          });
        }
      }

      _.each(errorFields, addErrors);

      this.$form.prepend(this.mainFormError());
    },

    loadTemplates: function () {
      this.mainFormError = _.template($('#mainFormError').html());
      this.fieldError = _.template($('#fieldError').html());
    },

    clearErrors: function () {
      $('.form-row.field-error').remove();
      $('.alert.alert-error').remove();
      $('.m-error').removeClass('m-error');
    }
  };
}());
<|endoftext|>


<commit_before>/* jshint laxcomma: true */
var utils = require('./utils');

exports.C14nCanonicalization = C14nCanonicalization;
exports.C14nCanonicalizationWithComments = C14nCanonicalizationWithComments;

function C14nCanonicalization() {
	this.includeComments = false;
};

C14nCanonicalization.prototype.attrCompare = function(a,b) {
  if (!a.namespaceURI && b.namespaceURI) { return -1; }
  if (!b.namespaceURI && a.namespaceURI) { return 1; }

  var left = a.namespaceURI + a.localName
  var right = b.namespaceURI + b.localName

  if (left===right) return 0
  else if (left<right) return -1
  else return 1

};

C14nCanonicalization.prototype.nsCompare = function(a,b) {
  var attr1 = a.prefix;
  var attr2 = b.prefix;
  if (attr1 == attr2) { return 0; }
  return attr1.localeCompare(attr2);
};

C14nCanonicalization.prototype.renderAttrs = function(node, defaultNS) {
  var a, i, attr
    , res = []
    , attrListToRender = [];

  if (node.nodeType===8) { return this.renderComment(node); }

  if (node.attributes) {
    for (i = 0; i < node.attributes.length; ++i) {
      attr = node.attributes[i];
      //ignore namespace definition attributes
      if (attr.name.indexOf("xmlns") === 0) { continue; }
      attrListToRender.push(attr);
    }
  }

  attrListToRender.sort(this.attrCompare);

  for (a in attrListToRender) {
    if (!attrListToRender.hasOwnProperty(a)) { continue; }

    attr = attrListToRender[a];
    res.push(" ", attr.name, '="', utils.encodeSpecialCharactersInAttribute(attr.value), '"');
  }

  return res.join("");
};

/**
 * Create the string of all namespace declarations that should appear on this element
 *
 * @param {Node} node. The node we now render
 * @param {Array} prefixesInScope. The prefixes defined on this node
 *                parents which are a part of the output set
 * @param {String} defaultNs. The current default namespace
 * @param {String} defaultNsForPrefix.
 * @param {String} ancestorNamespaces - Import ancestor namespaces if it is specified
 * @return {String}
 * @api private
 */
C14nCanonicalization.prototype.renderNs = function(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces) {
  var a, i, p, attr
    , res = []
    , newDefaultNs = defaultNs
    , nsListToRender = []
    , currNs = node.namespaceURI || "";

  //handle the namespaceof the node itself
  if (node.prefix) {
    if (prefixesInScope.indexOf(node.prefix)==-1) {
      nsListToRender.push({"prefix": node.prefix, "namespaceURI": node.namespaceURI || defaultNsForPrefix[node.prefix]});
      prefixesInScope.push(node.prefix);
    }
  }
  else if (defaultNs!=currNs) {
      //new default ns
      newDefaultNs = node.namespaceURI;
      res.push(' xmlns="', newDefaultNs, '"');
  }

  //handle the attributes namespace
  if (node.attributes) {
    for (i = 0; i < node.attributes.length; ++i) {
      attr = node.attributes[i];

      //handle all prefixed attributes that are included in the prefix list and where
      //the prefix is not defined already. New prefixes can only be defined by `xmlns:`.
      if (attr.prefix === "xmlns" && prefixesInScope.indexOf(attr.localName) === -1) {
        nsListToRender.push({"prefix": attr.localName, "namespaceURI": attr.value});
        prefixesInScope.push(attr.localName);
      }

      //handle all prefixed attributes that are not xmlns definitions and where
      //the prefix is not defined already
      if (attr.prefix && prefixesInScope.indexOf(attr.prefix)==-1 && attr.prefix!="xmlns" && attr.prefix!="xml") {
        nsListToRender.push({"prefix": attr.prefix, "namespaceURI": attr.namespaceURI});
        prefixesInScope.push(attr.prefix);
      }
    }
  }

  if(Array.isArray(ancestorNamespaces) && ancestorNamespaces.length > 0){
    // Remove namespaces which are already present in nsListToRender
    for(var p1 in ancestorNamespaces){
      if(!ancestorNamespaces.hasOwnProperty(p1)) continue;
      var alreadyListed = false;
      for(var p2 in nsListToRender){
        if(nsListToRender[p2].prefix === ancestorNamespaces[p1].prefix
          && nsListToRender[p2].namespaceURI === ancestorNamespaces[p1].namespaceURI)
        {
          alreadyListed = true;
        }
      }

      if(!alreadyListed){
        nsListToRender.push(ancestorNamespaces[p1]);
      }
    }
  }

  nsListToRender.sort(this.nsCompare);

  //render namespaces
  for (a in nsListToRender) {
    if (!nsListToRender.hasOwnProperty(a)) { continue; }

    p = nsListToRender[a];
    res.push(" xmlns:", p.prefix, '="', p.namespaceURI, '"');
  }

  return {"rendered": res.join(""), "newDefaultNs": newDefaultNs};
};

C14nCanonicalization.prototype.processInner = function(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces) {

  if (node.nodeType === 8) { return this.renderComment(node); }
  if (node.data) { return utils.encodeSpecialCharactersInText(node.data); }

  var i, pfxCopy
    , ns = this.renderNs(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces)
    , res = ["<", node.tagName, ns.rendered, this.renderAttrs(node, ns.newDefaultNs), ">"];

  for (i = 0; i < node.childNodes.length; ++i) {
    pfxCopy = prefixesInScope.slice(0);
    res.push(this.processInner(node.childNodes[i], pfxCopy, ns.newDefaultNs, defaultNsForPrefix, []));
  }

  res.push("</", node.tagName, ">");
  return res.join("");
};

// Thanks to deoxxa/xml-c14n for comment renderer
C14nCanonicalization.prototype.renderComment = function (node) {

  if (!this.includeComments) { return ""; }

  var isOutsideDocument = (node.ownerDocument === node.parentNode),
      isBeforeDocument = null,
      isAfterDocument = null;

  if (isOutsideDocument) {
    var nextNode = node,
        previousNode = node;

    while (nextNode !== null) {
      if (nextNode === node.ownerDocument.documentElement) {
        isBeforeDocument = true;
        break;
      }

      nextNode = nextNode.nextSibling;
    }

    while (previousNode !== null) {
      if (previousNode === node.ownerDocument.documentElement) {
        isAfterDocument = true;
        break;
      }

      previousNode = previousNode.previousSibling;
    }
  }

  return (isAfterDocument ? "\n" : "") + "<!--" + utils.encodeSpecialCharactersInText(node.data) + "-->" + (isBeforeDocument ? "\n" : "");
};

/**
 * Perform canonicalization of the given node
 *
 * @param {Node} node
 * @return {String}
 * @api public
 */
C14nCanonicalization.prototype.process = function(node, options) {
  options = options || {};
  var defaultNs = options.defaultNs || "";
  var defaultNsForPrefix = options.defaultNsForPrefix || {};
  var ancestorNamespaces = options.ancestorNamespaces || [];

  var prefixesInScope = [];
  for (var i = 0; i < ancestorNamespaces.length; i++) {
    prefixesInScope.push(ancestorNamespaces[i].prefix)
  }

  console.log({prefixesInScope})
  var res = this.processInner(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces);
  return res;
};

C14nCanonicalization.prototype.getAlgorithmName = function() {
  return "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
};

// Add c14n#WithComments here (very simple subclass)
exports.C14nCanonicalizationWithComments = C14nCanonicalizationWithComments;

function C14nCanonicalizationWithComments() {
	C14nCanonicalization.call(this);
	this.includeComments = true;
};

C14nCanonicalizationWithComments.prototype = Object.create(C14nCanonicalization.prototype);

C14nCanonicalizationWithComments.prototype.constructor = C14nCanonicalizationWithComments;

C14nCanonicalizationWithComments.prototype.getAlgorithmName = function() {
  return "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
};
<commit_msg>Remove accidental `console.log`<commit_after>/* jshint laxcomma: true */
var utils = require('./utils');

exports.C14nCanonicalization = C14nCanonicalization;
exports.C14nCanonicalizationWithComments = C14nCanonicalizationWithComments;

function C14nCanonicalization() {
	this.includeComments = false;
};

C14nCanonicalization.prototype.attrCompare = function(a,b) {
  if (!a.namespaceURI && b.namespaceURI) { return -1; }
  if (!b.namespaceURI && a.namespaceURI) { return 1; }

  var left = a.namespaceURI + a.localName
  var right = b.namespaceURI + b.localName

  if (left===right) return 0
  else if (left<right) return -1
  else return 1

};

C14nCanonicalization.prototype.nsCompare = function(a,b) {
  var attr1 = a.prefix;
  var attr2 = b.prefix;
  if (attr1 == attr2) { return 0; }
  return attr1.localeCompare(attr2);
};

C14nCanonicalization.prototype.renderAttrs = function(node, defaultNS) {
  var a, i, attr
    , res = []
    , attrListToRender = [];

  if (node.nodeType===8) { return this.renderComment(node); }

  if (node.attributes) {
    for (i = 0; i < node.attributes.length; ++i) {
      attr = node.attributes[i];
      //ignore namespace definition attributes
      if (attr.name.indexOf("xmlns") === 0) { continue; }
      attrListToRender.push(attr);
    }
  }

  attrListToRender.sort(this.attrCompare);

  for (a in attrListToRender) {
    if (!attrListToRender.hasOwnProperty(a)) { continue; }

    attr = attrListToRender[a];
    res.push(" ", attr.name, '="', utils.encodeSpecialCharactersInAttribute(attr.value), '"');
  }

  return res.join("");
};

/**
 * Create the string of all namespace declarations that should appear on this element
 *
 * @param {Node} node. The node we now render
 * @param {Array} prefixesInScope. The prefixes defined on this node
 *                parents which are a part of the output set
 * @param {String} defaultNs. The current default namespace
 * @param {String} defaultNsForPrefix.
 * @param {String} ancestorNamespaces - Import ancestor namespaces if it is specified
 * @return {String}
 * @api private
 */
C14nCanonicalization.prototype.renderNs = function(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces) {
  var a, i, p, attr
    , res = []
    , newDefaultNs = defaultNs
    , nsListToRender = []
    , currNs = node.namespaceURI || "";

  //handle the namespaceof the node itself
  if (node.prefix) {
    if (prefixesInScope.indexOf(node.prefix)==-1) {
      nsListToRender.push({"prefix": node.prefix, "namespaceURI": node.namespaceURI || defaultNsForPrefix[node.prefix]});
      prefixesInScope.push(node.prefix);
    }
  }
  else if (defaultNs!=currNs) {
      //new default ns
      newDefaultNs = node.namespaceURI;
      res.push(' xmlns="', newDefaultNs, '"');
  }

  //handle the attributes namespace
  if (node.attributes) {
    for (i = 0; i < node.attributes.length; ++i) {
      attr = node.attributes[i];

      //handle all prefixed attributes that are included in the prefix list and where
      //the prefix is not defined already. New prefixes can only be defined by `xmlns:`.
      if (attr.prefix === "xmlns" && prefixesInScope.indexOf(attr.localName) === -1) {
        nsListToRender.push({"prefix": attr.localName, "namespaceURI": attr.value});
        prefixesInScope.push(attr.localName);
      }

      //handle all prefixed attributes that are not xmlns definitions and where
      //the prefix is not defined already
      if (attr.prefix && prefixesInScope.indexOf(attr.prefix)==-1 && attr.prefix!="xmlns" && attr.prefix!="xml") {
        nsListToRender.push({"prefix": attr.prefix, "namespaceURI": attr.namespaceURI});
        prefixesInScope.push(attr.prefix);
      }
    }
  }

  if(Array.isArray(ancestorNamespaces) && ancestorNamespaces.length > 0){
    // Remove namespaces which are already present in nsListToRender
    for(var p1 in ancestorNamespaces){
      if(!ancestorNamespaces.hasOwnProperty(p1)) continue;
      var alreadyListed = false;
      for(var p2 in nsListToRender){
        if(nsListToRender[p2].prefix === ancestorNamespaces[p1].prefix
          && nsListToRender[p2].namespaceURI === ancestorNamespaces[p1].namespaceURI)
        {
          alreadyListed = true;
        }
      }

      if(!alreadyListed){
        nsListToRender.push(ancestorNamespaces[p1]);
      }
    }
  }

  nsListToRender.sort(this.nsCompare);

  //render namespaces
  for (a in nsListToRender) {
    if (!nsListToRender.hasOwnProperty(a)) { continue; }

    p = nsListToRender[a];
    res.push(" xmlns:", p.prefix, '="', p.namespaceURI, '"');
  }

  return {"rendered": res.join(""), "newDefaultNs": newDefaultNs};
};

C14nCanonicalization.prototype.processInner = function(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces) {

  if (node.nodeType === 8) { return this.renderComment(node); }
  if (node.data) { return utils.encodeSpecialCharactersInText(node.data); }

  var i, pfxCopy
    , ns = this.renderNs(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces)
    , res = ["<", node.tagName, ns.rendered, this.renderAttrs(node, ns.newDefaultNs), ">"];

  for (i = 0; i < node.childNodes.length; ++i) {
    pfxCopy = prefixesInScope.slice(0);
    res.push(this.processInner(node.childNodes[i], pfxCopy, ns.newDefaultNs, defaultNsForPrefix, []));
  }

  res.push("</", node.tagName, ">");
  return res.join("");
};

// Thanks to deoxxa/xml-c14n for comment renderer
C14nCanonicalization.prototype.renderComment = function (node) {

  if (!this.includeComments) { return ""; }

  var isOutsideDocument = (node.ownerDocument === node.parentNode),
      isBeforeDocument = null,
      isAfterDocument = null;

  if (isOutsideDocument) {
    var nextNode = node,
        previousNode = node;

    while (nextNode !== null) {
      if (nextNode === node.ownerDocument.documentElement) {
        isBeforeDocument = true;
        break;
      }

      nextNode = nextNode.nextSibling;
    }

    while (previousNode !== null) {
      if (previousNode === node.ownerDocument.documentElement) {
        isAfterDocument = true;
        break;
      }

      previousNode = previousNode.previousSibling;
    }
  }

  return (isAfterDocument ? "\n" : "") + "<!--" + utils.encodeSpecialCharactersInText(node.data) + "-->" + (isBeforeDocument ? "\n" : "");
};

/**
 * Perform canonicalization of the given node
 *
 * @param {Node} node
 * @return {String}
 * @api public
 */
C14nCanonicalization.prototype.process = function(node, options) {
  options = options || {};
  var defaultNs = options.defaultNs || "";
  var defaultNsForPrefix = options.defaultNsForPrefix || {};
  var ancestorNamespaces = options.ancestorNamespaces || [];

  var prefixesInScope = [];
  for (var i = 0; i < ancestorNamespaces.length; i++) {
    prefixesInScope.push(ancestorNamespaces[i].prefix)
  }

  var res = this.processInner(node, prefixesInScope, defaultNs, defaultNsForPrefix, ancestorNamespaces);
  return res;
};

C14nCanonicalization.prototype.getAlgorithmName = function() {
  return "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
};

// Add c14n#WithComments here (very simple subclass)
exports.C14nCanonicalizationWithComments = C14nCanonicalizationWithComments;

function C14nCanonicalizationWithComments() {
	C14nCanonicalization.call(this);
	this.includeComments = true;
};

C14nCanonicalizationWithComments.prototype = Object.create(C14nCanonicalization.prototype);

C14nCanonicalizationWithComments.prototype.constructor = C14nCanonicalizationWithComments;

C14nCanonicalizationWithComments.prototype.getAlgorithmName = function() {
  return "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
};
<|endoftext|>


<commit_before>if (!window.AppleFools) {
    AppleFools = {};
}

AppleFools.MainMenu = function () {
    this.selectAMode = null;
};

AppleFools.MainMenu.prototype.preload = function () {
    this.camera.bounds = null;
};

AppleFools.MainMenu.prototype.create = function () {
    this.selectAMode = this.add.text(145, 10, 'Select a mode');
    this.classicMode = this.add.button(40, 90, 'ball', this.gotoClassicMode, this);
    this.classicMode.width = 160;
    this.classicMode.height = 160;
    var tex = this.add.text(70, 135, 'Classic\nMode');
    this.afMode = this.add.button(280, 90, 'shapes', this.gotoAfMode, this, 'pen', 'apple', 'pineapple', 'pen');
    this.afMode.width = 160;
    this.afMode.height = 160;
    var tex = this.add.text(325, 170, 'Apple\nFools');
    this.music = this.add.sound('music');
    this.music.loop = true;
    this.music.play();
};

AppleFools.MainMenu.prototype.update = function () {
    var w = this.game.width, h = this.game.height;
    if (w > h * 4/3) {
        this.camera.scale.x = h/360;
        this.camera.scale.y = h/360;
        this.camera.setPosition(-(w - h * 4/3) /2, 0);
    }
    else {
        this.camera.scale.x = w/480;
        this.camera.scale.y = w/480;
        this.camera.setPosition(0, -(h - w * 3/4) / 2);
    }
};

AppleFools.MainMenu.prototype.shutdown = function () {
    this.camera.reset();
    this.camera.scale.x = this.camera.scale.y = 1;
    this.music.destroy();
    this.music = null;
};

AppleFools.MainMenu.prototype.gotoClassicMode = function () {
    AppleFools.chooseMode('classic');
    this.state.start("GameScreen");
};

AppleFools.MainMenu.prototype.gotoAfMode = function () {
    var me = this;
    AppleFools.getLife(function (result) {
        if (result) {
            AppleFools.chooseMode('AppleFools');
            me.state.start("GameScreen");
        }
        else {
            alertBox('Sorry... Server is busy. Please try again. (You can still play Classic Mode)');
        }
    });
};
<commit_msg>fix Apple Fools resolution issue<commit_after>if (!window.AppleFools) {
    AppleFools = {};
}

AppleFools.MainMenu = function () {
    this.selectAMode = null;
};

AppleFools.MainMenu.prototype.preload = function () {
    this.camera.bounds = null;
};

AppleFools.MainMenu.prototype.create = function () {
    this.selectAMode = this.add.text(145, 10, 'Select a mode');
    this.classicMode = this.add.button(40, 90, 'ball', this.gotoClassicMode, this);
    this.classicMode.width = 160 * this.game.resolution;
    this.classicMode.height = 160 * this.game.resolution;
    var tex = this.add.text(70, 135, 'Classic\nMode');
    this.afMode = this.add.button(280, 90, 'shapes', this.gotoAfMode, this, 'pen', 'apple', 'pineapple', 'pen');
    this.afMode.width = 160 * this.game.resolution;
    this.afMode.height = 160 * this.game.resolution;
    var tex = this.add.text(325, 170, 'Apple\nFools');
    this.music = this.add.sound('music');
    this.music.loop = true;
    this.music.play();
};

AppleFools.MainMenu.prototype.update = function () {
    var w = this.game.width, h = this.game.height;
    if (w > h * 4/3) {
        this.camera.scale.x = h/360;
        this.camera.scale.y = h/360;
        this.camera.setPosition(-(w - h * 4/3) /2, 0);
    }
    else {
        this.camera.scale.x = w/480;
        this.camera.scale.y = w/480;
        this.camera.setPosition(0, -(h - w * 3/4) / 2);
    }
};

AppleFools.MainMenu.prototype.shutdown = function () {
    this.camera.reset();
    this.camera.scale.x = this.camera.scale.y = 1;
    this.music.destroy();
    this.music = null;
};

AppleFools.MainMenu.prototype.gotoClassicMode = function () {
    AppleFools.chooseMode('classic');
    this.state.start("GameScreen");
};

AppleFools.MainMenu.prototype.gotoAfMode = function () {
    var me = this;
    AppleFools.getLife(function (result) {
        if (result) {
            AppleFools.chooseMode('AppleFools');
            me.state.start("GameScreen");
        }
        else {
            alertBox('Sorry... Server is busy. Please try again. (You can still play Classic Mode)');
        }
    });
};
<|endoftext|>


<commit_before>/**
 * Nodeunit functional tests.  Requires internet connection to validate slimer
 * functions correctly.
 */

var childProcess = require('child_process')
var fs = require('fs')
var path = require('path')
var slimerjs = require('../lib/slimerjs')

exports.testDownload = function (test) {
  test.expect(1)
  test.ok(fs.existsSync(slimerjs.path), 'Binary file should have been downloaded')
  test.done()
}

exports.testSlimerExecutesTestScript = function (test) {
  test.expect(1)

  var childArgs = [
    path.join(__dirname, 'loadspeed.js'),
    'http://www.google.com/'
  ]

  childProcess.execFile(slimerjs.path, childArgs, function (err, stdout, stderr) {
    console.log([stdout, stderr]);

    var value = (stdout.indexOf('msec') !== -1)
    test.ok(value, 'Test script should have executed and returned run time')
    test.done()
  })
}

exports.testBinFile = function (test) {
  test.expect(1)

  var binPath = process.platform === 'win32' ?
      path.join(__dirname, '..', 'lib', 'slimer', 'slimerjs.exe') :
      path.join(__dirname, '..', 'bin', 'slimerjs')

  childProcess.execFile(binPath, ['--version'], function (err, stdout, stderr) {
    test.ok(stdout.trim().indexOf(slimerjs.version) >= -1, 'Version should be match')
    test.done()
  })
}

exports.testCleanPath = function (test) {
  test.expect(5)
  test.equal('/Users/dan/bin', slimerjs.cleanPath('/Users/dan/bin:./bin'))
  test.equal('/Users/dan/bin:/usr/bin', slimerjs.cleanPath('/Users/dan/bin:./bin:/usr/bin'))
  test.equal('/usr/bin', slimerjs.cleanPath('./bin:/usr/bin'))
  test.equal('', slimerjs.cleanPath('./bin'))
  test.equal('/Work/bin:/usr/bin', slimerjs.cleanPath('/Work/bin:/Work/slimerjs/node_modules/.bin:/usr/bin'))
  test.done()
}
<commit_msg>More debugging - print "err"<commit_after>/**
 * Nodeunit functional tests.  Requires internet connection to validate slimer
 * functions correctly.
 */

var childProcess = require('child_process')
var fs = require('fs')
var path = require('path')
var slimerjs = require('../lib/slimerjs')

exports.testDownload = function (test) {
  test.expect(1)
  test.ok(fs.existsSync(slimerjs.path), 'Binary file should have been downloaded')
  test.done()
}

exports.testSlimerExecutesTestScript = function (test) {
  test.expect(1)

  var childArgs = [
    path.join(__dirname, 'loadspeed.js'),
    'http://www.google.com/'
  ]

  childProcess.execFile(slimerjs.path, childArgs, function (err, stdout, stderr) {
    console.log([err, stdout, stderr]);

    var value = (stdout.indexOf('msec') !== -1)
    test.ok(value, 'Test script should have executed and returned run time')
    test.done()
  })
}

exports.testBinFile = function (test) {
  test.expect(1)

  var binPath = process.platform === 'win32' ?
      path.join(__dirname, '..', 'lib', 'slimer', 'slimerjs.exe') :
      path.join(__dirname, '..', 'bin', 'slimerjs')

  childProcess.execFile(binPath, ['--version'], function (err, stdout, stderr) {
    test.ok(stdout.trim().indexOf(slimerjs.version) >= -1, 'Version should be match')
    test.done()
  })
}

exports.testCleanPath = function (test) {
  test.expect(5)
  test.equal('/Users/dan/bin', slimerjs.cleanPath('/Users/dan/bin:./bin'))
  test.equal('/Users/dan/bin:/usr/bin', slimerjs.cleanPath('/Users/dan/bin:./bin:/usr/bin'))
  test.equal('/usr/bin', slimerjs.cleanPath('./bin:/usr/bin'))
  test.equal('', slimerjs.cleanPath('./bin'))
  test.equal('/Work/bin:/usr/bin', slimerjs.cleanPath('/Work/bin:/Work/slimerjs/node_modules/.bin:/usr/bin'))
  test.done()
}
<|endoftext|>


<commit_before>'use strict';
import logger from './logger';
import TradeInfo from './tradeInfo';
import account from 'binary-common-utils/account';
import Observer from 'binary-common-utils/observer';
import _Blockly from './blockly';
import storageManager from 'binary-common-utils/storageManager';
import Translator from 'translator';
import Bot from '../bot';
import Introduction from './tours/introduction';
import Welcome from './tours/welcome';
import {PlainChart as Chart} from 'binary-charts';
import lzString from 'lz-string';
import _ from 'underscore';

var View = function View(){
	if ( View.instance ) {
		return View.instance;
	}
	this.observer = new Observer();
	View.instance = this;
	this.chartType = 'area';
	this.tours = {};
	this.translator = new Translator();
	this.tradeInfo = new TradeInfo();
	this.addTranslationToUi();
	this.errorAndLogHandling();
	var that = this;
	this.bot = new Bot();
	this.initPromise = new Promise(function(resolve, reject){
		that.updateTokenList();
		that.blockly = new _Blockly();
		that.blockly.initPromise.then(function(){
			that.setElementActions();
			that.initTours();
			resolve();
		});
	});
};

View.prototype = Object.create(null, {
	updateTokenList: {
		value: function updateTokenList() {
			var tokenList = storageManager.getTokenList();
			if (tokenList.length === 0) {
				$('#login').css('display', 'inline-block');
				$('#accountSelect').css('display', 'none');
				$('#logout').css('display', 'none');
			} else {
				$('#login').css('display', 'none');
				$('#accountSelect').css('display', 'inline-block');
				$('#logout').css('display', 'inline-block');
				tokenList.forEach(function (tokenInfo) {
					var str;
					if ( tokenInfo.hasOwnProperty('isVirtual') ) {
						str = (tokenInfo.isVirtual) ? 'Virtual Account' : 'Real Account';
					} else {
						str = '';
					}
					$('#accountSelect').append('<option value="' + tokenInfo.token + '">'+str + ' (' + tokenInfo.account_name+ ') ' + '</option>');
				});
			}
		}
	},
	addTranslationToUi: {
		value: function addTranslationToUi(){
			var that = this;
			$('[data-i18n-text]')
				.each(function() {
						var contents = $(this).contents();
						if (contents.length > 0) {
								if (contents.get(0).nodeType == Node.TEXT_NODE) {
										$(this).text(that.translator.translateText($(this)
								.attr('data-i18n-text')))
								.append(contents.slice(1));
								}
						} else {
						$(this)
							.text(that.translator.translateText($(this)
								.attr('data-i18n-text')));
					}
				});
		}
	},
	initTours: {
		value: function initTours() {
			this.tours.introduction = new Introduction();
			this.tours.welcome = new Welcome();
		}
	},
	startTour: {
		value: function startTour() {
			var that = this;
			$('#tours').on('change', function(e) {
					var value = $(this).val();
					if (value === '') return;
					if (that.activeTour) {
						that.activeTour.stop();
					}
					that.activeTour = that.tours[value];
					that.activeTour.start(function(){
						that.activeTour = null;
					});
			});
		}
	},
	errorAndLogHandling: {
		value: function errorAndLogHandling(){

			var that = this;

			this.observer.register('ui.error', function showError(error) {
				var api = true;
				if (error.stack) {
					api = false;
					if (logger.isDebug()) {
						console.log('%c' + error.stack, 'color: red');
					} else {
						logger.addLogToQueue('%c' + error.stack, 'color: red');
					}
				}
				var message = error.message;
				$.notify(message, {
					position: 'bottom right',
					className: 'error',
				});
				if (logger.isDebug()) {
					console.log('%cError: ' + message, 'color: red');
				} else {
					logger.addLogToQueue('%cError: ' + message, 'color: red');
				}
				var customError = new Error(JSON.stringify({
					api: api,
					0: error.message,
					1: lzString.compressToBase64(that.blockly.generatedJs),
					2: lzString.compressToBase64(that.blockly.blocksXmlStr)
				}));
				customError.stack = error.stack;
				trackJs.track(customError);
			});

			var observeForLog = function observeForLog(type, position) {
				var subtype = ( position === 'left' )? '.left' : '';
				that.observer.register('ui.log.' + type + subtype , function(message){
					if ( type === 'warn' ) {
						console.warn(message);
					}
					$.notify(message, {
						position: 'bottom ' + position,
						className: type,
					});
					if (logger.isDebug()) {
						console.log(message);
					} else {
						logger.addLogToQueue(message);
					}
				});
			};

			["success", "info", "warn", "error"].forEach(function(type){
				observeForLog(type, 'right');
				observeForLog(type, 'left');
			});

		}
	},
	setFileBrowser: {
		value: function setFileBrowser(){
			var that = this;
			var handleFileSelect = function handleFileSelect(e) {
				var files;
				if (e.type === 'drop') {
					e.stopPropagation();
					e.preventDefault();
					files = e.dataTransfer.files;
				} else {
					files = e.target.files;
				}
				files = Array.prototype.slice.apply(files);
				var file = files[0];
				if (file) {
					if (file.type.match('text/xml')) {
						readFile(file);
					} else {
						that.observer.emit('ui.log.info', that.translator.translateText('File is not supported:' + ' ') + file.name);
					}
				}
			};

			var readFile = function readFile(f) {
				var reader = new FileReader();
				reader.onload = (function (theFile) {
					$('#fileBrowser').hide();
					return function (e) {
						try {
							that.blockly.loadBlocks(e.target.result);
							that.observer.emit('ui.log.success', that.translator.translateText('Blocks are loaded successfully'));
						} catch (err) {
							that.observer.emit('ui.error', err);
						}
					};
				})(f);
				reader.readAsText(f);
			};

			var handleDragOver = function handleDragOver(e) {
				e.stopPropagation();
				e.preventDefault();
				e.dataTransfer.dropEffect = 'copy';
			};

			var dropZone = document.getElementById('dropZone');

			dropZone.addEventListener('dragover', handleDragOver, false);
			dropZone.addEventListener('drop', handleFileSelect, false);
			if (document.getElementById('files')) {
				document.getElementById('files')
					.addEventListener('change', handleFileSelect, false);
			}
			$('#open_btn')
				.on('click', function() {
					$.FileDialog({
						accept: ".xml",
						cancelButton: "Close",
						dragMessage: "Drop files here",
						dropheight: 400,
						errorMessage: "An error occured while loading file",
						multiple: false,
						okButton: "OK",
						readAs: "DataURL",
						removeMessage: "Remove file",
						title: "Load file"
					});
				})
				.on('files.bs.filedialog', function(ev) {
					var files_list = ev.files;
					handleFileSelect(files_list);
				})
				.on('cancel.bs.filedialog', function(ev) {
					handleFileSelect(ev);
				});
		}
	},
	setElementActions: {
		value: function setElementActions(){
			this.setFileBrowser();
			this.startTour();
			this.addBindings();
			this.addEventHandlers();
			this.tradeInfo.show();
		}
	},
	addBindings: {
		value: function addBindings(){
			var that = this;
			var stop = function stop(e) {
				if (e) {
					e.preventDefault();
				}
				that.bot.stop();
			};

			var logout = function logout() {
				account.logoutAllTokens(function(){
					that.updateTokenList();
					that.observer.emit('ui.log.info', that.translator.translateText('Logged you out!'));
				});
			};

			$('#stopButton')
				.click(stop)
				.hide();

			$('.panelExitButton')
				.click(function () {
					$(this)
						.parent()
						.hide();
				});

			$('.panel')
				.hide();

			$('.panel')
				.drags();

			$('#chart')
				.mousedown(function (e) { // prevent chart to trigger draggable
					e.stopPropagation();
				});

			$('table')
				.mousedown(function (e) { // prevent tables to trigger draggable
					e.stopPropagation();
				});

			$('#saveXml')
				.click(function (e) {
					that.blockly.saveXml();
				});

			$('#undo')
				.click(function (e) {
					that.blockly.undo();
				});

			$('#redo')
				.click(function (e) {
					that.blockly.redo();
				});

			$('#showSummary')
				.click(function (e) {
					$('#summaryPanel')
						.show();
				});

		 $('#loadXml')
				.click(function (e) {
					$('#fileBrowser')
						.show();
				});

			$('#logout')
				.click(function (e) {
					logout();
					$('.logout').hide();
				});

			$('#runButton')
				.click(function (e) {
					$('#stopButton').show();
					$('#runButton').hide();
					that.blockly.run();
				});

			$('#resetButton')
				.click(function (e) {
					that.blockly.loadBlocks();
				});

			$('#login')
				.bind('click.login', function(e){
					document.location = 'https://oauth.binary.com/oauth2/authorize?app_id=' + storageManager.get('appId') + '&l=' + that.translator.getLanguage().toUpperCase();
				})
				.text('Log in');

			$(document).keydown(function(e) {
				switch(e.which) {
					case 189: // -
						if ( e.ctrlKey ) {
							that.blockly.zoomOnPlusMinus(false);
						}
						break;
					case 187: // +
						if ( e.ctrlKey ) {
							that.blockly.zoomOnPlusMinus(true);
						}
						break;
					case 39: // right
						if (that.activeTour) {
							that.activeTour.next();
						} else {
							return;
						}
						break;
					default: return; // exit this handler for other keys
				}
				e.preventDefault(); // prevent the default action (scroll / move caret)
			});

		}
	},
	updateChart: {
		value: function updateChart(info) {
			var that = this;
			var chartOptions = {
				type: this.chartType,
				theme: 'light',
			};
			if ( this.chartType === 'candlestick' ) {
				chartOptions.ticks = info.candles;
			} else {
				chartOptions.ticks = info.ticks;
			}
			if (this.latestOpenContract) {
				chartOptions.contract = this.latestOpenContract;
				if (this.latestOpenContract.is_sold) {
					delete this.latestOpenContract;
				}
			}
			chartOptions.pipSize = Number(Number(info.pip)
				.toExponential()
				.substring(3));
			if (!this.chart) {
				this.chart = Chart('chart', chartOptions);
			} else {
				this.chart.updateChart(chartOptions);
			}
		}
	},
	addEventHandlers: {
		value: function addEventHandlers() {
			var that = this;

			this.observer.register('api.error', function(error){
				if (error.code === 'InvalidToken'){
					storageManager.removeAllTokens();
					that.updateTokenList();
				}
				that.bot.stop();
				that.observer.emit('ui.error', error);
			});

			this.observer.register('bot.stop', function(tradeInfo){
				$('#runButton').show();
				$('#stopButton').hide();
			});

			this.observer.register('bot.tradeInfo', function(tradeInfo){
				_.extend(that.tradeInfo.tradeInfo, tradeInfo);
				that.tradeInfo.update();
			});

			this.observer.register('bot.tradeUpdate', function(contract){
				that.latestOpenContract = contract;
			});

			this.observer.register('bot.finish', function(contract){
				that.tradeInfo.add(contract);
			});

			this.observer.register('bot.tickUpdate', function(info){
				that.updateChart(info);
			});
		}
	}
});

module.exports = View;
<commit_msg>Added empty stack message for the api errors<commit_after>'use strict';
import logger from './logger';
import TradeInfo from './tradeInfo';
import account from 'binary-common-utils/account';
import Observer from 'binary-common-utils/observer';
import _Blockly from './blockly';
import storageManager from 'binary-common-utils/storageManager';
import Translator from 'translator';
import Bot from '../bot';
import Introduction from './tours/introduction';
import Welcome from './tours/welcome';
import {PlainChart as Chart} from 'binary-charts';
import lzString from 'lz-string';
import _ from 'underscore';

var View = function View(){
	if ( View.instance ) {
		return View.instance;
	}
	this.observer = new Observer();
	View.instance = this;
	this.chartType = 'area';
	this.tours = {};
	this.translator = new Translator();
	this.tradeInfo = new TradeInfo();
	this.addTranslationToUi();
	this.errorAndLogHandling();
	var that = this;
	this.bot = new Bot();
	this.initPromise = new Promise(function(resolve, reject){
		that.updateTokenList();
		that.blockly = new _Blockly();
		that.blockly.initPromise.then(function(){
			that.setElementActions();
			that.initTours();
			resolve();
		});
	});
};

View.prototype = Object.create(null, {
	updateTokenList: {
		value: function updateTokenList() {
			var tokenList = storageManager.getTokenList();
			if (tokenList.length === 0) {
				$('#login').css('display', 'inline-block');
				$('#accountSelect').css('display', 'none');
				$('#logout').css('display', 'none');
			} else {
				$('#login').css('display', 'none');
				$('#accountSelect').css('display', 'inline-block');
				$('#logout').css('display', 'inline-block');
				tokenList.forEach(function (tokenInfo) {
					var str;
					if ( tokenInfo.hasOwnProperty('isVirtual') ) {
						str = (tokenInfo.isVirtual) ? 'Virtual Account' : 'Real Account';
					} else {
						str = '';
					}
					$('#accountSelect').append('<option value="' + tokenInfo.token + '">'+str + ' (' + tokenInfo.account_name+ ') ' + '</option>');
				});
			}
		}
	},
	addTranslationToUi: {
		value: function addTranslationToUi(){
			var that = this;
			$('[data-i18n-text]')
				.each(function() {
						var contents = $(this).contents();
						if (contents.length > 0) {
								if (contents.get(0).nodeType == Node.TEXT_NODE) {
										$(this).text(that.translator.translateText($(this)
								.attr('data-i18n-text')))
								.append(contents.slice(1));
								}
						} else {
						$(this)
							.text(that.translator.translateText($(this)
								.attr('data-i18n-text')));
					}
				});
		}
	},
	initTours: {
		value: function initTours() {
			this.tours.introduction = new Introduction();
			this.tours.welcome = new Welcome();
		}
	},
	startTour: {
		value: function startTour() {
			var that = this;
			$('#tours').on('change', function(e) {
					var value = $(this).val();
					if (value === '') return;
					if (that.activeTour) {
						that.activeTour.stop();
					}
					that.activeTour = that.tours[value];
					that.activeTour.start(function(){
						that.activeTour = null;
					});
			});
		}
	},
	errorAndLogHandling: {
		value: function errorAndLogHandling(){

			var that = this;

			this.observer.register('ui.error', function showError(error) {
				var api = true;
				if (error.stack) {
					api = false;
					if (logger.isDebug()) {
						console.log('%c' + error.stack, 'color: red');
					} else {
						logger.addLogToQueue('%c' + error.stack, 'color: red');
					}
				}
				var message = error.message;
				$.notify(message, {
					position: 'bottom right',
					className: 'error',
				});
				if (logger.isDebug()) {
					console.log('%cError: ' + message, 'color: red');
				} else {
					logger.addLogToQueue('%cError: ' + message, 'color: red');
				}
				var customError = new Error(JSON.stringify({
					api: api,
					0: error.message || error,
					1: lzString.compressToBase64(that.blockly.generatedJs),
					2: lzString.compressToBase64(that.blockly.blocksXmlStr)
				}));
				customError.stack = error.stack || 'No stack data';
				trackJs.track(customError);
			});

			var observeForLog = function observeForLog(type, position) {
				var subtype = ( position === 'left' )? '.left' : '';
				that.observer.register('ui.log.' + type + subtype , function(message){
					if ( type === 'warn' ) {
						console.warn(message);
					}
					$.notify(message, {
						position: 'bottom ' + position,
						className: type,
					});
					if (logger.isDebug()) {
						console.log(message);
					} else {
						logger.addLogToQueue(message);
					}
				});
			};

			["success", "info", "warn", "error"].forEach(function(type){
				observeForLog(type, 'right');
				observeForLog(type, 'left');
			});

		}
	},
	setFileBrowser: {
		value: function setFileBrowser(){
			var that = this;
			var handleFileSelect = function handleFileSelect(e) {
				var files;
				if (e.type === 'drop') {
					e.stopPropagation();
					e.preventDefault();
					files = e.dataTransfer.files;
				} else {
					files = e.target.files;
				}
				files = Array.prototype.slice.apply(files);
				var file = files[0];
				if (file) {
					if (file.type.match('text/xml')) {
						readFile(file);
					} else {
						that.observer.emit('ui.log.info', that.translator.translateText('File is not supported:' + ' ') + file.name);
					}
				}
			};

			var readFile = function readFile(f) {
				var reader = new FileReader();
				reader.onload = (function (theFile) {
					$('#fileBrowser').hide();
					return function (e) {
						try {
							that.blockly.loadBlocks(e.target.result);
							that.observer.emit('ui.log.success', that.translator.translateText('Blocks are loaded successfully'));
						} catch (err) {
							that.observer.emit('ui.error', err);
						}
					};
				})(f);
				reader.readAsText(f);
			};

			var handleDragOver = function handleDragOver(e) {
				e.stopPropagation();
				e.preventDefault();
				e.dataTransfer.dropEffect = 'copy';
			};

			var dropZone = document.getElementById('dropZone');

			dropZone.addEventListener('dragover', handleDragOver, false);
			dropZone.addEventListener('drop', handleFileSelect, false);
			if (document.getElementById('files')) {
				document.getElementById('files')
					.addEventListener('change', handleFileSelect, false);
			}
			$('#open_btn')
				.on('click', function() {
					$.FileDialog({
						accept: ".xml",
						cancelButton: "Close",
						dragMessage: "Drop files here",
						dropheight: 400,
						errorMessage: "An error occured while loading file",
						multiple: false,
						okButton: "OK",
						readAs: "DataURL",
						removeMessage: "Remove file",
						title: "Load file"
					});
				})
				.on('files.bs.filedialog', function(ev) {
					var files_list = ev.files;
					handleFileSelect(files_list);
				})
				.on('cancel.bs.filedialog', function(ev) {
					handleFileSelect(ev);
				});
		}
	},
	setElementActions: {
		value: function setElementActions(){
			this.setFileBrowser();
			this.startTour();
			this.addBindings();
			this.addEventHandlers();
			this.tradeInfo.show();
		}
	},
	addBindings: {
		value: function addBindings(){
			var that = this;
			var stop = function stop(e) {
				if (e) {
					e.preventDefault();
				}
				that.bot.stop();
			};

			var logout = function logout() {
				account.logoutAllTokens(function(){
					that.updateTokenList();
					that.observer.emit('ui.log.info', that.translator.translateText('Logged you out!'));
				});
			};

			$('#stopButton')
				.click(stop)
				.hide();

			$('.panelExitButton')
				.click(function () {
					$(this)
						.parent()
						.hide();
				});

			$('.panel')
				.hide();

			$('.panel')
				.drags();

			$('#chart')
				.mousedown(function (e) { // prevent chart to trigger draggable
					e.stopPropagation();
				});

			$('table')
				.mousedown(function (e) { // prevent tables to trigger draggable
					e.stopPropagation();
				});

			$('#saveXml')
				.click(function (e) {
					that.blockly.saveXml();
				});

			$('#undo')
				.click(function (e) {
					that.blockly.undo();
				});

			$('#redo')
				.click(function (e) {
					that.blockly.redo();
				});

			$('#showSummary')
				.click(function (e) {
					$('#summaryPanel')
						.show();
				});

		 $('#loadXml')
				.click(function (e) {
					$('#fileBrowser')
						.show();
				});

			$('#logout')
				.click(function (e) {
					logout();
					$('.logout').hide();
				});

			$('#runButton')
				.click(function (e) {
					$('#stopButton').show();
					$('#runButton').hide();
					that.blockly.run();
				});

			$('#resetButton')
				.click(function (e) {
					that.blockly.loadBlocks();
				});

			$('#login')
				.bind('click.login', function(e){
					document.location = 'https://oauth.binary.com/oauth2/authorize?app_id=' + storageManager.get('appId') + '&l=' + that.translator.getLanguage().toUpperCase();
				})
				.text('Log in');

			$(document).keydown(function(e) {
				switch(e.which) {
					case 189: // -
						if ( e.ctrlKey ) {
							that.blockly.zoomOnPlusMinus(false);
						}
						break;
					case 187: // +
						if ( e.ctrlKey ) {
							that.blockly.zoomOnPlusMinus(true);
						}
						break;
					case 39: // right
						if (that.activeTour) {
							that.activeTour.next();
						} else {
							return;
						}
						break;
					default: return; // exit this handler for other keys
				}
				e.preventDefault(); // prevent the default action (scroll / move caret)
			});

		}
	},
	updateChart: {
		value: function updateChart(info) {
			var that = this;
			var chartOptions = {
				type: this.chartType,
				theme: 'light',
			};
			if ( this.chartType === 'candlestick' ) {
				chartOptions.ticks = info.candles;
			} else {
				chartOptions.ticks = info.ticks;
			}
			if (this.latestOpenContract) {
				chartOptions.contract = this.latestOpenContract;
				if (this.latestOpenContract.is_sold) {
					delete this.latestOpenContract;
				}
			}
			chartOptions.pipSize = Number(Number(info.pip)
				.toExponential()
				.substring(3));
			if (!this.chart) {
				this.chart = Chart('chart', chartOptions);
			} else {
				this.chart.updateChart(chartOptions);
			}
		}
	},
	addEventHandlers: {
		value: function addEventHandlers() {
			var that = this;

			this.observer.register('api.error', function(error){
				if (error.code === 'InvalidToken'){
					storageManager.removeAllTokens();
					that.updateTokenList();
				}
				that.bot.stop();
				that.observer.emit('ui.error', error);
			});

			this.observer.register('bot.stop', function(tradeInfo){
				$('#runButton').show();
				$('#stopButton').hide();
			});

			this.observer.register('bot.tradeInfo', function(tradeInfo){
				_.extend(that.tradeInfo.tradeInfo, tradeInfo);
				that.tradeInfo.update();
			});

			this.observer.register('bot.tradeUpdate', function(contract){
				that.latestOpenContract = contract;
			});

			this.observer.register('bot.finish', function(contract){
				that.tradeInfo.add(contract);
			});

			this.observer.register('bot.tickUpdate', function(info){
				that.updateChart(info);
			});
		}
	}
});

module.exports = View;
<|endoftext|>


<commit_before>// Copyright (c) 2012 UX Productivity Pty Ltd. All rights reserved.

var Tables_insertTable;
var Tables_insertRowsAbove;
var Tables_insertRowsBelow;
var Tables_insertColumnsLeft;
var Tables_insertColumnsRight;
var Tables_deleteRows;
var Tables_deleteColumns;
var Tables_clearCells;
var Tables_mergeCells;
var Tables_splitCell;
var Tables_analyseStructure;
var Tables_findContainingCell;
var Tables_findContainingTable;

(function() {

    function Cell(element,row,col)
    {
        this.element = element;
        this.row = row;
        this.col = col;

        if (element.hasAttribute("colspan"))
            this.colspan = parseInt(element.getAttribute("colspan"));
        else
            this.colspan = 1;
        if (element.hasAttribute("rowspan"))
            this.rowspan = parseInt(element.getAttribute("rowspan"));
        else
            this.rowspan = 1;

        if (this.colspan < 1)
            this.colspan = 1;
        if (this.rowspan < 1)
            this.rowspan = 1;
    }

    function Table(element)
    {
        this.row = 0;
        this.col = 0;
        this.cells = new Array();
        this.numRows = 0;
        this.numCols = 0;
        this.translated = false;
        this.cellsByElement = new NodeMap();
        this.processTable(element);
    }

    Table.prototype.set = function(row,col,cell)
    {
        if (this.numRows < row+1)
            this.numRows = row+1;
        if (this.numCols < col+1)
            this.numCols = col+1;
        if (this.cells[row] == null)
            this.cells[row] = new Array();
        this.cells[row][col] = cell;
    }

    Table.prototype.get = function(row,col)
    {
        if (this.cells[row] == null)
            return null;
        return this.cells[row][col];
    }

    Table.prototype.processTable = function(node)
    {
        if ((DOM_upperName(node) == "TD") || (DOM_upperName(node) == "TH")) {
            var cell = new Cell(node,this.row,this.col);
            this.cellsByElement.put(node,cell);

            while (this.get(this.row,this.col) != null)
                this.col++;

            for (var r = 0; r < cell.rowspan; r++) {
                for (var c = 0; c < cell.colspan; c++) {
                    this.set(this.row+r,this.col+c,cell);
                }
            }
            this.col += cell.colspan;
        }
        else if (DOM_upperName(node) == "TR") {
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                this.processTable(child);
            this.row++;
            this.col = 0;
        }
        else {
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                this.processTable(child);
        }
    }

    // public
    function insertTable(rows,cols,numbered,caption)
    {
        var table = DOM_createElement(document,"TABLE");

        // Probably the most sensible defaults for now
        table.setAttribute("border","1");
        table.setAttribute("width","100%");

        // Caption comes first
        if ((caption != null) && (caption != "")) {
            var tableCaption = DOM_createElement(document,"CAPTION");
            tableCaption.appendChild(DOM_createTextNode(document,caption));
            DOM_appendChild(table,tableCaption);
        }

        // Then the rows and columns
        for (var r = 0; r < rows; r++) {
            var tr = DOM_createElement(document,"TR");
            DOM_appendChild(table,tr);
            for (var c = 0; c < cols; c++) {
                var td = DOM_createElement(document,"TD");
                var p = DOM_createElement(document,"P");
                var br = DOM_createElement(document,"BR");
                DOM_appendChild(tr,td);
                DOM_appendChild(td,p);
                DOM_appendChild(p,br);
            }
        }

        Clipboard_pasteNodes([table]);
    }

    // public
    function insertRowsAbove(rows)
    {
    }

    // public
    function insertRowsBelow(rows)
    {
    }

    // public
    function insertColumnsLeft(cols)
    {
    }

    // public
    function insertColumnsRight(cols)
    {
    }

    // public
    function deleteRows()
    {
    }

    // public
    function deleteColumns()
    {
    }

    // public
    function clearCells()
    {
    }

    // public
    function mergeCells()
    {
    }

    // public
    function splitCell()
    {
    }

    // public
    function analyseStructure(element)
    {
        return new Table(element);
    }

    // public
    function findContainingCell(node)
    {
        for (var ancestor = node; ancestor != null; ancestor = ancestor.parentNode) {
            if (isTableCell(ancestor))
                return ancestor;
        }
        return null;
    }

    // public
    function findContainingTable(node)
    {
        for (var ancestor = node; ancestor != null; ancestor = ancestor.parentNode) {
            if (isTableNode(ancestor))
                return ancestor;
        }
        return null;
    }

    Tables_insertTable = trace(insertTable);
    Tables_insertRowsAbove = trace(insertRowsAbove);
    Tables_insertRowsBelow = trace(insertRowsBelow);
    Tables_insertColumnsLeft = trace(insertColumnsLeft);
    Tables_insertColumnsRight = trace(insertColumnsRight);
    Tables_deleteRows = trace(deleteRows);
    Tables_deleteColumns = trace(deleteColumns);
    Tables_clearCells = trace(clearCells);
    Tables_mergeCells = trace(mergeCells);
    Tables_splitCell = trace(splitCell);
    Tables_analyseStructure = trace(analyseStructure);
    Tables_findContainingCell = trace(findContainingCell);
    Tables_findContainingTable = trace(findContainingTable);

})();
<commit_msg>Made it possible to specify the width of a table when inserting<commit_after>// Copyright (c) 2012 UX Productivity Pty Ltd. All rights reserved.

var Tables_insertTable;
var Tables_insertRowsAbove;
var Tables_insertRowsBelow;
var Tables_insertColumnsLeft;
var Tables_insertColumnsRight;
var Tables_deleteRows;
var Tables_deleteColumns;
var Tables_clearCells;
var Tables_mergeCells;
var Tables_splitCell;
var Tables_analyseStructure;
var Tables_findContainingCell;
var Tables_findContainingTable;

(function() {

    function Cell(element,row,col)
    {
        this.element = element;
        this.row = row;
        this.col = col;

        if (element.hasAttribute("colspan"))
            this.colspan = parseInt(element.getAttribute("colspan"));
        else
            this.colspan = 1;
        if (element.hasAttribute("rowspan"))
            this.rowspan = parseInt(element.getAttribute("rowspan"));
        else
            this.rowspan = 1;

        if (this.colspan < 1)
            this.colspan = 1;
        if (this.rowspan < 1)
            this.rowspan = 1;
    }

    function Table(element)
    {
        this.row = 0;
        this.col = 0;
        this.cells = new Array();
        this.numRows = 0;
        this.numCols = 0;
        this.translated = false;
        this.cellsByElement = new NodeMap();
        this.processTable(element);
    }

    Table.prototype.set = function(row,col,cell)
    {
        if (this.numRows < row+1)
            this.numRows = row+1;
        if (this.numCols < col+1)
            this.numCols = col+1;
        if (this.cells[row] == null)
            this.cells[row] = new Array();
        this.cells[row][col] = cell;
    }

    Table.prototype.get = function(row,col)
    {
        if (this.cells[row] == null)
            return null;
        return this.cells[row][col];
    }

    Table.prototype.processTable = function(node)
    {
        if ((DOM_upperName(node) == "TD") || (DOM_upperName(node) == "TH")) {
            var cell = new Cell(node,this.row,this.col);
            this.cellsByElement.put(node,cell);

            while (this.get(this.row,this.col) != null)
                this.col++;

            for (var r = 0; r < cell.rowspan; r++) {
                for (var c = 0; c < cell.colspan; c++) {
                    this.set(this.row+r,this.col+c,cell);
                }
            }
            this.col += cell.colspan;
        }
        else if (DOM_upperName(node) == "TR") {
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                this.processTable(child);
            this.row++;
            this.col = 0;
        }
        else {
            for (var child = node.firstChild; child != null; child = child.nextSibling)
                this.processTable(child);
        }
    }

    // public
    function insertTable(rows,cols,width,numbered,caption)
    {
        debug("insertTable: width = "+width);
        var table = DOM_createElement(document,"TABLE");

        // Probably the most sensible defaults for now
        table.setAttribute("border","1");
//        table.setAttribute("width","100%");
        if (width != null) {
            table.style.width = width;
        }

        // Caption comes first
        if ((caption != null) && (caption != "")) {
            var tableCaption = DOM_createElement(document,"CAPTION");
            tableCaption.appendChild(DOM_createTextNode(document,caption));
            DOM_appendChild(table,tableCaption);
        }

        // Then the rows and columns
        for (var r = 0; r < rows; r++) {
            var tr = DOM_createElement(document,"TR");
            DOM_appendChild(table,tr);
            for (var c = 0; c < cols; c++) {
                var td = DOM_createElement(document,"TD");
                var p = DOM_createElement(document,"P");
                var br = DOM_createElement(document,"BR");
                DOM_appendChild(tr,td);
                DOM_appendChild(td,p);
                DOM_appendChild(p,br);
            }
        }

        Clipboard_pasteNodes([table]);
    }

    // public
    function insertRowsAbove(rows)
    {
    }

    // public
    function insertRowsBelow(rows)
    {
    }

    // public
    function insertColumnsLeft(cols)
    {
    }

    // public
    function insertColumnsRight(cols)
    {
    }

    // public
    function deleteRows()
    {
    }

    // public
    function deleteColumns()
    {
    }

    // public
    function clearCells()
    {
    }

    // public
    function mergeCells()
    {
    }

    // public
    function splitCell()
    {
    }

    // public
    function analyseStructure(element)
    {
        return new Table(element);
    }

    // public
    function findContainingCell(node)
    {
        for (var ancestor = node; ancestor != null; ancestor = ancestor.parentNode) {
            if (isTableCell(ancestor))
                return ancestor;
        }
        return null;
    }

    // public
    function findContainingTable(node)
    {
        for (var ancestor = node; ancestor != null; ancestor = ancestor.parentNode) {
            if (isTableNode(ancestor))
                return ancestor;
        }
        return null;
    }

    Tables_insertTable = trace(insertTable);
    Tables_insertRowsAbove = trace(insertRowsAbove);
    Tables_insertRowsBelow = trace(insertRowsBelow);
    Tables_insertColumnsLeft = trace(insertColumnsLeft);
    Tables_insertColumnsRight = trace(insertColumnsRight);
    Tables_deleteRows = trace(deleteRows);
    Tables_deleteColumns = trace(deleteColumns);
    Tables_clearCells = trace(clearCells);
    Tables_mergeCells = trace(mergeCells);
    Tables_splitCell = trace(splitCell);
    Tables_analyseStructure = trace(analyseStructure);
    Tables_findContainingCell = trace(findContainingCell);
    Tables_findContainingTable = trace(findContainingTable);

})();
<|endoftext|>