text:
KEY_CODES = {
  32: 'space',
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  71: 'g',
  72: 'h',
  77: 'm'
}

KEY_STATUS = { keyDown:false };
for (code in KEY_CODES) {
  KEY_STATUS[KEY_CODES[code]] = false;
}

var chatting = false;

$(window).keydown(function (e) {
  KEY_STATUS.keyDown = true;
  if (KEY_CODES[e.keyCode]) {
    e.preventDefault();
    KEY_STATUS[KEY_CODES[e.keyCode]] = true;
  }
}).keyup(function (e) {
  KEY_STATUS.keyDown = false;
  if (KEY_CODES[e.keyCode]) {
    e.preventDefault();
    KEY_STATUS[KEY_CODES[e.keyCode]] = false;
  }
});

GRID_SIZE = 60;

var frefR = 'https://gxasteroids.firebaseio.com/';
var frefA = frefR + 'game';
var frefL = frefR + 'leaderboard';

// Firebase.enableLogging(true);
var asteroids = new Firebase(frefA);
var myship = asteroids.child('players').push();
myship.onDisconnect().remove();

// Leaderboard start
var LEADERBOARD_SIZE = 25;
// Should the leaderboard be global? Move it to delta?
var leaderboard = new Firebase(frefL);
var scoreListRef = leaderboard.child('scoreList');
var htmlForPath = {};
var currentUser = { name: "Guest" + Math.floor((10000 * Math.random())), type: 'guest', photo: null };

function updateName() {
 if(currentUser.type == 'twitter') {
   $('#my-name').html(' @' + currentUser.name);
 }
 else {
   $('#my-name').text(currentUser.name);
 }
}

updateName();

function handleScoreAdded(scoreSnapshot, lowerScoreName) {
	var newScoreRow = $("
");
	var postedScore = scoreSnapshot.val();
	if(postedScore.user.type == 'twitter') {
	  newScoreRow.append($("").append('').append($("").text('@' + postedScore.user.name)));
	  newScoreRow.append($("").text(postedScore.score));
	}
	else {
	  newScoreRow.append($("").append($("").text(postedScore.user.name)));
	  newScoreRow.append($("").text(postedScore.score));
	}

	// Store a reference to the table row so we can get it again later.
	htmlForPath[scoreSnapshot.key()] = newScoreRow;

	// Insert the new score in the appropriate place in the GUI.
	if (lowerScoreName === null) {
		$("#leaderboardTable").append(newScoreRow);
	}
	else {
		var lowerScoreRow = htmlForPath[lowerScoreName];
		lowerScoreRow.before(newScoreRow);
	}
}

function handleScoreRemoved(scoreSnapshot) {
	var removedScoreRow = htmlForPath[scoreSnapshot.key()];
	removedScoreRow.remove();
	delete htmlForPath[scoreSnapshot.key()];
}

var scoreListView = scoreListRef.limit(LEADERBOARD_SIZE);

scoreListView.on('child_added', function (newScoreSnapshot, prevScoreName) {
		handleScoreAdded(newScoreSnapshot, prevScoreName);
		});

scoreListView.on('child_removed', function (oldScoreSnapshot) {
		handleScoreRemoved(oldScoreSnapshot);
		});

var changedCallback = function (scoreSnapshot, prevScoreName) {
	handleScoreRemoved(scoreSnapshot);
	handleScoreAdded(scoreSnapshot, prevScoreName);
};
scoreListView.on('child_moved', changedCallback);
scoreListView.on('child_changed', changedCallback);

function setScore(score) {
   Game.score = score;
   updateScore();
}

function deltaScore(score) {
   Game.score += score;
   updateScore();
}

function updateScore() {
     $("#my-score").html(Game.score);
}

// Leaderboard end

Matrix = function (rows, columns) {
  var i, j;
  this.data = new Array(rows);
  for (i = 0; i < rows; i++) {
    this.data[i] = new Array(columns);
  }

  this.configure = function (rot, scale, transx, transy) {
    var rad = (rot * Math.PI)/180;
    var sin = Math.sin(rad) * scale;
    var cos = Math.cos(rad) * scale;
    this.set(cos, -sin, transx,
             sin,  cos, transy);
  };

  this.set = function () {
    var k = 0;
    for (i = 0; i < rows; i++) {
      for (j = 0; j < columns; j++) {
        this.data[i][j] = arguments[k];
        k++;
      }
    }
  };

  this.multiply = function () {
    var vector = new Array(rows);
    for (i = 0; i < rows; i++) {
      vector[i] = 0;
      for (j = 0; j < columns; j++) {
        vector[i] += this.data[i][j] * arguments[j];
      }
    }
    return vector;
  };
};

Sprite = function () {
  this.init = function (name, points) {
    this.name     = name;
    this.points   = points;

    this.vel = {
      x:   0,
      y:   0,
      rot: 0
    };

    this.acc = {
      x:   0,
      y:   0,
      rot: 0
    };
  };

  this.children = {};

  this.visible  = false;
  this.reap     = false;
  this.bridgesH = true;
  this.bridgesV = true;

  this.collidesWith = [];

  this.x     = 0;
  this.y     = 0;
  this.rot   = 0;
  this.scale = 1;

  this.currentNode = null;
  this.nextSprite  = null;

  this.preMove  = null;
  this.postMove = null;
  this.strokeStyle = "#000000";

  this.run = function(delta) {

    this.move(delta);
    this.updateGrid();

    this.context.save();
    this.configureTransform();
    this.draw();

    var canidates = this.findCollisionCanidates();

    this.matrix.configure(this.rot, this.scale, this.x, this.y);
    this.checkCollisionsAgainst(canidates);

    this.context.restore();

    if (this.bridgesH && this.currentNode && this.currentNode.dupe.horizontal) {
      this.x += this.currentNode.dupe.horizontal;
      this.context.save();
      this.configureTransform();
      this.draw();
      this.checkCollisionsAgainst(canidates);
      this.context.restore();
      if (this.currentNode) {
        this.x -= this.currentNode.dupe.horizontal;
      }
    }
    if (this.bridgesV && this.currentNode && this.currentNode.dupe.vertical) {
      this.y += this.currentNode.dupe.vertical;
      this.context.save();
      this.configureTransform();
      this.draw();
      this.checkCollisionsAgainst(canidates);
      this.context.restore();
      if (this.currentNode) {
        this.y -= this.currentNode.dupe.vertical;
      }
    }
    if (this.bridgesH && this.bridgesV &&
        this.currentNode &&
        this.currentNode.dupe.vertical &&
        this.currentNode.dupe.horizontal) {
      this.x += this.currentNode.dupe.horizontal;
      this.y += this.currentNode.dupe.vertical;
      this.context.save();
      this.configureTransform();
      this.draw();
      this.checkCollisionsAgainst(canidates);
      this.context.restore();
      if (this.currentNode) {
        this.x -= this.currentNode.dupe.horizontal;
        this.y -= this.currentNode.dupe.vertical;
      }
    }
  };
  this.move = function (delta) {
    if (!this.visible) return;
    this.transPoints = null; // clear cached points

    if ($.isFunction(this.preMove)) {
      this.preMove(delta);
    }

    this.vel.x += this.acc.x * delta;
    this.vel.y += this.acc.y * delta;
    this.x += this.vel.x * delta;
    this.y += this.vel.y * delta;
    this.rot += this.vel.rot * delta;
    if (this.rot > 360) {
      this.rot -= 360;
    } else if (this.rot < 0) {
      this.rot += 360;
    }

    if ($.isFunction(this.postMove)) {
      this.postMove(delta);
    }
  };
  this.updateGrid = function () {
    if (!this.visible) return;
    var gridx = Math.floor(this.x / GRID_SIZE);
    var gridy = Math.floor(this.y / GRID_SIZE);
    gridx = (gridx >= this.grid.length) ? 0 : gridx;
    gridy = (gridy >= this.grid[0].length) ? 0 : gridy;
    gridx = (gridx < 0) ? this.grid.length-1 : gridx;
    gridy = (gridy < 0) ? this.grid[0].length-1 : gridy;
    var newNode = this.grid[gridx][gridy];
    if (newNode != this.currentNode) {
      if (this.currentNode) {
        this.currentNode.leave(this);
      }
      newNode.enter(this);
      this.currentNode = newNode;
    }

    if (KEY_STATUS.g && this.currentNode) {
      this.context.lineWidth = 3.0;
      this.context.strokeStyle = 'green';
      this.context.strokeRect(gridx*GRID_SIZE+2, gridy*GRID_SIZE+2, GRID_SIZE-4, GRID_SIZE-4);
      this.context.strokeStyle = 'black';
      this.context.lineWidth = 1.0;
    }
  };
  this.configureTransform = function () {
    if (!this.visible) return;

    var rad = (this.rot * Math.PI)/180;

    this.context.translate(this.x, this.y);
    this.context.rotate(rad);
    this.context.scale(this.scale, this.scale);
  };
  this.draw = function () {
    if (!this.visible) return;

    this.context.lineWidth = 1.5 / this.scale;

    for (child in this.children) {
      this.children[child].draw();
    }

    this.context.beginPath();

    this.context.moveTo(this.points[0], this.points[1]);
    for (var i = 1; i < this.points.length/2; i++) {
      var xi = i*2;
      var yi = xi + 1;
      this.context.lineTo(this.points[xi], this.points[yi]);
    }

    this.context.closePath();
    this.context.strokeStyle = this.strokeStyle;
    this.context.stroke();
  };
  this.findCollisionCanidates = function () {
    if (!this.visible || !this.currentNode) return [];
    var cn = this.currentNode;
    var canidates = [];
    if (cn.nextSprite) canidates.push(cn.nextSprite);
    if (cn.north.nextSprite) canidates.push(cn.north.nextSprite);
    if (cn.south.nextSprite) canidates.push(cn.south.nextSprite);
    if (cn.east.nextSprite) canidates.push(cn.east.nextSprite);
    if (cn.west.nextSprite) canidates.push(cn.west.nextSprite);
    if (cn.north.east.nextSprite) canidates.push(cn.north.east.nextSprite);
    if (cn.north.west.nextSprite) canidates.push(cn.north.west.nextSprite);
    if (cn.south.east.nextSprite) canidates.push(cn.south.east.nextSprite);
    if (cn.south.west.nextSprite) canidates.push(cn.south.west.nextSprite);
    return canidates
  };
  this.checkCollisionsAgainst = function (canidates) {
    for (var i = 0; i < canidates.length; i++) {
      var ref = canidates[i];
      do {
        this.checkCollision(ref);
        ref = ref.nextSprite;
      } while (ref)
    }
  };
  this.checkCollision = function (other) {
    if (!other.visible ||
         this == other ||
         this.collidesWith.indexOf(other.name) == -1) return;
    var trans = other.transformedPoints();
    var px, py;
    var count = trans.length/2;
    for (var i = 0; i < count; i++) {
      px = trans[i*2];
      py = trans[i*2 + 1];
      // mozilla doesn't take into account transforms with isPointInPath >:-P
     //TODO: fix ->($.browser.mozilla) ? this.pointInPolygon(px, py) : this.context.isPointInPath(px, py)
      if (this.context.isPointInPath(px, py)) {
        other.collision(this);
        this.collision(other);
        return;
      }
    }
  };
  this.pointInPolygon = function (x, y) {
    var points = this.transformedPoints();
    var j = 2;
    var y0, y1;
    var oddNodes = false;
    for (var i = 0; i < points.length; i += 2) {
      y0 = points[i + 1];
      y1 = points[j + 1];
      if ((y0 < y && y1 >= y) ||
          (y1 < y && y0 >= y)) {
        if (points[i]+(y-y0)/(y1-y0)*(points[j]-points[i]) < x) {
          oddNodes = !oddNodes;
        }
      }
      j += 2
      if (j == points.length) j = 0;
    }
    return oddNodes;
  };
  this.collision = function () {
  };
  this.die = function () {
    this.visible = false;
    this.reap = true;
    if (this.currentNode) {
      this.currentNode.leave(this);
      this.currentNode = null;
    }
  };
  this.transformedPoints = function () {
    if (this.transPoints) return this.transPoints;
    var trans = new Array(this.points.length);
    this.matrix.configure(this.rot, this.scale, this.x, this.y);
    for (var i = 0; i < this.points.length/2; i++) {
      var xi = i*2;
      var yi = xi + 1;
      var pts = this.matrix.multiply(this.points[xi], this.points[yi], 1);
      trans[xi] = pts[0];
      trans[yi] = pts[1];
    }
    this.transPoints = trans; // cache translated points
    return trans;
  };
  this.isClear = function () {
    if (this.collidesWith.length == 0) return true;
    var cn = this.currentNode;
    if (cn == null) {
      var gridx = Math.floor(this.x / GRID_SIZE);
      var gridy = Math.floor(this.y / GRID_SIZE);
      gridx = (gridx >= this.grid.length) ? 0 : gridx;
      gridy = (gridy >= this.grid[0].length) ? 0 : gridy;
      cn = this.grid[gridx][gridy];
    }
    return (cn.isEmpty(this.collidesWith) &&
            cn.north.isEmpty(this.collidesWith) &&
            cn.south.isEmpty(this.collidesWith) &&
            cn.east.isEmpty(this.collidesWith) &&
            cn.west.isEmpty(this.collidesWith) &&
            cn.north.east.isEmpty(this.collidesWith) &&
            cn.north.west.isEmpty(this.collidesWith) &&
            cn.south.east.isEmpty(this.collidesWith) &&
            cn.south.west.isEmpty(this.collidesWith));
  };
  this.wrapPostMove = function () {
    if (this.x > Game.canvasWidth) {
      this.x = 0;
    } else if (this.x < 0) {
      this.x = Game.canvasWidth;
    }
    if (this.y > Game.canvasHeight) {
      this.y = 0;
    } else if (this.y < 0) {
      this.y = Game.canvasHeight;
    }
  };

};

Ship = function () {
  this.init("ship",
            [-5,   4,
              0, -12,
              5,   4]);

  this.scale = 1.5;
  this.children.exhaust = new Sprite();
  this.children.exhaust.strokeStyle = "#ff0000";
  this.children.exhaust.init("exhaust",
                             [-3,  6,
                               0, 11,
                               3,  6]);

  this.bulletCounter = 0;
  this.strokeStyle = "#ffff00";
  this.keyFrame = 0;

  this.postMove = this.wrapPostMove;

  this.collidesWith = ["enemybullet", "enemyship"];

  this.previousKeyFrame = { vel: { rot: 0 }, accb: false };

  this.preMove = function (delta) {
    if (KEY_STATUS.left) {
      this.vel.rot = -5;
    } else if (KEY_STATUS.right) {
      this.vel.rot = 5;
    } else {
      this.vel.rot = 0;
    }

    if (KEY_STATUS.up) {
      var rad = ((this.rot-90) * Math.PI)/180;
      this.acc.x = 0.5 * Math.cos(rad);
      this.acc.y = 0.5 * Math.sin(rad);
      this.children.exhaust.visible = Math.random() > 0.1;
    } else {
      this.acc.x = 0;
      this.acc.y = 0;
      this.children.exhaust.visible = false;
    }

    if (this.bulletCounter > 0) {
      this.bulletCounter -= delta;
    }
    if (KEY_STATUS.space) {
      if (this.bulletCounter <= 0) {
        this.bulletCounter = 10; // XXX
        for (var i = 0; i < this.bullets.length; i++) {
          if (!this.bullets[i].visible) {
            SFX.laser();
            var bullet = this.bullets[i];
            var rad = ((this.rot-90) * Math.PI)/180;
            var vectorx = Math.cos(rad);
            var vectory = Math.sin(rad);
            // move to the nose of the ship
            bullet.x = this.x + vectorx * 4;
            bullet.y = this.y + vectory * 4;
            bullet.vel.x = 6 * vectorx + this.vel.x;
            bullet.vel.y = 6 * vectory + this.vel.y;
            bullet.visible = true;
            bullet.fref = asteroids.child('bullets').push({s: myship.key(), x: bullet.x, y: bullet.y, vel: bullet.vel});
            bullet.fref.onDisconnect().remove();
            break;
          }
        }
      }
    }

    // limit the ship's speed
    if (Math.sqrt(this.vel.x * this.vel.x + this.vel.y * this.vel.y) > 8) {
      this.vel.x *= 0.95;
      this.vel.y *= 0.95;
    }

    if((this.vel.rot != this.previousKeyFrame.vel.rot) || (KEY_STATUS.up != this.previousKeyFrame.accb)) {
      myship.set({ship: {acc: this.acc, vel: this.vel, x: this.x, y: this.y, rot: this.rot, accb: KEY_STATUS.up }, user: currentUser  });
    }
    this.previousKeyFrame = { vel: { rot: this.vel.rot }, accb: KEY_STATUS.up };

    this.keyFrame++;
    if(this.keyFrame % 60 == 0) {
      myship.set({ship: {acc: this.acc, vel: this.vel, x: this.x, y: this.y, rot: this.rot, accb: KEY_STATUS.up }, user: currentUser  });
    }
  };

  this.collision = function (other) {
    SFX.explosion();
    if(other != null) {
      Game.explosionAt(other.x, other.y);
    }
    else {
      Game.explosionAt(Game.ship.x, Game.ship.y);
    }
    Game.FSM.state = 'player_died';
    this.visible = false;
    if(this.currentNode != null) {
      this.currentNode.leave(this);
    }
    this.currentNode = null;
    Game.lives--;
    if (other != null && other.name == "enemyship") deltaScore(Math.floor(100 * Math.random()));
  };

};
Ship.prototype = new Sprite();

EnemyShip = function () {
  this.init("enemyship",
            [-5,   4,
              0, -12,
              5,   4]);

  this.children.exhaust = new Sprite();
  this.children.exhaust.strokeStyle = "#ff0000";
  this.children.exhaust.init("exhaust",
                             [-3,  6,
                               0, 11,
                               3,  6]);

  this.scale = 1.5;
  this.bulletCounter = 0;
  this.strokeStyle = "#ffffff";

  this.postMove = this.wrapPostMove;
  this.collidesWith = ["bullet"];

  this.draw = function () {
    if (!this.visible) return;

    this.context.lineWidth = 1.5 / this.scale;

    for (child in this.children) {
      this.children[child].draw();
    }

    this.context.beginPath();

    this.context.moveTo(this.points[0], this.points[1]);
    for (var i = 1; i < this.points.length/2; i++) {
      var xi = i*2;
      var yi = xi + 1;
      this.context.lineTo(this.points[xi], this.points[yi]);
    }

    this.context.closePath();
    this.context.strokeStyle = this.strokeStyle;
    if(this.eimg != null) {
     this.context.drawImage(this.eimg, 0, 0, 20, 20);
    }
    this.context.stroke();
  };

  this.preMove = function (delta) {
    // limit the ship's speed
    if (Math.sqrt(this.vel.x * this.vel.x + this.vel.y * this.vel.y) > 8) {
      this.vel.x *= 0.95;
      this.vel.y *= 0.95;
    }

    if(this.accb) {
      var rad = ((this.rot-90) * Math.PI)/180;
      this.acc.x = 0.5 * Math.cos(rad);
      this.acc.y = 0.5 * Math.sin(rad);
       this.children.exhaust.visible = Math.random() > 0.1;
    }
    else {
       this.acc.x = 0;
       this.acc.y = 0;
       this.children.exhaust.visible = false;
    }
  };

  this.collision = function (other) {
    SFX.explosion();
    Game.explosionAt(other.x, other.y);
    this.fref.remove();
    this.visible = false;
    this.currentNode.leave(this);
    this.currentNode = null;
    //Game.lives--;
  };

};
EnemyShip.prototype = new Sprite();

Bullet = function () {
  this.init("bullet", [0, 0]);
  this.time = 0;
  this.bridgesH = false;
  this.bridgesV = false;
  this.postMove = this.wrapPostMove;

  this.configureTransform = function () {};
  this.draw = function () {
    if (this.visible) {
      this.context.save();
      this.context.lineWidth = 2;
      this.context.beginPath();
      this.context.moveTo(this.x-1, this.y-1);
      this.context.lineTo(this.x+1, this.y+1);
      this.context.moveTo(this.x+1, this.y-1);
      this.context.lineTo(this.x-1, this.y+1);
      this.context.strokeStyle = "#ffffff";
      this.context.stroke();
      this.context.restore();
    }
  };
  this.preMove = function (delta) {
    if (this.visible) {
      this.time += delta;
    }
    if (this.time > 50) { // XXX
      this.visible = false;
      this.time = 0;
      this.fref.remove();
    }
  };
  this.collision = function (other) {
    this.time = 0;
    this.visible = false;
    this.fref.remove();
    this.currentNode.leave(this);
    this.currentNode = null;
    if (other.name == "enemyship") deltaScore(100);
  };
  this.transformedPoints = function (other) {
    return [this.x, this.y];
  };

};
Bullet.prototype = new Sprite();

EnemyBullet = function () {
  this.init("enemybullet", [0, 0]);
  this.time = 0;
  this.bridgesH = false;
  this.bridgesV = false;
  this.postMove = this.wrapPostMove;

  this.configureTransform = function () {};
  this.draw = function () {
    if (this.visible) {
      this.context.save();
      this.context.lineWidth = 2;
      this.context.beginPath();
      this.context.moveTo(this.x-1, this.y-1);
      this.context.lineTo(this.x+1, this.y+1);
      this.context.moveTo(this.x+1, this.y-1);
      this.context.lineTo(this.x-1, this.y+1);
      this.context.strokeStyle = "#ff0000";
      this.context.stroke();
      this.context.restore();
    }
  };
  this.preMove = function (delta) {
    if (this.visible) {
      this.time += delta;
    }
    if (this.time > 50) {
      this.visible = false;
      this.time = 0;
      this.fref.remove();
    }
  };
  this.collision = function (other) {
    this.time = 0;
    this.visible = false;
    this.currentNode.leave(this);
    this.currentNode = null;
  };
  this.transformedPoints = function (other) {
    return [this.x, this.y];
  };

};
EnemyBullet.prototype = new Sprite();

Explosion = function () {
  this.init("explosion");

  this.bridgesH = false;
  this.bridgesV = false;

  this.lines = [];
  for (var i = 0; i < 5; i++) {
    var rad = 2 * Math.PI * Math.random();
    var x = Math.cos(rad);
    var y = Math.sin(rad);
    this.lines.push([x, y, x*2, y*2]);
  }

  this.draw = function () {
    if (this.visible) {
      this.context.save();
      this.context.lineWidth = 1.0 / this.scale;
      this.context.beginPath();
      for (var i = 0; i < 5; i++) {
        var line = this.lines[i];
        this.context.moveTo(line[0], line[1]);
        this.context.lineTo(line[2], line[3]);
      }
      this.context.strokeStyle = "#CC3232";
      this.context.stroke();
      this.context.restore();
    }
  };

  this.preMove = function (delta) {
    if (this.visible) {
      this.scale += delta;
    }
    if (this.scale > 8) {
      this.die();
    }
  };
};
Explosion.prototype = new Sprite();

GridNode = function () {
  this.north = null;
  this.south = null;
  this.east  = null;
  this.west  = null;

  this.nextSprite = null;

  this.dupe = {
    horizontal: null,
    vertical:   null
  };

  this.enter = function (sprite) {
    sprite.nextSprite = this.nextSprite;
    this.nextSprite = sprite;
  };

  this.leave = function (sprite) {
    var ref = this;
    while (ref && (ref.nextSprite != sprite)) {
      ref = ref.nextSprite;
    }
    if (ref) {
      ref.nextSprite = sprite.nextSprite;
      sprite.nextSprite = null;
    }
  };

  this.eachSprite = function(sprite, callback) {
    var ref = this;
    while (ref.nextSprite) {
      ref = ref.nextSprite;
      callback.call(sprite, ref);
    }
  };

  this.isEmpty = function (collidables) {
    var empty = true;
    var ref = this;
    while (ref.nextSprite) {
      ref = ref.nextSprite;
      empty = !ref.visible || collidables.indexOf(ref.name) == -1
      if (!empty) break;
    }
    return empty;
  };
};

// borrowed from typeface-0.14.js
// http://typeface.neocracy.org
Text = {
  renderGlyph: function (ctx, face, char) {
    this.context.strokeStyle = "#FFFFFF";
    this.context.fillStyle = "#FFFFFF";

    var glyph = face.glyphs[char];

    if (glyph.o) {

      var outline;
      if (glyph.cached_outline) {
        outline = glyph.cached_outline;
      } else {
        outline = glyph.o.split(' ');
        glyph.cached_outline = outline;
      }

      var outlineLength = outline.length;
      for (var i = 0; i < outlineLength; ) {

        var action = outline[i++];

        switch(action) {
          case 'm':
            ctx.moveTo(outline[i++], outline[i++]);
            break;
          case 'l':
            ctx.lineTo(outline[i++], outline[i++]);
            break;

          case 'q':
            var cpx = outline[i++];
            var cpy = outline[i++];
            ctx.quadraticCurveTo(outline[i++], outline[i++], cpx, cpy);
            break;

          case 'b':
            var x = outline[i++];
            var y = outline[i++];
            ctx.bezierCurveTo(outline[i++], outline[i++], outline[i++], outline[i++], x, y);
            break;
        }
      }
    }
    if (glyph.ha) {
      ctx.translate(glyph.ha, 0);
    }
  },

  renderText: function(text, size, x, y) {
    this.context.save();

    this.context.translate(x, y);

    var pixels = size * 72 / (this.face.resolution * 100);
    this.context.scale(pixels, -1 * pixels);
    this.context.beginPath();
    var chars = text.split('');
    var charsLength = chars.length;
    this.context.strokeStyle = "#FFFFFF";
    this.context.fillStyle = "#FFFFFF";
    for (var i = 0; i < charsLength; i++) {
      this.renderGlyph(this.context, this.face, chars[i]);
    }
    this.context.fill();

    this.context.restore();
  },

  context: null,
  face: null
};

SFX = {
  laser:     new Audio('39459__THE_bizniss__laser.wav'),
  explosion: new Audio('51467__smcameron__missile_explosion.wav')
};

// preload audio
for (var sfx in SFX) {
  (function () {
    var audio = SFX[sfx];
    audio.muted = true;
    audio.play();

    SFX[sfx] = function () {
      if (!this.muted) {
        if (audio.duration == 0) {
          // somehow dropped out
          audio.load();
          audio.play();
        } else {
          audio.muted = false;
          audio.currentTime = 0;
        }
      }
      return audio;
    }
  })();
}
// pre-mute audio
SFX.muted = true;

Game = {
  score: 0,
  lives: 0,

  canvasWidth: 650,
  canvasHeight: 350,

  sprites: [],
  ship: null,

  explosionAt: function (x, y) {
    var splosion = new Explosion();
    splosion.x = x;
    splosion.y = y;
    splosion.visible = true;
    Game.sprites.push(splosion);
  },

  FSM: {
    boot: function () {
        KEY_STATUS.space = false; // hack so we don't shoot right away
        window.gameStart = false;
        this.state = 'start';
    },
    start: function () {
      for (sprite in Game.sprites) {
        if (Game.sprites[sprite].name == 'asteroid') {
          Game.sprites[sprite].die();
        } else if (Game.sprites[sprite].name == 'bullet') {
          Game.sprites[sprite].visible = false;
        }
      }

      setScore(0);
      Game.lives = 7;

      this.state = 'spawn_ship';
    },
    spawn_ship: function () {
      Game.ship.x = Math.floor(Game.canvasWidth * Math.random());
      Game.ship.y = Math.floor(Game.canvasHeight * Math.random());
      if (Game.ship.isClear()) {
        Game.ship.rot = 0;
        Game.ship.vel.x = 0;
        Game.ship.vel.y = 0;
        Game.ship.visible = true;
        this.state = 'run';
      }
    },
    run: function () {
    },
    new_level: function () {
      if (this.timer == null) {
        this.timer = Date.now();
      }
      // wait a second before spawning more asteroids
      if (Date.now() - this.timer > 1000) {
        this.timer = null;
        this.state = 'run';
      }
    },
    player_died: function () {
      if (Game.lives < 0) {
        this.state = 'end_game';
      } else {
        if (this.timer == null) {
          this.timer = Date.now();
        }
        // wait a second before spawning
        if (Date.now() - this.timer > 1000) {
          this.timer = null;
          this.state = 'spawn_ship';
        }
      }
    },
    end_game: function () {
      Text.renderText('GAME OVER RESTARTING...', 50, 30, Game.canvasHeight/2 + 10);
      if (this.timer == null) {
        this.timer = Date.now();
      }
      // wait 5 seconds then go back to start state
      if (Date.now() - this.timer > 5000) {
        this.timer = null;
        this.state = 'start';
        var postScoreRef = scoreListRef.push();
        postScoreRef.setWithPriority({user: currentUser, score: Game.score}, Game.score);
      }

      window.gameStart = false;
    },

    execute: function () {
      this[this.state]();
    },
    state: 'boot'
  }

};

$(function () {
  var canvas = $("#canvas");
  Game.canvasWidth  = canvas.width();
  Game.canvasHeight = canvas.height();

  var context = canvas[0].getContext("2d");

  Text.context = context;
  Text.face = vector_battle;

  var gridWidth = Math.round(Game.canvasWidth / GRID_SIZE);
  var gridHeight = Math.round(Game.canvasHeight / GRID_SIZE);
  var grid = new Array(gridWidth);
  for (var i = 0; i < gridWidth; i++) {
    grid[i] = new Array(gridHeight);
    for (var j = 0; j < gridHeight; j++) {
      grid[i][j] = new GridNode();
    }
  }

  // set up the positional references
  for (var i = 0; i < gridWidth; i++) {
    for (var j = 0; j < gridHeight; j++) {
      var node   = grid[i][j];
      node.north = grid[i][(j == 0) ? gridHeight-1 : j-1];
      node.south = grid[i][(j == gridHeight-1) ? 0 : j+1];
      node.west  = grid[(i == 0) ? gridWidth-1 : i-1][j];
      node.east  = grid[(i == gridWidth-1) ? 0 : i+1][j];
    }
  }

  // set up borders
  for (var i = 0; i < gridWidth; i++) {
    grid[i][0].dupe.vertical            =  Game.canvasHeight;
    grid[i][gridHeight-1].dupe.vertical = -Game.canvasHeight;
  }

  for (var j = 0; j < gridHeight; j++) {
    grid[0][j].dupe.horizontal           =  Game.canvasWidth;
    grid[gridWidth-1][j].dupe.horizontal = -Game.canvasWidth;
  }

  var sprites = [];
  Game.sprites = sprites;

  // so all the sprites can use it
  Sprite.prototype.context = context;
  Sprite.prototype.grid    = grid;
  Sprite.prototype.matrix  = new Matrix(2, 3);

  var ship = new Ship();

//  ship.x = Game.canvasWidth / 2;
//  ship.y = Game.canvasHeight / 2;

  sprites.push(ship);

  ship.bullets = [];
  for (var i = 0; i < 10; i++) { // XXX
    var bull = new Bullet();
    ship.bullets.push(bull);
    sprites.push(bull);
  }
  Game.ship = ship;

  var extraDude = new Ship();
  extraDude.scale = 0.6;
  extraDude.visible = true;
  extraDude.preMove = null;
  extraDude.children = [];

  var i, j = 0;

  var avgFramerate = 0;
  var frameCount = 0;
  var elapsedCounter = 0;

  var lastFrame = Date.now();
  var thisFrame;
  var elapsed;
  var delta;

  var canvasNode = canvas[0];

  // shim layer with setTimeout fallback
  // from here:
  // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  window.requestAnimFrame = (function () {
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
            function (/* function */ callback, /* DOMElement */ element) {
              window.setTimeout(callback, 1000 / 60);
            };
  })();

  var mainLoop = function () {
    context.clearRect(0, 0, Game.canvasWidth, Game.canvasHeight);

    Game.FSM.execute();

    if (KEY_STATUS.g) {
      context.beginPath();
      for (var i = 0; i < gridWidth; i++) {
        context.moveTo(i * GRID_SIZE, 0);
        context.lineTo(i * GRID_SIZE, Game.canvasHeight);
      }
      for (var j = 0; j < gridHeight; j++) {
        context.moveTo(0, j * GRID_SIZE);
        context.lineTo(Game.canvasWidth, j * GRID_SIZE);
      }
      context.closePath();
      context.stroke();
    }

    thisFrame = Date.now();
    elapsed = thisFrame - lastFrame;
    lastFrame = thisFrame;
    delta = elapsed / 30;

    var i = 0;
    for (sprite in sprites) {
      var s = sprites[sprite];
      if(typeof(s) != undefined) {
        s.run(delta);
        if (s.reap) {
          s.reap = false;
          sprites.splice(i, 1);
          i--;
        }
      }
      i++;
    }

    // extra dudes
    for (i = 0; i < Game.lives; i++) {
      context.save();
      extraDude.x = Game.canvasWidth - (8 * (i + 1));
      extraDude.y = 16;
      extraDude.configureTransform();
      extraDude.draw();
      context.restore();
    }

    frameCount++;
    elapsedCounter += elapsed;
    if (elapsedCounter > 1000) {
      elapsedCounter -= 1000;
      avgFramerate = frameCount;
      frameCount = 0;
    }

    requestAnimFrame(mainLoop, canvasNode);
  };

  var cb = new Firebase(frefR).child('.info/connected').on('value', function(snap) {
    if (snap.val()) {
      new Firebase(frefR).child('.info/connected').off('value', cb);
      mainLoop();
    }
  });

  $(window).keydown(function (e) {
    switch (KEY_CODES[e.keyCode]) {
      case 'm': // mute
        SFX.muted = !SFX.muted;
        break;
    }
  });

  asteroids.child('players').on('child_added', function(snapshot) {
    if(snapshot.key() != myship.key()) {
	var enemy = new EnemyShip();
	enemy.acc = snapshot.val().ship.acc;
	enemy.vel = snapshot.val().ship.vel;
	enemy.x = snapshot.val().ship.x;
	enemy.y = snapshot.val().ship.y;
	enemy.rot = snapshot.val().ship.rot;
	enemy.accb = snapshot.val().ship.accb;
	enemy.visible = true;
	enemy.user = snapshot.val().user;
	enemy.fref = asteroids.child('players').child(snapshot.key());
	if(typeof(enemy.user.photo) != undefined && enemy.user.photo != null) {
	  enemy.eimg = new Image();
	  enemy.eimg.src = enemy.user.photo;
	}
	else {
	  enemy.eimg = null;
	}
	Game.sprites[snapshot.key()] = enemy;
    }
    else {
    }
  });

  asteroids.child('players').on('child_changed', function(snapshot) {
    if(snapshot.key() != myship.key()) {
	var enemy = Game.sprites[snapshot.key()];
	enemy.visible = true;
	enemy.acc = snapshot.val().ship.acc;
	enemy.vel = snapshot.val().ship.vel;
	enemy.x = snapshot.val().ship.x;
	enemy.y = snapshot.val().ship.y;
	enemy.rot = snapshot.val().ship.rot;
	enemy.accb = snapshot.val().ship.accb;
	enemy.user = snapshot.val().user;
	enemy.fref = asteroids.child('players').child(snapshot.key());
	if(typeof(enemy.user.photo) != undefined && enemy.user.photo != null) {
	  enemy.eimg = new Image();
	  enemy.eimg.src = enemy.user.photo;
	}
	else {
	  enemy.eimg = null;
	}
    }
    else {
    }
  });

  asteroids.child('players').on('child_removed', function(snapshot) {
    if(snapshot.key() != myship.key()) {
	var enemy = Game.sprites[snapshot.key()];
	enemy.visible = false;
	delete Game.sprites[snapshot.key()];
    }
    else {
      Game.ship.collision(null);
    }
  });

  // bullet.fref = asteroids.child('bullets').push({s: myship.key(), x: bullet.x, y: bullet.y, vel: bullet.vel});
  asteroids.child('bullets').on('child_added', function(snapshot) {
     var bullet = snapshot.val();
     if(bullet.s != myship.key()) {
	var enemybullet = new EnemyBullet();
	enemybullet.x = bullet.x;
	enemybullet.y = bullet.y;
	enemybullet.vel = bullet.vel;
	enemybullet.visible = true;
	enemybullet.fref = asteroids.child('bullets').child(snapshot.key());
	Game.sprites['bullet:' + snapshot.key()] = enemybullet;
     }
  });

  asteroids.child('bullets').on('child_removed', function(snapshot) {
     var bullet = snapshot.val();
     if(bullet.s != myship.key()) {
	var enemybullet = Game.sprites['bullet:' + snapshot.key()];
	if(enemybullet != null) {
	  enemybullet.visible = false;
	}
	delete Game.sprites['bullet:' + snapshot.key()];
     }
  });

  updateName();

  var at = $.getUrlVar('access_token');
  if(! (typeof at === "undefined")) {
	$.get('https://api.singly.com/profiles/twitter?access_token=' + at, function(data) {
		currentUser = { name: data.data.screen_name, type: 'twitter', photo: data.data.profile_image_url };
  		updateName();
		$('#login').hide();
	});
  }
});

// vim: fdl=0


text:
title: Masonry Column Shift
layout: default
category: custom-layout-modes
---

Custom layout mode masonryColumnShift. Enabled columns of a Masonry layout to be shifted and not affect other columns. After the size of an item element has changed, you can trigger a special columnShiftOfItem method that will push the column down. This layout only works with item elements that have the same width

{% highlight javascript %}

var $container = $('#container');

$container.isotope({
  itemSelector: '.shifty-item',
  layoutMode: 'masonryColumnShift'
});

$container.find('.shifty-item').hover(
  function() {
    $(this).css({ height: "+=100" });
    // note that element is passed in, not jQuery object
    $container.isotope( 'shiftColumnOfItem', this );
  },
  function() {
    $(this).css({ height: "-=100" });
    $container.isotope( 'shiftColumnOfItem', this );
  }
);

{% endhighlight %}

redpajama_set_name: RedPajamaGithub


text:
package com.msaf.validador.core.tratamentoxls.xls;

import java.util.ResourceBundle;

import com.msaf.validador.consultaonline.TipoValidacao;
import com.msaf.validador.core.tratamentoxls.xls.column.ColumnString;

public abstract class AbstractDadosXLS implements DadosXLS {

	private static ResourceBundle bundle = ResourceBundle.getBundle("com.msaf.validador.xls");

	private TipoValidacao tipoValidacao;

	public AbstractDadosXLS(TipoValidacao tipoValidacao){
		this.tipoValidacao = tipoValidacao;
	}

	protected String getLabel(String key) {
		return bundle.getString(key);
	}

	protected Column writeValue(String value){
		value = value == null? "": value;

		return new ColumnString(value);
	}

	@Override
	public TipoValidacao getTipoValidacao(){
		return this.tipoValidacao;
	}
}


text:
/**
 * Pipedrive API v1
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1.0.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 *
 */

import ApiClient from '../ApiClient';
import AdditionalDataWithPagination from './AdditionalDataWithPagination';
import BaseNote from './BaseNote';

/**
 * The GetNotes model module.
 * @module model/GetNotes
 * @version 1.0.0
 */
class GetNotes {
    /**
     * Constructs a new GetNotes.
     * @alias module:model/GetNotes
     */
    constructor() {

        GetNotes.initialize(this);
    }

    /**
     * Initializes the fields of this object.
     * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
     * Only for internal use.
     */
    static initialize(obj) {
    }

    /**
     * Constructs a GetNotes from a plain JavaScript object, optionally creating a new instance.
     * Copies all relevant properties from data to obj if supplied or a new instance if not.
     * @param {Object} data The plain JavaScript object bearing properties of interest.
     * @param {module:model/GetNotes} obj Optional instance to populate.
     * @return {module:model/GetNotes} The populated GetNotes instance.
     */
    static constructFromObject(data, obj) {
        if (data) {
            obj = obj || new GetNotes();

            if (data.hasOwnProperty('success')) {
                obj['success'] = ApiClient.convertToType(data['success'], 'Boolean');

                delete data['success'];
            }
            if (data.hasOwnProperty('data')) {
                obj['data'] = ApiClient.convertToType(data['data'], [BaseNote]);

                delete data['data'];
            }
            if (data.hasOwnProperty('additional_data')) {
                obj['additional_data'] = AdditionalDataWithPagination.constructFromObject(data['additional_data']);

                delete data['additional_data'];
            }

            if (Object.keys(data).length > 0) {
                Object.assign(obj, data);
            }

        }
        return obj;
    }

}

/**
 * If the request was successful or not
 * @member {Boolean} success
 */
GetNotes.prototype['success'] = undefined;

/**
 * The array of notes
 * @member {Array.<module:model/BaseNote>} data
 */
GetNotes.prototype['data'] = undefined;

/**
 * @member {module:model/AdditionalDataWithPagination} additional_data
 */
GetNotes.prototype['additional_data'] = undefined;

export default GetNotes;


text:
package fr.inra.maiage.bibliome.util.trie;

import java.io.IOException;

import fr.inra.maiage.bibliome.util.marshall.StringCodec;

public class Test {
	private static final String FILE_PATH = "test.trie";
	private static final String QUERY = "There's a fo ol tràïn in the foul by a single Toto";

	private static void lookup(Trie<String> trie, String key) {
		System.out.println(key + ": " + trie.getValues(key));
	}

	private static void search(Matcher<String> matcher) {
		matcher.init();
		matcher.search(QUERY);
		System.out.println();
		System.out.println(matcher.getMatchControl());
		for (Match<String> m : matcher.finish(QUERY.length())) {
			System.out.println(
					QUERY.substring(m.getStart(), m.getEnd()) + " " +
							m.getStart() + "-" + m.getEnd() + " " +
							m.getValues()
					);
		}
	}

	private static void testTrie(Trie<String> trie) {
		System.out.println();
		System.out.println();
		System.out.println();
		lookup(trie, "foo");
		lookup(trie, "foul");
		lookup(trie, "train");
		lookup(trie, "toto");
		lookup(trie, "qux");
		System.out.println();
		trie.tree(System.out);
		StandardMatchControl control = new StandardMatchControl();
		Matcher<String> matcher = new Matcher<String>(trie, control);

		control.setWordStartCaseInsensitive(true);
		control.setIgnoreDiacritics(true);
		control.setSkipWhitespace(true);
		search(matcher);
	}

	private static Trie<String> buildTrie() {
		Trie<String> result = new Trie<String>();
		result.addEntry("foo", "bar");
		result.addEntry("fool", "mad");
		result.addEntry("toto", "titi");
		result.addEntry("train", "wagon");
		return result;
	}

	private static Trie<String> loadTrie(String file) throws IOException {
		return new Trie<String>(file, StringCodec.INSTANCE, Integer.MAX_VALUE);
	}

	public static void main(String[] args) throws IOException {
		Trie<String> trie = buildTrie();
		testTrie(trie);

		trie.save(FILE_PATH, StringCodec.INSTANCE);
		testTrie(loadTrie(FILE_PATH));
	}
}


text:
describe "Rails development-mode support", :type => :rails do
  uses_rails_with_template :development_mode_system_spec, :rails_env => :development

  it "should automatically reload widgets if they change on disk" do
    expect_match("reload_widget", /before_reload/)
    # The sleep is unfortunate, but required: without it, Rails will not necessarily pick up our change,
    # especially if we run multiple tests back-to-back. (There's a maximum frequency at which Rails can
    # detect distinct file changes on disk, which on the order of 1 Hz -- i.e., once a second; any more
    # than this and it fails. This is irrelevant for human-centered development, but important for
    # tests like this.)
    sleep 1
    splat_new_widget!
    expect_match("reload_widget", /after_reload/)
  end

  it "should automatically reload widgets if related files change on disk, even if they're named '.html.rb' at the end" do
    expect_match("reload_widget_with_html_extension", /with_html_extension.*helper: yo/)
    sleep 1
    splat_new_module_for_reload_widget_failing!
    expect_exception("reload_widget_with_html_extension", NameError, "some_helper")
    sleep 1
    splat_new_module_for_reload_widget!
    expect_match("reload_widget_with_html_extension", /with_html_extension.*helper: yo/)
  end

  it "should not autoload classes that live under views/ but don't start with a Views:: prefix" do
    expect_exception('the_class_should_not_load', 'NameError',
      /uninitialized constant DevelopmentModeSystemSpec::ClassShouldNotLoad/i)
  end

  it "should let you change the controller, and that should work fine, too" do
    expect(rails_server.get("replaced/reload_widget")).to match(/datum\s+one\s+datum/)
    sleep 1
    splat_new_controller!
    expect(rails_server.get("replaced/reload_widget")).to match(/datum\s+two\s+datum/)
  end

  it "should, by default, format output" do
    expect_match("sample_output", %r{

hello, Jessica

}mi)
  end

  it "should, by default, output BEGIN/END debugging tags" do
    expect_match("sample_output", %r{
.*
}mi)
  end

  it "should pick up changes to mailer views" do
    expect_match("mailer_view_test", /mail sent/i)
    mail = mail_sent_to('mailer_view_test@example.com')
    expect(mail[:body].strip).to match(%r{
this is the basic mail!
}mi)
    clear_mails!

    sleep 1
    splat_new_mailer_view!
    expect_match("mailer_view_test", /mail sent/i)
    mail = mail_sent_to('mailer_view_test@example.com')
    expect(mail[:body].strip).to match(%r{
this is the NEW basic mail!
}mi)
  end

  it "should pick up changes to mailer layouts" do
    expect_match("mailer_layout_test", /mail sent/i)
    mail = mail_sent_to('mailer_layout_test@example.com')
    expect(mail[:body].strip).to match(%r{this is the layout, before.*this is the basic mail!.*this is the layout, after}mi)
    clear_mails!

    sleep 1
    splat_new_mailer_layout!
    expect_match("mailer_layout_test", /mail sent/i)
    mail = mail_sent_to('mailer_layout_test@example.com')
    expect(mail[:body].strip).to match(%r{this is the NEW layout, before.*this is the basic mail!.*this is the NEW layout, after}mi)
  end

  it "should format output and output BEGIN/END debugging tags in mailers" do
    expect_match("mailer_formatting_test", /mail sent/i)
    mail = mail_sent_to('mailer_formatting_test@example.com')
    expect(mail[:body].strip).to eq(%{

this is the text!

})
  end

  it "should allow referencing a widget by partial namespace" do
    expect_match("namespace_reference", /before.*referenced.*after/mi)
  end

  it "should allow you to toggle back and forth between two forms of referencing a superclass" do
    current_form = :full_reference
    5.times do
      if current_form == :full_reference
        splat_full_reference_edit!
      else
        splat_partial_reference_edit!
      end

      sleep 1
      $stderr.puts "checking for #{current_form.inspect}"
      expect_match("edit", /#{Regexp.escape(current_form.to_s)}/i)

      current_form = if current_form == :full_reference
        :partial_reference
      else
        :full_reference
      end
    end
  end

  private
  def splat_full_reference_edit!
    widget_file = File.join(rails_server.rails_root, "app/views/development_mode_system_spec/edit.rb")
    File.open(widget_file, 'w') do |f|
      f.puts <<-EOS
module Views
  module DevelopmentModeSystemSpec
    if const_defined?(:Edit)
      $stderr.puts "(full) Edit constant: \#{const_get(:Edit).inspect}"
      $stderr.puts "(full) Edit superclass: \#{const_get(:Edit).superclass}/\#{const_get(:Edit).superclass.object_id}"

      if (::Views.const_defined?(:Base))
        $stderr.puts "(full) Views::Base already defined: \#{::Views::Base.object_id}"
      else
        $stderr.puts "(full) Views::Base not defined"
      end

      $stderr.puts "(full) ::Views::Base: \#{::Views::Base.name}/\#{::Views::Base.object_id}"
      $stderr.puts "(full) Views::Base: \#{Views::Base.name}/\#{Views::Base.object_id}"
    else
      $stderr.puts "(full) No edit constant!"
    end

    class Edit < Views::Base
      def content
        widget(Views::DevelopmentModeSystemSpec::Form, :label => "full_reference")
      end
    end

    $stderr.puts "(full) After definition: \#{::Views::Base.object_id}"
  end
end
EOS
    end
  end

  def splat_partial_reference_edit!
    widget_file = File.join(rails_server.rails_root, "app/views/development_mode_system_spec/edit.rb")
    File.open(widget_file, 'w') do |f|
      f.puts <<-EOS
module Views
  module DevelopmentModeSystemSpec
    if const_defined?(:Edit)
      $stderr.puts "(partial) Edit constant: \#{const_get(:Edit).inspect}"
      $stderr.puts "(partial) Edit superclass: \#{const_get(:Edit).superclass}/\#{const_get(:Edit).superclass.object_id}"

      if (::Views.const_defined?(:Base))
        $stderr.puts "(partial) Views::Base already defined: \#{::Views::Base.object_id}"
      else
        $stderr.puts "(partial) Views::Base not defined"
      end

      $stderr.puts "(partial) ::Views::Base: \#{::Views::Base.name}/\#{::Views::Base.object_id}"
      $stderr.puts "(partial) Views::Base: \#{Views::Base.name}/\#{Views::Base.object_id}"
    else
      $stderr.puts "(partial) No edit constant!"
    end

    class Edit < Views::Base
      def content
        widget(Form, :label => "partial_reference")
      end
    end

    $stderr.puts "(partial) After definition: \#{::Views::Base.object_id}"
  end
end
EOS
    end
  end

  def splat_new_widget!
    reload_file = File.join(rails_server.rails_root, 'app/views/development_mode_system_spec/reload_widget.rb')
    File.open(reload_file, 'w') do |f|
      f.puts <<-EOS
class Views::DevelopmentModeSystemSpec::ReloadWidget < Fortitude::Widgets::Html5
  needs :datum

  def content
    p "after_reload: datum \#{datum} datum"
  end
end
EOS
    end
  end

  def splat_new_module_for_reload_widget_failing!
    module_file = File.join(rails_server.rails_root, 'app/views/shared/some_module.rb')
    File.open(module_file, 'w') do |f|
      f.puts <<-EOS
module Views::Shared::SomeModule
end
EOS
    end
  end

  def splat_new_module_for_reload_widget!
    module_file = File.join(rails_server.rails_root, 'app/views/shared/some_module.rb')
    File.open(module_file, 'w') do |f|
      f.puts <<-EOS
module Views::Shared::SomeModule
  def some_helper
    "yo"
  end
end
EOS
    end
  end

  def splat_new_controller!
    controller_file = File.join(rails_server.rails_root, 'app/controllers/replaced_controller.rb')
    File.open(controller_file, 'w') do |f|
      f.puts <<-EOS
class ReplacedController < ApplicationController
  def reload_widget
    @datum = "two"
  end
end
EOS
    end
  end

  def splat_new_mailer_view!
    reload_file = File.join(rails_server.rails_root, 'app/views/development_mode_mailer/mailer_view_test.rb')
    File.open(reload_file, 'w') do |f|
      f.puts <<-EOS
class Views::DevelopmentModeMailer::MailerViewTest < Fortitude::Widgets::Html5
  def content
    p "this is the NEW basic mail!"
  end
end
EOS
    end
  end

  def splat_new_mailer_layout!
    reload_file = File.join(rails_server.rails_root, 'app/views/layouts/mail_layout.rb')
    File.open(reload_file, 'w') do |f|
      f.puts <<-EOS
class Views::Layouts::MailLayout < Fortitude::Widgets::Html5
  def content
    p "this is the NEW layout, before"
    yield
    p "this is the NEW layout, after"
  end
end
EOS
    end
  end
end


text:
package org.kaazing.mina.core.session;

/**
 * Detection of thread alignment in AbstractIoSession.
*/
interface IoAlignment {

    // capture relationship with IoSessionEx method of same signature
    boolean isIoAligned();

}


text:
/************************************************/
/*                                              */
/*          AIMP Programming Interface          */
/*               v3.60 build 1473               */
/*                                              */
/*                Artem Izmaylov                */
/*                (C) 2006-2015                 */
/*                 www.aimp.ru                  */
/*              ICQ: 345-908-513                */
/*            Mail: support@aimp.ru             */
/*                                              */
/************************************************/

#ifndef apiAlbumArtH
#define apiAlbumArtH

#include <windows.h>
#include <unknwn.h>
#include "apiObjects.h"
#include "apiCore.h"
#include "apiFileManager.h"

static const GUID IID_IAIMPExtensionAlbumArtCatalog   = {0x41494D50, 0x4578, 0x7441, 0x6C, 0x62, 0x41, 0x72, 0x74, 0x43, 0x61, 0x74};
static const GUID IID_IAIMPExtensionAlbumArtCatalog2  = {0x41494D50, 0x4578, 0x416C, 0x62, 0x41, 0x72, 0x74, 0x43, 0x61, 0x74, 0x32};
static const GUID IID_IAIMPExtensionAlbumArtProvider  = {0x41494D50, 0x4578, 0x7441, 0x6C, 0x62, 0x41, 0x72, 0x74, 0x50, 0x72, 0x76};
static const GUID IID_IAIMPExtensionAlbumArtProvider2 = {0x41494D50, 0x4578, 0x416C, 0x62, 0x41, 0x72, 0x74, 0x50, 0x72, 0x76, 0x32};
static const GUID IID_IAIMPServiceAlbumArt = {0x41494D50, 0x5372, 0x7641, 0x6C, 0x62, 0x41, 0x72, 0x74, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPServiceAlbumArtCache = {0x4941494D, 0x5053, 0x7276, 0x41, 0x6C, 0x62, 0x41, 0x72, 0x74, 0x43, 0x68};

const int AIMP_ALBUMART_PROVIDER_CATEGORY_MASK     = 0xF;
// Providers Categories
const int AIMP_ALBUMART_PROVIDER_CATEGORY_TAGS     = 0;
const int AIMP_ALBUMART_PROVIDER_CATEGORY_FILE     = 1;
const int AIMP_ALBUMART_PROVIDER_CATEGORY_INTERNET = 2;

// PropIDs for IAIMPPropertyList in IAIMPExtensionAlbumArtLocalFinder.Get
const int AIMP_SERVICE_ALBUMART_PROPID_FIND_IN_FILES                  = 1;
const int AIMP_SERVICE_ALBUMART_PROPID_FIND_IN_FILES_MASKS            = 2;
const int AIMP_SERVICE_ALBUMART_PROPID_FIND_IN_FILES_EXTS             = 3;
const int AIMP_SERVICE_ALBUMART_PROPID_FIND_IN_INTERNET               = 4;
const int AIMP_SERVICE_ALBUMART_PROPID_FIND_IN_INTERNET_MAX_FILE_SIZE = 5;

// Flags for IAIMPServiceAlbumArt.Get
const int AIMP_SERVICE_ALBUMART_FLAGS_IGNORECACHE = 1;
const int AIMP_SERVICE_ALBUMART_FLAGS_ORIGINAL    = 2;
const int AIMP_SERVICE_ALBUMART_FLAGS_WAITFOR     = 4;

typedef void (CALLBACK TAIMPServiceAlbumArtReceiveProc)(IAIMPImage *image, IAIMPImageContainer *imageContainer, void *UserData);

/* IAIMPExtensionAlbumArtCatalog */

class IAIMPExtensionAlbumArtCatalog: public IUnknown
{
	public:
		virtual HRESULT WINAPI GetIcon(HICON *Image) = 0;
		virtual HRESULT WINAPI GetName(IAIMPString **Name) = 0;
		virtual HRESULT WINAPI Show(IAIMPString *FileURI, IAIMPString *Artist, IAIMPString *Album, IAIMPImageContainer **Image) = 0;
};

/* IAIMPExtensionAlbumArtCatalog2 */

class IAIMPExtensionAlbumArtCatalog2: public IAIMPExtensionAlbumArtCatalog
{
	public:
		virtual HRESULT WINAPI Show2(IAIMPFileInfo *FileInfo, IAIMPImageContainer **Image) = 0;
};

/* IAIMPExtensionAlbumArtProvider */

class IAIMPExtensionAlbumArtProvider: public IUnknown
{
	public:
		virtual HRESULT WINAPI Get(IAIMPString *FileURI, IAIMPString *Artist, IAIMPString *Album, IAIMPPropertyList *Options, IAIMPImageContainer **Image) = 0;
		virtual DWORD WINAPI GetCategory() = 0;
};

/* IAIMPExtensionAlbumArtProvider2 */

class IAIMPExtensionAlbumArtProvider2: public IAIMPExtensionAlbumArtProvider
{
	public:
		virtual HRESULT WINAPI Get2(IAIMPFileInfo *FileInfo, IAIMPPropertyList *Options, IAIMPImageContainer **Image) = 0;
};

/* IAIMPServiceAlbumArt */

class IAIMPServiceAlbumArt: public IUnknown
{
	public:
		virtual HRESULT WINAPI Get(IAIMPString *FileURI, IAIMPString *Artist, IAIMPString *Album, DWORD Flags, TAIMPServiceAlbumArtReceiveProc *CallbackProc, void *UserData, void **TaskID) = 0;
		virtual HRESULT WINAPI Get2(IAIMPFileInfo *FileInfo, DWORD Flags, TAIMPServiceAlbumArtReceiveProc *CallbackProc, void *UserData, void **TaskID) = 0;
		virtual HRESULT WINAPI Cancel(void *TaskID, DWORD Flags) = 0;
};

/* IAIMPServiceAlbumArtCache */

class IAIMPServiceAlbumArtCache: public IUnknown
{
	public:
		virtual HRESULT WINAPI Flush(IAIMPString *Artist, IAIMPString *Album) = 0;
		virtual HRESULT WINAPI Flush2(IAIMPString *FileURI) = 0;
		virtual HRESULT WINAPI FlushAll() = 0;
};

#endif // !apiAlbumArtH


text:
<?php

/**
 * ListView Model Class for Project module
 */
class Project_ListView_Model extends Vtiger_ListView_Model {

	/**
	 * Function to get the list of listview links
	 * @param <Array> $linkParams Parameters to be replaced in the link template
	 * @return <Array> - an array of Vtiger_Link_Model instances
	 */
	public function getListViewLinks($linkParams) {
		$links = parent::getListViewLinks($linkParams);

		$quickLinks = array(
			array(
				'linktype' => 'LISTVIEWQUICK',
				'linklabel' => 'Tasks List',
				'linkurl' => $this->getModule()->getDefaultUrl(),
				'linkicon' => ''
			),
		);
		foreach($quickLinks as $quickLink) {
			$links['LISTVIEWQUICK'][] = Vtiger_Link_Model::getInstanceFromValues($quickLink);
		}

		return $links;
	}

}


text:
from collections import OrderedDict
import sys
from functools import update_wrapper
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.models.base import ModelBase
from django.utils import six
from django.views.decorators.cache import never_cache

if sys.version_info[0] == 2:
    reload(sys)
    sys.setdefaultencoding("utf-8")
else:
    from imp import reload
    reload(sys)

class AlreadyRegistered(Exception):
    pass

class NotRegistered(Exception):
    pass

class MergeAdminMetaclass(type):
    def __new__(cls, name, bases, attrs):
        return type.__new__(cls, str(name), bases, attrs)

class AdminSite(object):

    def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = OrderedDict()  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
            # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
            # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = OrderedDict()

        self.check_dependencies()

        self.model_admins_order = 0

    def copy_registry(self):
        import copy
        return {
            'models': copy.copy(self._registry),
            'avs': copy.copy(self._registry_avs),
            'views': copy.copy(self._registry_views),
            'settings': copy.copy(self._registry_settings),
            'modelviews': copy.copy(self._registry_modelviews),
            'plugins': copy.copy(self._registry_plugins),
        }

    def restore_registry(self, data):
        self._registry = data['models']
        self._registry_avs = data['avs']
        self._registry_views = data['views']
        self._registry_settings = data['settings']
        self._registry_modelviews = data['modelviews']
        self._registry_plugins = data['plugins']

    def register_modelview(self, path, admin_view_class, name):
        from xadmin.views.base import BaseAdminView
        if issubclass(admin_view_class, BaseAdminView):
            self._registry_modelviews.append((path, admin_view_class, name))
        else:
            raise ImproperlyConfigured(u'The registered view class %s isn\'t subclass of %s' %
                                      (admin_view_class.__name__, BaseAdminView.__name__))

    def register_view(self, path, admin_view_class, name):
        self._registry_views.append((path, admin_view_class, name))

    def register_plugin(self, plugin_class, admin_view_class):
        from xadmin.views.base import BaseAdminPlugin
        if issubclass(plugin_class, BaseAdminPlugin):
            self._registry_plugins.setdefault(
                admin_view_class, []).append(plugin_class)
        else:
            raise ImproperlyConfigured(u'The registered plugin class %s isn\'t subclass of %s' %
                                      (plugin_class.__name__, BaseAdminPlugin.__name__))

    def register_settings(self, name, admin_class):
        self._registry_settings[name.lower()] = admin_class

    def register(self, model_or_iterable, admin_class=object, **options):
        from xadmin.views.base import BaseAdminView
        if isinstance(model_or_iterable, ModelBase) or issubclass(model_or_iterable, BaseAdminView):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if isinstance(model, ModelBase):
                if model._meta.abstract:
                    raise ImproperlyConfigured('The model %s is abstract, so it '
                                               'cannot be registered with admin.' % model.__name__)

                if model in self._registry:
                    raise AlreadyRegistered(
                        'The model %s is already registered' % model.__name__)

                # If we got **options then dynamically construct a subclass of
                # admin_class with those **options.
                if options:
                    # For reasons I don't quite understand, without a __module__
                    # the created class appears to "live" in the wrong place,
                    # which causes issues later on.
                    options['__module__'] = __name__

                admin_class = type(str("%s%sAdmin" % (model._meta.app_label, model._meta.model_name)), (admin_class,), options or {})
                admin_class.model = model
                admin_class.order = self.model_admins_order
                self.model_admins_order += 1
                self._registry[model] = admin_class
            else:
                if model in self._registry_avs:
                    raise AlreadyRegistered('The admin_view_class %s is already registered' % model.__name__)
                if options:
                    options['__module__'] = __name__
                    admin_class = type(str(
                        "%sAdmin" % model.__name__), (admin_class,), options)

                # Instantiate the admin class to save in the registry
                self._registry_avs[model] = admin_class

    def unregister(self, model_or_iterable):
        """
        Unregisters the given model(s).

        If a model isn't already registered, this will raise NotRegistered.
        """
        from xadmin.views.base import BaseAdminView
        if isinstance(model_or_iterable, (ModelBase, BaseAdminView)):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if isinstance(model, ModelBase):
                if model not in self._registry:
                    raise NotRegistered(
                        'The model %s is not registered' % model.__name__)
                del self._registry[model]
            else:
                if model not in self._registry_avs:
                    raise NotRegistered('The admin_view_class %s is not registered' % model.__name__)
                del self._registry_avs[model]

    def set_loginview(self, login_view):
        self.login_view = login_view

    def has_permission(self, request):
        """
        Returns True if the given HttpRequest has permission to view
        *at least one* page in the admin site.
        """
        return request.user.is_active and request.user.is_staff

    def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")
        if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
                'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")

    def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import patterns, url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += patterns('',
                        url(r'^my_view/$', self.admin_view(some_view))
                    )
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view)

    def _get_merge_attrs(self, option_class, plugin_class):
        return dict([(name, getattr(option_class, name)) for name in dir(option_class)
                    if name[0] != '_' and not callable(getattr(option_class, name)) and hasattr(plugin_class, name)])

    def _get_settings_class(self, admin_view_class):
        name = admin_view_class.__name__.lower()

        if name in self._registry_settings:
            return self._registry_settings[name]
        elif name.endswith('admin') and name[0:-5] in self._registry_settings:
            return self._registry_settings[name[0:-5]]
        elif name.endswith('adminview') and name[0:-9] in self._registry_settings:
            return self._registry_settings[name[0:-9]]

        return None

    def _create_plugin(self, option_classes):
        def merge_class(plugin_class):
            if option_classes:
                attrs = {}
                bases = [plugin_class]
                for oc in option_classes:
                    attrs.update(self._get_merge_attrs(oc, plugin_class))
                    meta_class = getattr(oc, plugin_class.__name__, getattr(oc, plugin_class.__name__.replace('Plugin', ''), None))
                    if meta_class:
                        bases.insert(0, meta_class)
                if attrs:
                    plugin_class = MergeAdminMetaclass(
                        '%s%s' % (''.join([oc.__name__ for oc in option_classes]), plugin_class.__name__),
                        tuple(bases), attrs)
            return plugin_class
        return merge_class

    def get_plugins(self, admin_view_class, *option_classes):
        from xadmin.views import BaseAdminView
        plugins = []
        opts = [oc for oc in option_classes if oc]
        for klass in admin_view_class.mro():
            if klass == BaseAdminView or issubclass(klass, BaseAdminView):
                merge_opts = []
                reg_class = self._registry_avs.get(klass)
                if reg_class:
                    merge_opts.append(reg_class)
                settings_class = self._get_settings_class(klass)
                if settings_class:
                    merge_opts.append(settings_class)
                merge_opts.extend(opts)
                ps = self._registry_plugins.get(klass, [])
                plugins.extend(map(self._create_plugin(
                    merge_opts), ps) if merge_opts else ps)
        return plugins

    def get_view_class(self, view_class, option_class=None, **opts):
        merges = [option_class] if option_class else []
        for klass in view_class.mro():
            reg_class = self._registry_avs.get(klass)
            if reg_class:
                merges.append(reg_class)
            settings_class = self._get_settings_class(klass)
            if settings_class:
                merges.append(settings_class)
            merges.append(klass)
        new_class_name = ''.join([c.__name__ for c in merges])

        if new_class_name not in self._admin_view_cache:
            plugins = self.get_plugins(view_class, option_class)
            self._admin_view_cache[new_class_name] = MergeAdminMetaclass(
                new_class_name, tuple(merges),
                dict({'plugin_classes': plugins, 'admin_site': self}, **opts))

        return self._admin_view_cache[new_class_name]

    def create_admin_view(self, admin_view_class):
        return self.get_view_class(admin_view_class).as_view()

    def create_model_admin_view(self, admin_view_class, model, option_class):
        return self.get_view_class(admin_view_class, option_class).as_view()

    def get_urls(self):
        from django.conf.urls import patterns, url, include
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = patterns('', url(r'^jsi18n/$', wrap(self.i18n_javascript,cacheable=True), name='jsi18n'))

        # Registed admin views
        urlpatterns += patterns('',
                                *[url(
                                    path,
                                    wrap(self.create_admin_view(clz_or_func)) if type(clz_or_func) == type and issubclass(clz_or_func, BaseAdminView) else include(clz_or_func(self)),
                                    name=name
                                ) for path, clz_or_func, name in self._registry_views]
                            )

        # Add in each model's views.
        for model, admin_class in six.iteritems(self._registry):
            view_urls = []
            for path, clz, name in self._registry_modelviews:
                _url =  url(path,
                            wrap(self.create_model_admin_view(clz, model, admin_class)),
                            name = name % (model._meta.app_label, model._meta.model_name) )
                view_urls.append(_url)

            _url = url(r'^%s/%s/'%(model._meta.app_label, model._meta.model_name), include(patterns('', *view_urls)))
            urlpatterns += patterns('', _url)

        return urlpatterns

    @property
    def urls(self):
        return self.get_urls(), self.name, self.app_name

    def i18n_javascript(self, request):
        """
        Displays the i18n JavaScript that the Django admin requires.

        This takes into account the USE_I18N setting. If it's set to False, the
        generated JavaScript will be leaner and faster.
        """
        if settings.USE_I18N:
            from django.views.i18n import javascript_catalog
        else:
            from django.views.i18n import null_javascript_catalog as javascript_catalog
        return javascript_catalog(request, packages=['django.conf', 'xadmin'])

# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()


text:
using namespace whiskey;

class MyRule : public ParserRule {
protected:
  ParserResult onParse(const ParserGrammar &grammar, ParserContext &ctx, MessageContext &msgs) const {
    msgs.emit(ctx.get(), Message::Severity::Error);
    return Node(NodeType::StmtEmpty, ctx.eat());
  }

public:
  MyRule() : ParserRule("asdf", "asdf") {}
};

TEST(Unit_Parsing_ParserRule, Simple) {
  ParserGrammar grammar;

  ParserRuleID rule = grammar.addRule(std::make_unique<MyRule>());

  std::vector<Token> toks = {
    Token(TokenID::Symbol)
  };

  ParserContext ctx(toks);
  MessageContext msgs;

  ParserResult res = grammar.getRule(rule).parse(grammar, ctx, msgs);

  ASSERT_TRUE(res.isGood());
  ASSERT_EQ(res.getNode().getType(), NodeType::StmtEmpty);
  ASSERT_EQ(res.getNode().getToken().getID(), TokenID::Symbol);
  ASSERT_EQ(msgs.getMessageCount(), 1);
  ASSERT_EQ(msgs.getErrorCount(), 1);
}


text:
@charset "iso-8859-11";
.tést { color: white; background: green; }


text:
package demoapp.dom.types.javalang.shorts.holder;

import java.util.List;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.apache.causeway.applib.annotation.Action;
import org.apache.causeway.applib.annotation.ActionLayout;
import org.apache.causeway.applib.annotation.MemberSupport;
import org.apache.causeway.applib.annotation.PromptStyle;
import org.apache.causeway.applib.annotation.SemanticsOf;

import demoapp.dom.types.Samples;
import lombok.RequiredArgsConstructor;

/* This file was GENERATED by the showcase generator (tooling). Do NOT edit! */
//tag::class[]
@Action(
        semantics = SemanticsOf.IDEMPOTENT
)
@ActionLayout(
        promptStyle = PromptStyle.INLINE
        , named = "Update with choices"
        , associateWith = "readOnlyProperty"
        , sequence = "2")
@RequiredArgsConstructor
public class WrapperShortHolder_updateReadOnlyPropertyWithChoices {

    private final WrapperShortHolder holder;

    @MemberSupport public WrapperShortHolder act(final java.lang.Short newValue) {
        holder.setReadOnlyProperty(newValue);
        return holder;
    }

    @MemberSupport public java.lang.Short default0Act() {
        return holder.getReadOnlyProperty();
    }

    @MemberSupport public List<java.lang.Short> choices0Act() {
        return samples.stream()
                .collect(Collectors.toList());
    }

    @Inject
    Samples<java.lang.Short> samples;

}
//end::class[]


text:
import { Member } from './member';
import { Activity } from '../activity/activity'
import { Pledge } from '../pledge/pledge'

export class MemberInfo {
  member: Member;
  memberActivities: Activity[];
  pledges: Pledge[];
}


text:
<?php

namespace VolunteerManagementSystem\pagesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use VolunteerManagementSystem\RegistrationBundle\Entity\User;

class NameType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

           $builder

            ->add('firstname','text', array(
            'label'  => 'First Name',
            'attr'   =>  array(
                'class'   => 'login',
                'placeholder' => "enter your first name")
            ))
            ->add('lastname','text', array(
            'label'  => 'Last Name',
            'attr'   =>  array(
                'class'   => 'login',
                'placeholder' => "enter your last name"
                )
            ))
            ->add('namewithinitials','text', array(
            'label'  => 'Name with Initials',
            'attr'   =>  array(
                'class'   => 'login',
                'placeholder' => "enter your name with the initials"
                )
            ));
           $builder

            ->add('submit','submit', array(
                'label' => 'Save Name',
                'attr' => array(
                    'class' => 'button'
                )

            ));
        ;

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'VolunteerManagementSystem\RegistrationBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'volunteermanagementsystem_registrationbundle_user';
    }
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	<meta name="author" content="Martin Suchan">
	<title>wp10.14393.to.wp10.15063.diff</title>

Windows <input checked type="checkbox" id="id54d480820c224d4d850bd8aaf0e8a53c" />

ApplicationModel <input checked type="checkbox" id="id8a4df62a95744cff888ccff580dec270" />

Activation <input checked type="checkbox" id="id66ec1fa0a0964ff7bdf6133191f18bde" />

ContactPanelActivatedEventArgs

IContactPanelActivatedEventArgs

LockScreenComponentActivatedEventArgs

Background <input checked type="checkbox" id="id6b604f637cbb4163848d0b9c7170ca7d" />

BackgroundTaskRegistrationGroup

GattServiceProviderTrigger

GattServiceProviderTriggerResult

IBackgroundTaskRegistration3

Contacts <input checked type="checkbox" id="idcaa9099be338402ab935a2e67ceb1452" />

ContactGroup

ContactPanel

ContactPanelClosingEventArgs

ContactPanelLaunchFullAppRequestedEventArgs

PinnedContactIdsQueryResult

PinnedContactManager

PinnedContactSurface

DataTransfer <input checked type="checkbox" id="id5a131dc93d8b4fd9b3bee1fe67b70392" />

ShareProviderHandler

ShareCompletedEventArgs

ShareProvider

ShareProviderOperation

ShareProvidersRequestedEventArgs

ShareTargetInfo

Payments <input checked type="checkbox" id="id6462ced1962c49268710e07c7f2bea09" />

Provider <input checked type="checkbox" id="ideb97423556634f9abf0192ba6e08b315" />

PaymentAppManager

PaymentTransaction

PaymentTransactionAcceptResult

PaymentRequestChangedHandler

PaymentAddress

PaymentCurrencyAmount

PaymentDetails

PaymentDetailsModifier

PaymentItem

PaymentMediator

PaymentMerchantInfo

PaymentMethodData

PaymentOptionPresence

PaymentOptions

PaymentRequest

PaymentRequestCompletionStatus

PaymentRequestChangedArgs

PaymentRequestChangedResult

PaymentRequestChangeKind

PaymentRequestStatus

PaymentRequestSubmitResult

PaymentResponse

PaymentShippingOption

PaymentShippingType

PaymentToken

Preview <input checked type="checkbox" id="ide44129c550eb4c4ea24bf539e4c32820" />

Holographic <input checked type="checkbox" id="idf1c9d26211424e6bab68898f775a6d45" />

HolographicApplicationPreview

Store <input checked type="checkbox" id="id43a2268bef2541ae82f7f82106302403" />

LicenseManagement <input checked type="checkbox" id="idff9397f36d4644ed8fd7c118a4df7e29" />

LicenseRefreshOption

Preview <input checked type="checkbox" id="id1c671bca916546419143cf684b95830d" />

InstallControl <input checked type="checkbox" id="id4e93b40a843246359b007cb4826041e2" />

GetEntitlementResult

GetEntitlementStatus

WebAuthenticationCoreManagerHelper

UserDataTasks <input checked type="checkbox" id="idf8d1e47a7dbc40bd90ea1523d19cf0c3" />

DataProvider <input checked type="checkbox" id="id44fa8175e06043f1b2608873a7ebdc45" />

UserDataTaskDataProviderConnection

UserDataTaskDataProviderTriggerDetails

UserDataTaskListCompleteTaskRequest

UserDataTaskListCompleteTaskRequestEventArgs

UserDataTaskListCreateOrUpdateTaskRequest

UserDataTaskListCreateOrUpdateTaskRequestEventArgs

UserDataTaskListDeleteTaskRequest

UserDataTaskListDeleteTaskRequestEventArgs

UserDataTaskListSkipOccurrenceRequest

UserDataTaskListSkipOccurrenceRequestEventArgs

UserDataTaskListSyncManagerSyncRequest

UserDataTaskListSyncManagerSyncRequestEventArgs

UserDataTask

UserDataTaskBatch

UserDataTaskDaysOfWeek

UserDataTaskDetailsKind

UserDataTaskKind

UserDataTaskList

UserDataTaskListLimitedWriteOperations

UserDataTaskListOtherAppReadAccess

UserDataTaskListOtherAppWriteAccess

UserDataTaskListSyncManager

UserDataTaskListSyncStatus

UserDataTaskManager

UserDataTaskPriority

UserDataTaskQueryKind

UserDataTaskQueryOptions

UserDataTaskQuerySortProperty

UserDataTaskReader

UserDataTaskRecurrenceProperties

UserDataTaskRecurrenceUnit

UserDataTaskRegenerationProperties

UserDataTaskRegenerationUnit

UserDataTaskSensitivity

UserDataTaskStore

UserDataTaskStoreAccessType

UserDataTaskWeekOfMonth

PackageCatalogAddOptionalPackageResult

PackageContentGroup

PackageContentGroupStagingEventArgs

PackageContentGroupState

Devices <input checked type="checkbox" id="ida0a8ad42ca2b4ae2ba72648c2452f5a7" />

Bluetooth <input checked type="checkbox" id="idaf26166771874265b6667d57157f51c1" />

Background <input checked type="checkbox" id="id4dc381b0abb444fbb70a7c5acc1926f1" />

BluetoothEventTriggeringMode

GattServiceProviderConnection

GattServiceProviderTriggerDetails

GenericAttributeProfile <input checked type="checkbox" id="idb67edc71156549bfb917bba7fc52a980" />

GattClientNotificationResult

GattDescriptorsResult

GattDeviceServicesResult

GattCharacteristicsResult

GattLocalDescriptor

GattLocalDescriptorParameters

GattLocalDescriptorResult

GattLocalCharacteristic

GattLocalCharacteristicParameters

GattLocalCharacteristicResult

GattLocalService

GattOpenStatus

GattProtocolError

GattReadRequest

GattReadRequestedEventArgs

GattRequestState

GattRequestStateChangedEventArgs

GattServiceProvider

GattServiceProviderAdvertisementStatus

GattServiceProviderAdvertisementStatusChangedEventArgs

GattServiceProviderAdvertisingParameters

GattServiceProviderResult

GattSession

GattSessionStatus

GattSessionStatusChangedEventArgs

GattSharingMode

GattSubscribedClient

GattWriteRequest

GattWriteRequestedEventArgs

GattWriteResult

BluetoothAdapter

BluetoothDeviceId

BluetoothUuidHelper

Gpio <input checked type="checkbox" id="idb6f521cf43e74dd6bf98f2d958a404a5" />

GpioChangeCount

GpioChangeCounter

GpioChangePolarity

GpioChangeReader

GpioChangeRecord

Haptics <input checked type="checkbox" id="id4d35bdd5faac4b96ba23662a6fed8d1f" />

KnownSimpleHapticsControllerWaveforms

SimpleHapticsController

SimpleHapticsControllerFeedback

VibrationAccessStatus

VibrationDevice

PointOfService <input checked type="checkbox" id="id5681d5b4fc5747709f33c15d94c999bd" />

BarcodeSymbologyAttributes

BarcodeSymbologyDecodeLengthKind

ClaimedLineDisplay

LineDisplay

LineDisplayCapabilities

LineDisplayScrollDirection

LineDisplayTextAttribute

LineDisplayTextAttributeGranularity

LineDisplayWindow

PosConnectionTypes

SmartCards <input checked type="checkbox" id="id029c0a9766fe4d11ad7c717338b2e1ca" />

SmartCardCryptogramGetAllCryptogramMaterialCharacteristicsResult

SmartCardCryptogramGetAllCryptogramMaterialPackageCharacteristicsResult

SmartCardCryptogramGetAllCryptogramStorageKeyCharacteristicsResult

SmartCardCryptogramMaterialCharacteristics

SmartCardCryptogramMaterialPackageCharacteristics

SmartCardCryptogramMaterialProtectionMethod

SmartCardCryptogramStorageKeyCharacteristics

Foundation <input checked type="checkbox" id="idb42aac5d8aac464c89fd1e1442749644" />

Metadata <input checked type="checkbox" id="idf8ace69719bd48b88f55a8e46b860f7c" />

FeatureAttribute

FeatureStage

Gaming <input checked type="checkbox" id="id932a75bcc9dd4d2d995412b46d28f9fa" />

Input <input checked type="checkbox" id="id4f1fab7f83014febb5e20c4568e705c6" />

Custom <input checked type="checkbox" id="id565003e9c78441b189a22c1284b0ce8e" />

HidGameControllerProvider

IHidGameControllerInputSink

FlightStick

FlightStickButtons

FlightStickReading

GameControllerSwitchKind

GameControllerSwitchPosition

IGameControllerBatteryInfo

RawGameController

UI <input checked type="checkbox" id="id6d97cbe08b28476591cba891ebf873f6" />

GameChatMessageOrigin

GameChatOverlay

GameChatOverlayPosition

Graphics <input checked type="checkbox" id="idc8a12eb9c9534109ace398f6186ee2a0" />

Display <input checked type="checkbox" id="id819fcf10eb9a4d62a4f1a4c68f348d38" />

Core <input checked type="checkbox" id="ida1ea82357da54640811cd1bf7189c853" />

HdmiDisplayColorSpace

HdmiDisplayHdr2086Metadata

HdmiDisplayHdrOption

HdmiDisplayInformation

HdmiDisplayMode

HdmiDisplayPixelEncoding

BrightnessOverride

DisplayBrightnessOverrideOptions

DisplayBrightnessScenario

Holographic <input checked type="checkbox" id="ide527cb823a7748e991cddebb0ec2d90e" />

HolographicCameraViewportParameters

HolographicDisplay

HolographicReprojectionMode

PointInt32

RectInt32

SizeInt32

Management <input checked type="checkbox" id="idf78f4665b4594e078c6a873a2f128a6a" />

Deployment <input checked type="checkbox" id="id9dda2afb9b114eb9bb9b00822e1e9fcc" />

PackageManagerDebugSettings

Policies <input checked type="checkbox" id="idf93aa3b07ae5489a8c8ce71f2b9ba830" />

NamedPolicy

NamedPolicyData

NamedPolicyKind

MdmAlert

MdmAlertDataType

MdmAlertMark

MdmSession

MdmSessionManager

MdmSessionState

Media <input checked type="checkbox" id="iddc18d434c7924ca1abea9e414720d609" />

Capture <input checked type="checkbox" id="idee449441d4ce49659632e00caa358f4f" />

Frames <input checked type="checkbox" id="id8ee65176e02b4318b12e7c71977df02b" />

MultiSourceMediaFrameArrivedEventArgs

MultiSourceMediaFrameReader

MultiSourceMediaFrameReaderStartStatus

MultiSourceMediaFrameReference

MediaCaptureDeviceExclusiveControlStatus

MediaCaptureDeviceExclusiveControlStatusChangedEventArgs

Core <input checked type="checkbox" id="idcb50dc339ba248c7a1aaba997bd79700" />

Preview <input checked type="checkbox" id="idc9dd3a2ecfe849f3aa5c2d9ea41da0d3" />

SoundLevelBroker

CodecCategory

CodecInfo

CodecKind

CodecQuery

CodecSubtypes

ChapterCue

ImageCue

ITimedMetadataTrackProvider

SpeechCue

TimedTextFontStyle

Devices <input checked type="checkbox" id="idb7ccac09005c489490bb2cda976b2670" />

AudioDeviceModule

AudioDeviceModuleNotificationEventArgs

AudioDeviceModulesManager

ModuleCommandResult

SendCommandStatus

VideoDeviceControllerGetDevicePropertyResult

VideoDeviceControllerGetDevicePropertyStatus

VideoDeviceControllerSetDevicePropertyStatus

MediaProperties <input checked type="checkbox" id="ida8a2d28fa0ab4f3c915d43ea628ffb06" />

SphericalVideoFrameFormat

Playback <input checked type="checkbox" id="id65e3fb44653f4a3fbed8e3ae2b18ea89" />

AutoLoadedDisplayPropertyKind

MediaPlaybackItemChangedReason

MediaPlaybackSphericalVideoProjection

SphericalVideoProjectionMode

Protection <input checked type="checkbox" id="id70eb943ac8d04776a4a92c54b182d962" />

PlayReady <input checked type="checkbox" id="id9d91cf7f3d13450b84c29eea5f8e7908" />

IPlayReadyLicenseSession2

SpeechSynthesis <input checked type="checkbox" id="id71eb616de1b8496f8a444edecae2899c" />

SpeechSynthesizerOptions

Streaming <input checked type="checkbox" id="id061a6cbc3d0f4325b517d7431817794c" />

Adaptive <input checked type="checkbox" id="id7a9f04754b664e1bb461ec5bdbcbf545" />

AdaptiveMediaSourceCorrelatedTimes

AdaptiveMediaSourceDiagnosticAvailableEventArgs

AdaptiveMediaSourceDiagnostics

AdaptiveMediaSourceDiagnosticType

AdaptiveMediaSourceDownloadBitrateChangedReason

AdaptiveMediaSourceDownloadStatistics

MediaTimelineControllerFailedEventArgs

MediaTimeRange

Perception <input checked type="checkbox" id="idfb5b209b7df14d5aa96720eeb342d150" />

Spatial <input checked type="checkbox" id="id7e3c2de063324ce0bcbc506bf942dcc9" />

SpatialEntity

SpatialEntityAddedEventArgs

SpatialEntityRemovedEventArgs

SpatialEntityStore

SpatialEntityUpdatedEventArgs

SpatialEntityWatcher

SpatialEntityWatcherStatus

SpatialLookDirectionRange

SpatialMovementRange

SpatialStageFrameOfReference

Security <input checked type="checkbox" id="idc799c9274c6a4c5c9b835354c084392f" />

Authentication <input checked type="checkbox" id="idcef6cfd9fd6644e19c9026e290500f21" />

Identity <input checked type="checkbox" id="id5c18453da9854631b67b1454b2aa4bb3" />

Provider <input checked type="checkbox" id="id005c54b184264ba6bf57389a7c9ff2e5" />

SecondaryAuthenticationFactorDevicePresence

SecondaryAuthenticationFactorDevicePresenceMonitoringMode

SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus

OnlineId <input checked type="checkbox" id="id0705ade51c5f43e985fa83072040a6df" />

OnlineIdSystemAuthenticator

OnlineIdSystemAuthenticatorForUser

OnlineIdSystemIdentity

OnlineIdSystemTicketResult

OnlineIdSystemTicketStatus

Web <input checked type="checkbox" id="id5b500cbe835e43f8a9a800f16528a4e7" />

Provider <input checked type="checkbox" id="id1ed731b1af2548af881f475d371814ce" />

IWebAccountProviderTokenObjects2

Cryptography <input checked type="checkbox" id="id897f0b75cf97496d82303884db446bd6" />

Certificates <input checked type="checkbox" id="idb3aa57ab47d04a79be69cbc2da40bec4" />

CertificateExtension

EnterpriseData <input checked type="checkbox" id="id26f6ca696af94f159fda969b486eb4d8" />

FileUnprotectOptions

Services <input checked type="checkbox" id="id4eee227561bd434aa2d4d9e297644a2d" />

Cortana <input checked type="checkbox" id="id145d3fd821f3405099fbd22de07ae73a" />

CortanaPermission

CortanaPermissionsChangeResult

CortanaPermissionsManager

Maps <input checked type="checkbox" id="idea7b5d098611403eb7a4957f67c81ec0" />

OfflineMaps <input checked type="checkbox" id="id4fa2dc30571d4790aaab4cdd31db5c90" />

OfflineMapPackage

OfflineMapPackageQueryResult

OfflineMapPackageQueryStatus

OfflineMapPackageStartDownloadResult

OfflineMapPackageStartDownloadStatus

OfflineMapPackageStatus

EnhancedWaypoint

ManeuverWarning

ManeuverWarningKind

ManeuverWarningSeverity

MapServiceDataUsagePreference

TrafficCongestion

WaypointKind

TargetedContent <input checked type="checkbox" id="idc611506201824edc82b8cc669c3ea183" />

TargetedContentAction

TargetedContentAppInstallationState

TargetedContentAvailability

TargetedContentAvailabilityChangedEventArgs

TargetedContentCollection

TargetedContentContainer

TargetedContentContract

TargetedContentFile

TargetedContentChangedEventArgs

TargetedContentImage

TargetedContentInteraction

TargetedContentItem

TargetedContentItemState

TargetedContentObject

TargetedContentObjectKind

TargetedContentStateChangedEventArgs

TargetedContentSubscription

TargetedContentSubscriptionOptions

TargetedContentValue

TargetedContentValueKind

System <input checked type="checkbox" id="id3408f99f6209444aaaf03c712cb78381" />

Diagnostics <input checked type="checkbox" id="idad27f425f3b047ceba95b66bac77a95c" />

DevicePortal <input checked type="checkbox" id="id2b344ba9b93b4eb387090ad3999343d6" />

DevicePortalConnection

DevicePortalConnectionClosedEventArgs

DevicePortalConnectionClosedReason

DevicePortalConnectionRequestReceivedEventArgs

Telemetry <input checked type="checkbox" id="id226db225274f41eb90cd6078e3416843" />

PlatformTelemetryClient

PlatformTelemetryRegistrationResult

PlatformTelemetryRegistrationSettings

PlatformTelemetryRegistrationStatus

TraceReporting <input checked type="checkbox" id="idfdb973648d2b4c2da5ffc2394b7f0feb" />

PlatformDiagnosticActions

PlatformDiagnosticActionState

PlatformDiagnosticEscalationType

PlatformDiagnosticEventBufferLatencies

PlatformDiagnosticTraceInfo

PlatformDiagnosticTracePriority

PlatformDiagnosticTraceRuntimeInfo

PlatformDiagnosticTraceSlotState

PlatformDiagnosticTraceSlotType

SystemCpuUsage

SystemCpuUsageReport

SystemDiagnosticInfo

SystemMemoryUsage

SystemMemoryUsageReport

Profile <input checked type="checkbox" id="id41e7ff57424c40d1819b9640a3965419" />

EducationSettings

RemoteSystems <input checked type="checkbox" id="idee216f08aba8460f830e881467885ffe" />

KnownRemoteSystemCapabilities

RemoteSystemAuthorizationKind

RemoteSystemAuthorizationKindFilter

RemoteSystemSession

RemoteSystemSessionAddedEventArgs

RemoteSystemSessionController

RemoteSystemSessionCreationResult

RemoteSystemSessionCreationStatus

RemoteSystemSessionDisconnectedEventArgs

RemoteSystemSessionDisconnectedReason

RemoteSystemSessionInfo

RemoteSystemSessionInvitation

RemoteSystemSessionInvitationListener

RemoteSystemSessionInvitationReceivedEventArgs

RemoteSystemSessionJoinRequest

RemoteSystemSessionJoinRequestedEventArgs

RemoteSystemSessionJoinResult

RemoteSystemSessionJoinStatus

RemoteSystemSessionMessageChannel

RemoteSystemSessionMessageChannelReliability

RemoteSystemSessionOptions

RemoteSystemSessionParticipant

RemoteSystemSessionParticipantAddedEventArgs

RemoteSystemSessionParticipantRemovedEventArgs

RemoteSystemSessionParticipantWatcher

RemoteSystemSessionParticipantWatcherStatus

RemoteSystemSessionRemovedEventArgs

RemoteSystemSessionUpdatedEventArgs

RemoteSystemSessionValueSetReceivedEventArgs

RemoteSystemSessionWatcher

RemoteSystemSessionWatcherStatus

UserProfile <input checked type="checkbox" id="id5ae9e52dce5f4adf87e612213ff57848" />

DiagnosticsSettings

AppDiagnosticInfo

UI <input checked type="checkbox" id="id0c7f93088ee2479485350f65673897ff" />

Composition <input checked type="checkbox" id="idd659045f0e084fda9cbc3a64e8d54558" />

Interactions <input checked type="checkbox" id="iddd548636bbf14420b6924d58adad4945" />

CompositionConditionalValue

AnimationDelayBehavior

CompositionCapabilities

CompositionVirtualDrawingSurface

Core <input checked type="checkbox" id="id0890f4de2f7f4e9a8722e92377e85e29" />

Preview <input checked type="checkbox" id="id0f7233a43fcb4f08b1ba42c25aa38ff3" />

SystemNavigationCloseRequestedPreviewEventArgs

SystemNavigationManagerPreview

Input <input checked type="checkbox" id="id142ab3ecf2e94e7cb8070cdad1d88593" />

Core <input checked type="checkbox" id="idd863368a94ac49eeb9780dee7d80723c" />

RadialControllerIndependentInputSource

Inking <input checked type="checkbox" id="idb49081f4e23942d6a7fc2b981b406c76" />

Analysis <input checked type="checkbox" id="id6972a2a5e2de4c16b2f2da8f3e44c867" />

IInkAnalysisNode

IInkAnalyzerFactory

InkAnalysisDrawingKind

InkAnalysisInkBullet

InkAnalysisInkDrawing

InkAnalysisInkWord

InkAnalysisLine

InkAnalysisListItem

InkAnalysisNode

InkAnalysisNodeKind

InkAnalysisParagraph

InkAnalysisResult

InkAnalysisRoot

InkAnalysisStatus

InkAnalysisStrokeKind

InkAnalysisWritingRegion

InkAnalyzer

InkHighContrastAdjustment

InkPersistenceFormat

InkPresenterProtractor

Spatial <input checked type="checkbox" id="id705603ab5f3845c6966057ecca1d8d6b" />

SpatialInteractionController

SpatialInteractionControllerProperties

SpatialInteractionPressKind

SpatialPointerInteractionSourcePose

RadialControllerButtonHoldingEventArgs

RadialControllerButtonPressedEventArgs

RadialControllerButtonReleasedEventArgs

RadialControllerScreenContactEndedEventArgs

Notifications <input checked type="checkbox" id="id1a5a839968f24b678730fb785cccfadf" />

NotificationData

NotificationUpdateResult

ToastCollection

ToastCollectionManager

ToastNotificationPriority

StartScreen <input checked type="checkbox" id="ide9d472ce081047ac8a2134291be44d7c" />

StartScreenManager

Text <input checked type="checkbox" id="idde4aba2c7f7e45119902177857777ac6" />

RichEditTextDocument

TextDecorations

ViewManagement <input checked type="checkbox" id="id3fd122ecf57f4377bb68e5786d351065" />

ApplicationViewMode

ViewModePreferences

WebUI <input checked type="checkbox" id="idec0617759e5a4920865a0adfdb8f54fb" />

WebUIContactPanelActivatedEventArgs

WebUILockScreenComponentActivatedEventArgs

WebUIPrintWorkflowForegroundTaskActivatedEventArgs

Xaml <input checked type="checkbox" id="ida32928b56f94456392ca5dcc476ca85f" />

Controls <input checked type="checkbox" id="id6124a5d11b914637865e2b55288ce592" />

Maps <input checked type="checkbox" id="id7e5a5361d5c8445c99acddab56da689b" />

MapBillboard

MapContextRequestedEventArgs

MapProjection

MapStyleSheet

ComboBoxSelectionChangedTrigger

ContentDialogButton

InkToolbarButtonFlyoutPlacement

InkToolbarFlyoutItem

InkToolbarFlyoutItemKind

InkToolbarIsStencilButtonCheckedChangedEventArgs

InkToolbarMenuButton

InkToolbarMenuKind

InkToolbarStencilButton

InkToolbarStencilKind

Input <input checked type="checkbox" id="idbd44d5f49e2d4609843afad7fda61c14" />

FindNextElementOptions

FocusInputDeviceKind

GettingFocusEventArgs

KeyTipPlacementMode

LosingFocusEventArgs

NoFocusCandidateFoundEventArgs

XYFocusKeyboardNavigationMode

XYFocusNavigationStrategy

XYFocusNavigationStrategyOverride

Markup <input checked type="checkbox" id="id48f5662e8be74c2f8c57982e739ae200" />

XamlMarkupHelper

Media <input checked type="checkbox" id="id0c120c16cc0944329efd14e8cfbf5cc7" />

Animation <input checked type="checkbox" id="id570573f7db554d31a617e118106ac842" />

ConnectedAnimationComponent

Imaging <input checked type="checkbox" id="idc857e48ba6eb46418b8301ea9b3173ae" />

SvgImageSource

SvgImageSourceFailedEventArgs

SvgImageSourceLoadStatus

SvgImageSourceOpenedEventArgs

LoadedImageSourceLoadCompletedEventArgs

LoadedImageSourceLoadStatus

LoadedImageSurface

XamlCompositionBrushBase

XamlLight

ApplicationHighContrastAdjustment

BringIntoViewOptions

ElementHighContrastAdjustment


text:
#import "ABI11_0_0RCTNavItemManager.h"

#import "ABI11_0_0RCTConvert.h"
#import "ABI11_0_0RCTNavItem.h"

@implementation ABI11_0_0RCTConvert (BarButtonSystemItem)

ABI11_0_0RCT_ENUM_CONVERTER(UIBarButtonSystemItem, (@{
  @"done": @(UIBarButtonSystemItemDone),
  @"cancel": @(UIBarButtonSystemItemCancel),
  @"edit": @(UIBarButtonSystemItemEdit),
  @"save": @(UIBarButtonSystemItemSave),
  @"add": @(UIBarButtonSystemItemAdd),
  @"flexible-space": @(UIBarButtonSystemItemFlexibleSpace),
  @"fixed-space": @(UIBarButtonSystemItemFixedSpace),
  @"compose": @(UIBarButtonSystemItemCompose),
  @"reply": @(UIBarButtonSystemItemReply),
  @"action": @(UIBarButtonSystemItemAction),
  @"organize": @(UIBarButtonSystemItemOrganize),
  @"bookmarks": @(UIBarButtonSystemItemBookmarks),
  @"search": @(UIBarButtonSystemItemSearch),
  @"refresh": @(UIBarButtonSystemItemRefresh),
  @"stop": @(UIBarButtonSystemItemStop),
  @"camera": @(UIBarButtonSystemItemCamera),
  @"trash": @(UIBarButtonSystemItemTrash),
  @"play": @(UIBarButtonSystemItemPlay),
  @"pause": @(UIBarButtonSystemItemPause),
  @"rewind": @(UIBarButtonSystemItemRewind),
  @"fast-forward": @(UIBarButtonSystemItemFastForward),
  @"undo": @(UIBarButtonSystemItemUndo),
  @"redo": @(UIBarButtonSystemItemRedo),
  @"page-curl": @(UIBarButtonSystemItemPageCurl)
}), NSNotFound, integerValue);

@end

@implementation ABI11_0_0RCTNavItemManager

ABI11_0_0RCT_EXPORT_MODULE()

- (UIView *)view
{
  return [ABI11_0_0RCTNavItem new];
}

ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(navigationBarHidden, BOOL)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(shadowHidden, BOOL)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(tintColor, UIColor)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(barTintColor, UIColor)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(translucent, BOOL)

ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(title, NSString)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(titleTextColor, UIColor)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(titleImage, UIImage)

ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(backButtonIcon, UIImage)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(backButtonTitle, NSString)

ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(leftButtonTitle, NSString)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(leftButtonIcon, UIImage)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(leftButtonSystemIcon, UIBarButtonSystemItem)

ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(rightButtonIcon, UIImage)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(rightButtonTitle, NSString)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(rightButtonSystemIcon, UIBarButtonSystemItem)

ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(onLeftButtonPress, ABI11_0_0RCTBubblingEventBlock)
ABI11_0_0RCT_EXPORT_VIEW_PROPERTY(onRightButtonPress, ABI11_0_0RCTBubblingEventBlock)

@end


text:
package com.streamsets.pipeline.lib.generator.json;

import com.google.common.annotations.VisibleForTesting;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.api.ext.ContextExtensions;
import com.streamsets.pipeline.api.ext.JsonRecordWriter;
import com.streamsets.pipeline.api.ext.json.Mode;
import com.streamsets.pipeline.lib.generator.DataGenerator;
import com.streamsets.pipeline.lib.generator.DataGeneratorException;

import java.io.IOException;
import java.io.Writer;

public class JsonCharDataGenerator implements DataGenerator {

  private final JsonRecordWriter recordWriter;
  private final Mode mode;

  public JsonCharDataGenerator(Stage.Context context, Writer writer, Mode mode) throws IOException {
    this.mode = mode;
    ContextExtensions ext = ((ContextExtensions) context);
    recordWriter = ext.createJsonRecordWriter(writer, mode);
  }

  @VisibleForTesting
  boolean isArrayObjects() {
    return mode == Mode.ARRAY_OBJECTS;
  }

  @Override
  public void write(Record record) throws IOException, DataGeneratorException {
    try {
      recordWriter.write(record);
    } catch (IOException e) {
      if (e.getMessage().contains("FileRef")) {
        throw new DataGeneratorException(Errors.JSON_GENERATOR_01);
      } else {
        throw e;
      }
    }
  }

  @Override
  public void flush() throws IOException {
    recordWriter.flush();
  }

  @Override
  public void close() throws IOException {
    recordWriter.close();
  }
}


text:
/*
Suppose you have a random list of people standing in a queue.
Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.
Write an algorithm to reconstruct the queue.
*/

'use strict'

/**
 * @param {number[][]} people
 * @return {number[][]}
 */
const reconstructQueue = function(people) {
  const output = []

  people.sort(function(a, b) {
    return (a[0] === b[0]) ? (a[1] - b[1]) : (b[0] - a[0])
  })

  for (let i = 0; i < people.length; ++i) {
    output.splice(people[i][1], 0, people[i])
  }

  return output
}