<commit_before>var grid = {

  setAmount: function(amount) {
    // This statement will make sure that if amount is not
    // put in there will still be a deafault value.
    var a = amount || 50;
    this.amount = a;
  }, // end

  setDiameter: function() {
    // Checking if the amount is defined. Ifnot it runs the
    // function, giving amount the default value of 50;
    if (this.amount == undefined || this.amount == null) {
      grid.setAmount();
    }
    // Checking which is smaller, the windows height or width.
    // The smallest one determines the diameter of the cells.
    if ($(window).height() > $(window).width()) {
      this.diameter = ($(window).width()-($(window).width() / 10)) /  this.amount;
    }else{
      this.diameter = ($(window).height()-($(window).width() / 10)) /  this.amount;
    }

  }, // end

  randomState: function() {
    // Rounding off a random number between 0 and 1 to
    // get 0 or 1 as a result.
    var state = Math.round(Math.random());
    return state;
  }, // end

  drawGrid: function() {
    // This function draws the grid and creates the objects
    // used to indevidually adress all the cells (cells & YX).

    // Creating an empty object for use later on.
    this.cells = {};
    this.YX = {};
    // Some variables needed.
    var number = 0;
    var y = 1;

    // If the diameter has not yet been set it runs the
    // function and sets it.

    if (this.diameter == undefined || this.diameter == null) {
      this.setDiameter();
    }

    // Two for loops, each runnin 'amount' times.
    // The inside for loop creates 'amount' div's and
    // adds them to the HTML page. The outside loop
    // runs the inner one and adds a line breaker (
)
    // at the end, making sure there's no more than
    // 'amount' div's on one line
    for (var i = 1; i < this.amount+1; i++) {
        // Declaring the x var inside the first loop so
        // it's reset with every line.
        var x = 1;
        this.YX[i] = {};
      for (var j = 1; j < this.amount+1; j++) {
        // A variable set equal to a jquery object for a div
        // with a class of .cell and a set height and width.
        var $cell = $('
')
        .addClass('cell')
        .height(this.diameter)
        .width(this.diameter);

        // This number is used in making the cells object,
        // no number can be the same. Soo +1;
        number = number + 1;

        // Adding a reference to this particular cell inside of
        // the cells object so we can change its classes later on.
        this.cells[number] = $cell;
        // Adding the X and Y coordinate
        this.cells[number]['x'] = x;
        this.cells[number]['y'] = y;

        // Adding the state of the cell to the cell object.
        this.cells[number]['state'] = this.randomState();

        // Adding the dead or alive class.
        if (this.cells[number]['state'] === 1) {
          $cell.addClass('alive');
        }else if (this.cells[number]['state'] === 0){
          $cell.addClass('dead');
        }

        // Adding the div with all its classes to
        // the #grid div in the html page.
        $('#grid').append($cell);

        console.log(i+' '+j);
        this.YX[i][j] = this.cells[number];

        // End of the loop. The next cells' x will be x+1
        x = x + 1;
      } // end of for loop (j)

      // After adding 'amount' divs to the page we add a line breaker to make sure
      // it goes to the next row.
      $('#grid').append($('
'));

      // End of the loop. Next row's y will be y+1
      y = y + 1;
    } // end of dor loop (i)

  }, // end

  updateDiameter: function(interval) {
    // Safety, inside the interval 'this' becomes the window
    // object instead of the grid object. We can now use 'self'.
    var self = this;
    window.setInterval(function () {

      var oldDiameter = self.diameter;
      grid.setDiameter();

      // The for loop runs a lot of times, this if statement prevents it
      // from running if the diameter does NOT change.
      if (oldDiameter !== self.diameter) {
        for (var i = 1; i < (self.amount*self.amount)+1; i++) {
          self.cells[i].height(self.diameter).width(self.diameter);
        }

      }

    }, interval);
  } // end

}; // end of object
<commit_msg>some minor tweaks<commit_after>var grid = {

  setAmount: function(amount) {
    // This statement will make sure that if amount is not
    // put in there will still be a deafault value.
    var a = amount || 50;
    this.amount = a;
  }, // end

  setDiameter: function() {
    // Checking if the amount is defined. Ifnot it runs the
    // function, giving amount the default value of 50;
    if (this.amount == undefined || this.amount == null) {
      grid.setAmount();
    }
    // Checking which is smaller, the windows height or width.
    // The smallest one determines the diameter of the cells.
    if ($(window).height() > $(window).width()) {
      this.diameter = ($(window).width()-($(window).width() / 10)) /  this.amount;
    }else{
      this.diameter = ($(window).height()-($(window).width() / 10)) /  this.amount;
    }

  }, // end

  randomState: function() {
    // Rounding off a random number between 0 and 1 to
    // get 0 or 1 as a result.
    var state = Math.round(Math.random());
    return state;
  }, // end

  drawGrid: function() {
    // This function draws the grid and creates the objects
    // used to indevidually adress all the cells (cells & YX).

    // Creating an empty object for use later on.
    this.cells = {};
    this.YX = {};
    // Some variables needed.
    var number = 0;
    var y = 1;

    // If the diameter has not yet been set it runs the
    // function and sets it.

    if (this.diameter == undefined || this.diameter == null) {
      this.setDiameter();
    }

    // Two for loops, each runnin 'amount' times.
    // The inside for loop creates 'amount' div's and
    // adds them to the HTML page. The outside loop
    // runs the inner one and adds a line breaker (
)
    // at the end, making sure there's no more than
    // 'amount' div's on one line
    for (var i = 1; i < this.amount+1; i++) {
        // Declaring the x var inside the first loop so
        // it's reset with every line.
        var x = 1;
        this.YX[i] = {};
      for (var j = 1; j < this.amount+1; j++) {
        // A variable set equal to a jquery object for a div
        // with a class of .cell and a set height and width.
        var $cell = $('
')
        .addClass('cell')
        .height(this.diameter)
        .width(this.diameter);

        // This number is used in making the 'cells' object,
        // no number can be the same. Soo +1;
        number = number + 1;

        // Adding a reference to this particular cell inside of
        // the cells object so we can change its classes later on.
        this.cells[number] = $cell;
        // Adding the X and Y coordinate
        this.cells[number]['x'] = x;
        this.cells[number]['y'] = y;

        // Adding the state of the cell to the cell object.
        this.cells[number]['state'] = this.randomState();

        // Adding the dead or alive class.
        if (this.cells[number]['state'] === 1) {
          $cell.addClass('alive');
        }else if (this.cells[number]['state'] === 0){
          $cell.addClass('dead');
        }

        // Adding the div with all its classes to
        // the #grid div in the html page.
        $('#grid').append($cell);

        this.YX[i][j] = this.cells[number];

        // End of the loop. The next cells' x will be x+1
        x = x + 1;
      } // end of for loop (j)

      // After adding 'amount' divs to the page we add a line breaker to make sure
      // it goes to the next row.
      $('#grid').append($('
'));

      // End of the loop. Next row's y will be y+1
      y = y + 1;
    } // end of dor loop (i)

  }, // end

  updateDiameter: function(interval) {
    // SAFETY!, inside the interval 'this' becomes the window
    // object instead of the grid object. We can now use 'self'.
    var self = this;
    window.setInterval(function () {

      var oldDiameter = self.diameter;
      grid.setDiameter();

      // The for loop runs a lot of times, this if statement prevents it
      // from running if the diameter does NOT change.
      if (oldDiameter !== self.diameter) {
        for (var i = 1; i < (self.amount*self.amount)+1; i++) {
          self.cells[i].height(self.diameter).width(self.diameter);
        }
      }

    }, interval);
  } // end

}; // end of object
<|endoftext|>


<commit_before>
var AlienFlock = function AlienFlock() {
  this.invulnrable = true;
  this.dx = 10; this.dy = 0;
  this.hit = 1; this.lastHit = 0;
  this.speed = 10;

  this.draw = function() {};

  this.die = function() {
    if(Game.board.nextLevel()) {
      Game.loadBoard(new GameBoard(Game.board.nextLevel()));
    } else {
      Game.callbacks['win']();
    }
  }

  this.step = function(dt) {
    if(this.hit && this.hit != this.lastHit) {
      this.lastHit = this.hit;
      this.dy = this.speed;
    } else {
      this.dy=0;
    }
    this.dx = this.speed * this.hit;

    var max = {}, cnt = 0;
    this.board.iterate(function() {
      if(this instanceof Alien)  {
        if(!max[this.x] || this.y > max[this.x]) {
          max[this.x] = this.y;
        }
        cnt++;
      }
    });

    if(cnt == 0) { this.die(); }

    this.max_y = max;
    return true;
  };

}

var Alien = function Alien(opts) {
  this.flock = opts['flock'];
  this.frame = 0;
  this.mx = 0;
}

Alien.prototype.draw = function(canvas) {
  Sprites.draw(canvas,this.name,this.x,this.y,this.frame);
}

Alien.prototype.die = function() {
  GameAudio.play('die');
  this.flock.speed += 1;
  this.board.remove(this);
}

Alien.prototype.step = function(dt) {               //this moves the alien
  this.mx += dt * this.flock.dx;
  this.y += this.flock.dy;
  if(Math.abs(this.mx) > 10) {
    if(this.y == this.flock.max_y[this.x]) {
      this.fireSometimes();
    }
    this.x += this.mx;
    this.mx = 0;
    this.frame = (this.frame+1) % 3;                //amount of frames
    if(this.x > Game.width - Sprites.map.alien1.w * 2) this.flock.hit = -1;
    if(this.x < Sprites.map.alien1.w) this.flock.hit = 1;
  }
  return true;
}

Alien.prototype.fireSometimes = function() {
      if(Math.random()*100 < 10) {
        this.board.addSprite('missile',this.x + this.w/2 - Sprites.map.missile.w/2,
                                      this.y + this.h,
                                     { dy: 100 });
      }
}

var Player = function Player(opts) {
  this.reloading = 0;
}

Player.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'player',this.x,this.y);
}

Player.prototype.die = function() {
  GameAudio.play('die');
  Game.callbacks['die']();
}

Player.prototype.step = function(dt) {
  if(Game.keys['left']) { this.x -= 100 * dt; }
  if(Game.keys['right']) { this.x += 100 * dt; }

  if(this.x < 0) this.x = 0;
  if(this.x > Game.width-this.w) this.x = Game.width-this.w;

  this.reloading--;

  if(Game.keys['fire'] && this.reloading <= 0 && this.board.missiles < 100) {
    GameAudio.play('fire');
    this.board.addSprite('missile',
                          this.x + this.w/2 - Sprites.map.missile.w/2,
                          this.y-this.h,
                          { dy: -100, player: true });
    this.board.missiles++;
    this.reloading = 10;
  }
  return true;
}

var Missile = function Missile(opts) {
   this.dy = opts.dy;
   this.player = opts.player;
}

Missile.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'missile',this.x,this.y);
}

Missile.prototype.step = function(dt) {
   this.y += this.dy * dt;

   var enemy = this.board.collide(this);
   if(enemy) {
     enemy.die();
     return false;
   }
   return (this.y < 0 || this.y > Game.height) ? false : true;
}

Missile.prototype.die = function() {
  if(this.player) this.board.missiles--;
  if(this.board.missiles < 0) this.board.missiles=0;
   this.board.remove(this);
}
<commit_msg>added comments to code to help myself remember what each part does<commit_after>
var AlienFlock = function AlienFlock() {
  this.invulnrable = true;
  this.dx = 10; this.dy = 0;
  this.hit = 1; this.lastHit = 0;
  this.speed = 10;

  this.draw = function() {};

  this.die = function() {
    if(Game.board.nextLevel()) {
      Game.loadBoard(new GameBoard(Game.board.nextLevel()));
    } else {
      Game.callbacks['win']();
    }
  }

  this.step = function(dt) {
    if(this.hit && this.hit != this.lastHit) {
      this.lastHit = this.hit;
      this.dy = this.speed;
    } else {
      this.dy=0;
    }
    this.dx = this.speed * this.hit;

    var max = {}, cnt = 0;
    this.board.iterate(function() {
      if(this instanceof Alien)  {
        if(!max[this.x] || this.y > max[this.x]) {
          max[this.x] = this.y;
        }
        cnt++;
      }
    });

    if(cnt == 0) { this.die(); }

    this.max_y = max;
    return true;
  };

}

var Alien = function Alien(opts) {
  this.flock = opts['flock'];
  this.frame = 0;
  this.mx = 0;
}

Alien.prototype.draw = function(canvas) {
  Sprites.draw(canvas,this.name,this.x,this.y,this.frame);
}

Alien.prototype.die = function() {
  GameAudio.play('die');
  this.flock.speed += 1;
  this.board.remove(this);
}

Alien.prototype.step = function(dt) {               //this moves the alien
  this.mx += dt * this.flock.dx;
  this.y += this.flock.dy;
  if(Math.abs(this.mx) > 10) {
    if(this.y == this.flock.max_y[this.x]) {
      this.fireSometimes();
    }
    this.x += this.mx;
    this.mx = 0;
    this.frame = (this.frame+1) % 3;                //amount of frames
    if(this.x > Game.width - Sprites.map.alien1.w * 2) this.flock.hit = -1;
    if(this.x < Sprites.map.alien1.w) this.flock.hit = 1;
  }
  return true;
}

Alien.prototype.fireSometimes = function() {
      if(Math.random()*100 < 10) {
        this.board.addSprite('missile',this.x + this.w/2 - Sprites.map.missile.w/2,
                                      this.y + this.h,
                                     { dy: 100 });
      }
}

var Player = function Player(opts) {
  this.reloading = 0;
}

Player.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'player',this.x,this.y);
}

Player.prototype.die = function() {
  GameAudio.play('die');
  Game.callbacks['die']();
}

Player.prototype.step = function(dt) {
  if(Game.keys['left']) { this.x -= 100 * dt; }             //moving the player only left and right
  if(Game.keys['right']) { this.x += 100 * dt; }

  if(this.x < 0) this.x = 0;
  if(this.x > Game.width-this.w) this.x = Game.width-this.w;

  this.reloading--;

  if(Game.keys['fire'] && this.reloading <= 0 && this.board.missiles < 100) {   //allowing player to fire laser
    GameAudio.play('fire');
    this.board.addSprite('missile',
                          this.x + this.w/2 - Sprites.map.missile.w/2,
                          this.y-this.h,
                          { dy: -100, player: true });
    this.board.missiles++;
    this.reloading = 10;
  }
  return true;
}

var Missile = function Missile(opts) {
   this.dy = opts.dy;
   this.player = opts.player;
}

Missile.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'missile',this.x,this.y);
}

Missile.prototype.step = function(dt) {
   this.y += this.dy * dt;

   var enemy = this.board.collide(this);
   if(enemy) {
     enemy.die();
     return false;
   }
   return (this.y < 0 || this.y > Game.height) ? false : true;
}

Missile.prototype.die = function() {
  if(this.player) this.board.missiles--;
  if(this.board.missiles < 0) this.board.missiles=0;
   this.board.remove(this);
}
<|endoftext|>


<commit_before>var opentype = require('opentype.js'),
	paper = require('paper'),
	Glyph = require('./Glyph.js'),
	assign = require('es6-object-assign').assign;

function Font( args ) {
	paper.Group.prototype.constructor.apply( this );

	args = assign({
		familyName: 'Default familyName',
		styleName: 'Regular',
		ascender: 1,
		descender: -1,
		unitsPerEm: 1024
	}, args);

	this.fontinfo = this.ot = new opentype.Font( args );

	this.glyphMap = {};
	this.charMap = {};
	this.altMap = {};
	this._subset = false;
	this.fontMap = {};

	this.addGlyph(new Glyph({
		name: '.notdef',
		unicode: 0,
		advanceWidth: 650
	}));

	if ( args && args.glyphs ) {
		this.addGlyphs( args.glyphs );
	}

	if ( typeof window === 'object' && window.document && !document.fonts ) {
		document.head.appendChild(
			this.styleElement = document.createElement('style')
		);
		// let's find the corresponding CSSStyleSheet
		// (would be much easier with Array#find)
		this.styleSheet = document.styleSheets[
			[].map.call(document.styleSheets, function(ss) {
				return ss.ownerNode;
			}).indexOf(this.styleElement)
		];
	}
}

Font.prototype = Object.create(paper.Group.prototype);
Font.prototype.constructor = Font;

// proxy .glyphs to .children
// TODO: handle unicode updates
Object.defineProperty(
	Font.prototype,
	'glyphs',
	Object.getOwnPropertyDescriptor( paper.Item.prototype, 'children' )
);

// TODO: proper proxying of ...Glyph[s] methods to ...Child[ren] methods
// see Glyph.js
Font.prototype.addGlyph = function( glyph ) {
	this.addChild( glyph );
	this.glyphMap[glyph.name] = glyph;

	if ( glyph.ot.unicode === undefined ) {
		return glyph;
	}

	// build the default cmap
	// if multiple glyphs share the same unicode, use the glyph where unicode
	// and name are equal
	if ( !this.charMap[glyph.ot.unicode] ||
			( glyph.name.length === 1 &&
				glyph.name.charCodeAt(0) === glyph.ot.unicode ) ) {

		this.charMap[glyph.ot.unicode] = glyph;
	}

	// build the alternates map
	if ( !this.altMap[glyph.ot.unicode] ) {
		this.altMap[glyph.ot.unicode] = [];
	}
	this.altMap[glyph.ot.unicode].push( glyph );

	// invalidate glyph subset cache
	// TODO: switch to immutable.js to avoid this maddness
	this._lastSubset = undefined;

	return glyph;
};

Font.prototype.addGlyphs = function( glyphs ) {
	return glyphs.forEach(function( glyph ) {
		this.addGlyph(glyph);

	}, this);
};

Object.defineProperty( Font.prototype, 'subset', {
	get: function() {
		if ( !this._subset ) {
			this._subset = this.normalizeSubset( false );
		}
		return this._subset;
	},
	set: function( set ) {
		this._subset = this.normalizeSubset( set );
	}
});

Font.prototype.normalizeSubset = function( _set ) {
	var set;

	// two cases where _set isn't an array
	// false set = all glyphs in the charMap
	if ( _set === false ) {
		set = Object.keys( this.charMap ).map(function( unicode ) {
			return this.charMap[unicode];
		}.bind(this));

	// convert string to array of chars
	} else if ( typeof _set === 'string' ) {
		set = _set.split('').map(function(e) {
			return e.charCodeAt(0);
		});

	} else {
		set = _set;
	}

	// convert array of number to array of glyphs
	if ( Array.isArray( set ) && typeof set[0] === 'number' ) {
		set = set.map(function( unicode ) {
			return this.charMap[ unicode ];
		}.bind(this));
	}

	// always include .undef
	if ( set.indexOf( this.glyphMap['.notdef'] ) === -1 ) {
		set.unshift( this.glyphMap['.notdef'] );
	}

	// when encountering diacritics, include their base-glyph in the subset
	set.forEach(function( glyph ) {
		if ( glyph && glyph.base !== undefined ) {
			var base = this.charMap[ glyph.base ];
			if ( set.indexOf( base ) === -1 ) {
				set.unshift( base );
			}
		}
	}, this);

	// remove undefined glyphs, dedupe the set and move diacritics at the end
	return set.filter(function(e, i, arr) {
		return e && arr.lastIndexOf(e) === i;
	});
};

Font.prototype.getGlyphSubset = function( _set ) {
	return _set !== undefined ? this.normalizeSubset( _set ) : this.subset;
};

Font.prototype.setAlternateFor = function( unicode, glyphName ) {
	this.charMap[ unicode ] = this.glyphMap[ glyphName ];
};

Font.prototype.interpolate = function( font0, font1, coef, set ) {
	this.getGlyphSubset( set ).map(function( glyph ) {
		glyph.interpolate(
			font0.glyphMap[glyph.name],
			font1.glyphMap[glyph.name],
			coef
		);
	});

	// TODO: evaluate if taking subsetting into account makes kerning
	// interpolation faster or slower.
	if ( this.ot.kerningPairs ) {
		for ( var i in this.ot.kerningPairs ) {
			this.ot.kerningPairs[i] =
				font0.ot.kerningPairs[i] +
				( font1.ot.kerningPairs[i] - font0.ot.kerningPairs[i] ) * coef;
		}
	}

	this.ot.ascender =
		font0.ot.ascender + ( font1.ot.ascender - font0.ot.ascender ) * coef;
	this.ot.descender =
		font0.ot.descender + ( font1.ot.descender - font0.ot.descender ) * coef;

	return this;
};

Font.prototype.updateSVGData = function( set ) {
	this.getGlyphSubset( set ).map(function( glyph ) {
		return glyph.updateSVGData();
	});

	return this;
};

Font.prototype.updateOTCommands = function( set, shouldMerge ) {
	return this.updateOT({
		set: set,
		shouldUpdateCommands: true,
		shouldMerge: shouldMerge
	});
};

Font.prototype.updateOT = function( args ) {
	if ( args && args.shouldUpdateCommands ) {
		// the following is required so that the globalMatrix of glyphs
		// is taken into account on each update. I assume this is done in the
		// main thread when calling view.update();
		this._project._updateVersion++;
	}

	this.ot.glyphs.glyphs = (
		this.getGlyphSubset( args && args.set ).reduce(function(o, glyph, i) {
			if ( args && args.shouldUpdateCommands ) {
				o[i] = args.shouldMerge ?
					glyph.combineOTCommands( null ) :
					glyph.updateOTCommands( null );
			} else {
				o[i] = glyph.ot;
			}

			return o;
		}, {})
	);
	this.ot.glyphs.length = Object.keys(this.ot.glyphs.glyphs).length;
	return this;
};

Font.prototype.toArrayBuffer = function() {
	// rewrite the postScriptName to remove invalid characters
	// TODO: this should be fixed in opentype.js
	this.ot.names.postScriptName.en = (
		this.ot.names.postScriptName.en.replace(/[^A-z]/g, '_')
	);

	return this.ot.toArrayBuffer();
}

Font.prototype.importOT = function( otFont ) {
	this.ot = otFont;

	for ( var i = 0; i < otFont.glyphs.length; ++i ) {
		var otGlyph = otFont.glyphs.get(i);
		var glyph = new Glyph({
				name: otGlyph.name,
				unicode: otGlyph.unicode
			});

		this.addGlyph( glyph );
		glyph.importOT( otGlyph );
	}

	return this;
};

if ( typeof window === 'object' && window.document ) {

	var _URL = window.URL || window.webkitURL;
	Font.prototype.addToFonts = document.fonts ?
		// CSS font loading, lightning fast
		function( buffer, enFamilyName ) {
			if ( !enFamilyName ) {
				enFamilyName = this.ot.getEnglishName('fontFamily');
			}

			if ( this.fontMap[ enFamilyName ] ) {
				document.fonts.delete( this.fontMap[ enFamilyName ] );
			}

			var fontface = this.fontMap[ enFamilyName ] = (
				new window.FontFace(
					enFamilyName,
					buffer || this.toArrayBuffer()
				)
			);

			if ( fontface.status === 'error' ) {
				throw new Error('Fontface is invalid and cannot be displayed');
			}

			document.fonts.add( fontface );

			return this;
		} :
		function( buffer, enFamilyName ) {
			if ( !enFamilyName ) {
				enFamilyName = this.ot.getEnglishName('fontFamily');
			}

			var url = _URL.createObjectURL(
					new Blob(
						[ new DataView( buffer || this.toArrayBuffer() ) ],
						{ type: 'font/opentype' }
					)
				);

			if ( this.fontObjectURL ) {
				_URL.revokeObjectURL( this.fontObjectURL );
				this.styleSheet.deleteRule(0);
			}

			this.styleSheet.insertRule(
				'@font-face { font-family: "' + enFamilyName + '";' +
				'src: url(' + url + '); }',
				0
			);
			this.fontObjectURL = url;

			return this;
		};

	var a = document.createElement('a');

	var triggerDownload = function( font, arrayBuffer, filename ) {
		var reader = new FileReader();
		var enFamilyName = filename || font.ot.getEnglishName('fontFamily');

		reader.onloadend = function() {
			a.download = enFamilyName + '.otf';
			a.href = reader.result;
			a.dispatchEvent(new MouseEvent('click'));

			setTimeout(function() {
				a.href = '#';
				_URL.revokeObjectURL( reader.result );
			}, 100);
		};

		reader.readAsDataURL(new Blob(
			[ new DataView( arrayBuffer || font.toArrayBuffer() ) ],
			{ type: 'font/opentype' }
		));
	};

	Font.prototype.download = function( arrayBuffer, merged, name, user ) {
		// TODO: replace that with client-side font merging
		fetch('http://localhost:3000/' +
			name.family + '/' +
			name.style + '/' +
			user +
			(name.template ? '/' + name.template : '') +
			(merged ? '/overlap' : ''), {
				method: 'POST',
				headers: { 'Content-Type': 'application/otf' },
				body: arrayBuffer
		})
		.then(function( response ) {
			return response.arrayBuffer();
		})
		.then(function( bufferToDownload ) {
			if( merged ) {
				triggerDownload( this, bufferToDownload );
			} else {
				triggerDownload(
					this, arrayBuffer, name && ( name.family + ' ' + name.style ) );
			}
		}.bind(this));

		return this;
	};

}

module.exports = Font;
<commit_msg>modified Font.js<commit_after>var opentype = require('opentype.js'),
	paper = require('paper'),
	Glyph = require('./Glyph.js'),
	assign = require('es6-object-assign').assign;

function Font( args ) {
	paper.Group.prototype.constructor.apply( this );

	args = assign({
		familyName: 'Default familyName',
		styleName: 'Regular',
		ascender: 1,
		descender: -1,
		unitsPerEm: 1024
	}, args);

	this.fontinfo = this.ot = new opentype.Font( args );

	this.glyphMap = {};
	this.charMap = {};
	this.altMap = {};
	this._subset = false;
	this.fontMap = {};

	this.addGlyph(new Glyph({
		name: '.notdef',
		unicode: 0,
		advanceWidth: 650
	}));

	if ( args && args.glyphs ) {
		this.addGlyphs( args.glyphs );
	}

	if ( typeof window === 'object' && window.document && !document.fonts ) {
		document.head.appendChild(
			this.styleElement = document.createElement('style')
		);
		// let's find the corresponding CSSStyleSheet
		// (would be much easier with Array#find)
		this.styleSheet = document.styleSheets[
			[].map.call(document.styleSheets, function(ss) {
				return ss.ownerNode;
			}).indexOf(this.styleElement)
		];
	}
}

Font.prototype = Object.create(paper.Group.prototype);
Font.prototype.constructor = Font;

// proxy .glyphs to .children
// TODO: handle unicode updates
Object.defineProperty(
	Font.prototype,
	'glyphs',
	Object.getOwnPropertyDescriptor( paper.Item.prototype, 'children' )
);

// TODO: proper proxying of ...Glyph[s] methods to ...Child[ren] methods
// see Glyph.js
Font.prototype.addGlyph = function( glyph ) {
	this.addChild( glyph );
	this.glyphMap[glyph.name] = glyph;

	if ( glyph.ot.unicode === undefined ) {
		return glyph;
	}

	// build the default cmap
	// if multiple glyphs share the same unicode, use the glyph where unicode
	// and name are equal
	if ( !this.charMap[glyph.ot.unicode] ||
			( glyph.name.length === 1 &&
				glyph.name.charCodeAt(0) === glyph.ot.unicode ) ) {

		this.charMap[glyph.ot.unicode] = glyph;
	}

	// build the alternates map
	if ( !this.altMap[glyph.ot.unicode] ) {
		this.altMap[glyph.ot.unicode] = [];
	}
	this.altMap[glyph.ot.unicode].push( glyph );

	// invalidate glyph subset cache
	// TODO: switch to immutable.js to avoid this maddness
	this._lastSubset = undefined;

	return glyph;
};

Font.prototype.addGlyphs = function( glyphs ) {
	return glyphs.forEach(function( glyph ) {
		this.addGlyph(glyph);

	}, this);
};

Object.defineProperty( Font.prototype, 'subset', {
	get: function() {
		if ( !this._subset ) {
			this._subset = this.normalizeSubset( false );
		}
		return this._subset;
	},
	set: function( set ) {
		this._subset = this.normalizeSubset( set );
	}
});

Font.prototype.normalizeSubset = function( _set ) {
	var set;

	// two cases where _set isn't an array
	// false set = all glyphs in the charMap
	if ( _set === false ) {
		set = Object.keys( this.charMap ).map(function( unicode ) {
			return this.charMap[unicode];
		}.bind(this));

	// convert string to array of chars
	} else if ( typeof _set === 'string' ) {
		set = _set.split('').map(function(e) {
			return e.charCodeAt(0);
		});

	} else {
		set = _set;
	}

	// convert array of number to array of glyphs
	if ( Array.isArray( set ) && typeof set[0] === 'number' ) {
		set = set.map(function( unicode ) {
			return this.charMap[ unicode ];
		}.bind(this));
	}

	// always include .undef
	if ( set.indexOf( this.glyphMap['.notdef'] ) === -1 ) {
		set.unshift( this.glyphMap['.notdef'] );
	}

	// when encountering diacritics, include their base-glyph in the subset
	set.forEach(function( glyph ) {
		if ( glyph && glyph.base !== undefined ) {
			var base = this.charMap[ glyph.base ];
			if ( set.indexOf( base ) === -1 ) {
				set.unshift( base );
			}
		}
	}, this);

	// remove undefined glyphs, dedupe the set and move diacritics at the end
	return set.filter(function(e, i, arr) {
		return e && arr.lastIndexOf(e) === i;
	});
};

Font.prototype.getGlyphSubset = function( _set ) {
	return _set !== undefined ? this.normalizeSubset( _set ) : this.subset;
};

Font.prototype.setAlternateFor = function( unicode, glyphName ) {
	this.charMap[ unicode ] = this.glyphMap[ glyphName ];
};

Font.prototype.interpolate = function( font0, font1, coef, set ) {
	this.getGlyphSubset( set ).map(function( glyph ) {
		glyph.interpolate(
			font0.glyphMap[glyph.name],
			font1.glyphMap[glyph.name],
			coef
		);
	});

	// TODO: evaluate if taking subsetting into account makes kerning
	// interpolation faster or slower.
	if ( this.ot.kerningPairs ) {
		for ( var i in this.ot.kerningPairs ) {
			this.ot.kerningPairs[i] =
				font0.ot.kerningPairs[i] +
				( font1.ot.kerningPairs[i] - font0.ot.kerningPairs[i] ) * coef;
		}
	}

	this.ot.ascender =
		font0.ot.ascender + ( font1.ot.ascender - font0.ot.ascender ) * coef;
	this.ot.descender =
		font0.ot.descender + ( font1.ot.descender - font0.ot.descender ) * coef;

	return this;
};

Font.prototype.updateSVGData = function( set ) {
	this.getGlyphSubset( set ).map(function( glyph ) {
		return glyph.updateSVGData();
	});

	return this;
};

Font.prototype.updateOTCommands = function( set, shouldMerge ) {
	return this.updateOT({
		set: set,
		shouldUpdateCommands: true,
		shouldMerge: shouldMerge
	});
};

Font.prototype.updateOT = function( args ) {
	if ( args && args.shouldUpdateCommands ) {
		// the following is required so that the globalMatrix of glyphs
		// is taken into account on each update. I assume this is done in the
		// main thread when calling view.update();
		this._project._updateVersion++;
	}

	this.ot.glyphs.glyphs = (
		this.getGlyphSubset( args && args.set ).reduce(function(o, glyph, i) {
			if ( args && args.shouldUpdateCommands ) {
				o[i] = args.shouldMerge ?
					glyph.combineOTCommands( null ) :
					glyph.updateOTCommands( null );
			} else {
				o[i] = glyph.ot;
			}

			return o;
		}, {})
	);
	this.ot.glyphs.length = Object.keys(this.ot.glyphs.glyphs).length;
	return this;
};

Font.prototype.toArrayBuffer = function() {
	// rewrite the postScriptName to remove invalid characters
	// TODO: this should be fixed in opentype.js
	this.ot.names.postScriptName.en = (
		this.ot.names.postScriptName.en.replace(/[^A-z]/g, '_')
	);

	return this.ot.toArrayBuffer();
}

Font.prototype.importOT = function( otFont ) {
	this.ot = otFont;

	for ( var i = 0; i < otFont.glyphs.length; ++i ) {
		var otGlyph = otFont.glyphs.get(i);
		var glyph = new Glyph({
				name: otGlyph.name,
				unicode: otGlyph.unicode
			});

		this.addGlyph( glyph );
		glyph.importOT( otGlyph );
	}

	return this;
};

if ( typeof window === 'object' && window.document ) {

	var _URL = window.URL || window.webkitURL;
	Font.prototype.addToFonts = document.fonts ?
		// CSS font loading, lightning fast
		function( buffer, enFamilyName ) {
			if ( !enFamilyName ) {
				enFamilyName = this.ot.getEnglishName('fontFamily');
			}

			if ( this.fontMap[ enFamilyName ] ) {
				document.fonts.delete( this.fontMap[ enFamilyName ] );
			}

			var fontface = this.fontMap[ enFamilyName ] = (
				new window.FontFace(
					enFamilyName,
					buffer || this.toArrayBuffer()
				)
			);

			if ( fontface.status === 'error' ) {
				throw new Error('Fontface is invalid and cannot be displayed');
			}

			document.fonts.add( fontface );

			return this;
		} :
		function( buffer, enFamilyName ) {
			if ( !enFamilyName ) {
				enFamilyName = this.ot.getEnglishName('fontFamily');
			}

			var url = _URL.createObjectURL(
					new Blob(
						[ new DataView( buffer || this.toArrayBuffer() ) ],
						{ type: 'font/opentype' }
					)
				);

			if ( this.fontObjectURL ) {
				_URL.revokeObjectURL( this.fontObjectURL );
				this.styleSheet.deleteRule(0);
			}

			this.styleSheet.insertRule(
				'@font-face { font-family: "' + enFamilyName + '";' +
				'src: url(' + url + '); }',
				0
			);
			this.fontObjectURL = url;

			return this;
		};

	var a = document.createElement('a');

	var triggerDownload = function( font, arrayBuffer, filename ) {
		var reader = new FileReader();
		var enFamilyName = filename || font.ot.getEnglishName('fontFamily');

		reader.onloadend = function() {
			a.download = enFamilyName + '.otf';
			a.href = reader.result;
			a.dispatchEvent(new MouseEvent('click'));

			setTimeout(function() {
				a.href = '#';
				_URL.revokeObjectURL( reader.result );
			}, 100);
		};

		reader.readAsDataURL(new Blob(
			[ new DataView( arrayBuffer || font.toArrayBuffer() ) ],
			{ type: 'font/opentype' }
		));
	};

	Font.prototype.download = function( arrayBuffer, merged, name, user ) {
		// TODO: replace that with client-side font merging
		fetch('http://localhost:3000/' +
			name.family + '/' +
			name.style + '/' +
			user +
			(name.template ? '/' + name.template : '') +
			(merged ? '/overlap' : ''), {
				method: 'POST',
				headers: { 'Content-Type': 'application/otf' },
				body: arrayBuffer
		})
		.then(function( response ) {
			return response.arrayBuffer();
		})
		.then(function( bufferToDownload ) {
			if ( merged ) {
				triggerDownload( this, bufferToDownload );
			} else {
				triggerDownload(
					this,
					arrayBuffer,
					name && ( name.family + ' ' + name.style ) );
			}
		}.bind(this));

		return this;
	};

}

module.exports = Font;
<|endoftext|>


<commit_before>var log;
var socket;

function main() {
	newLine();
	log = new Julien.log();
	socket = io.connect();
	socket.emit("clientType", "host");
}

function removeLine(ypos) {
	var dLine = document.getElementById("line");
	var lines = dLine.getElementsByTagName("p");
	var dCode = document.getElementById("code");
	var lCode = dCode.getElementsByTagName("p");
	if (ypos >= 0 && ypos < lines.length) {
		dLine.removeChild(lines[ypos]);
		dCode.removeChild(lCode[ypos]);
		updateLine();
	}
}

function newLine(ypos) {
	var dLine = document.getElementById("line");
	var lines = dLine.getElementsByTagName("p");

	if (ypos === undefined) {
		ypos = lines.length;
	}

	var pLine = document.createElement("p");
	pLine.textContent = lines.length + 1;
	dLine.appendChild(pLine);

	var dCode = document.getElementById("code");
	var lCode = dCode.getElementsByTagName("p");
	var pCode = document.createElement("p");
	pCode.setAttribute("contenteditable", "true");
	pCode.addEventListener("focus", function(e) {
		activate(document.getElementById("code").getElementsByTagName("p").toArray().indexOf(e.target));
	});
	pCode.addEventListener("blur", function() {
		activate(-1);
	});
	pCode.addEventListener("keydown", keyPressed);

	if (ypos < lCode.length) {
		dCode.insertBefore(pCode, lCode[ypos]);
	} else {
		dCode.appendChild(pCode);
	}
	updateLine();
	resetWidth();
	return ypos;
}

function activate(ypos) {
	var lCode = document.getElementById("code").getElementsByTagName("p");
	var lines = document.getElementById("line").getElementsByTagName("p");
	for (var i = 0; i < lines.length; i++) {
		if (i === ypos) {
			lCode[i].className = "active";
			lines[i].className = "active";
			lCode[i].focus();
		} else if (lCode[i].className === "active" || lines[i].className === "active") {
			lCode[i].removeAttribute("class");
			lines[i].removeAttribute("class");
		}
	}
	return lCode[ypos];
}

function resetWidth() {
	document.getElementById("code").style.width = "calc(100% - " + document.getElementById("line").offsetWidth + "px - 10px)";
}

function updateLine() {
		for (var i = 0, lines = document.getElementById("line").getElementsByTagName("p"); i < lines.length; i++) {
			lines[i].innerHTML = (i+1).toString().fill(" ", lines[lines.length - 1].textContent.length).replaceAll(" ", " ");
		}
}

function keyPressed(e) {
	var lines = document.getElementById("code").getElementsByTagName("p")
	var ypos = lines.toArray().indexOf(e.target);
	var xpos = getSelection().anchorOffset;
	if (e.keyCode === 13 || e.keyCode === 10) { // new line
		activate(newLine(ypos + 1));
		lines[ypos+1].textContent = lines[ypos].textContent.slice(xpos);
		lines[ypos].textContent = lines[ypos].textContent.slice(-xpos);
		e.stopPropagation();
		e.preventDefault();
		socket.emit("write", ypos, xpos, "\n")
	} else if (e.keyCode === 8 || e.keyCode === 127) { // backspace
		if (e.target.textContent.length) socket.emit("erase", ypos, e.keyCode === 8 ? xpos - 1 : xpos, 1);
		else if (lines.length > 1){
			socket.emit("eraseLine", ypos);
			e.target.parentNode.getElementsByTagName("p")[ypos-1].focus();
			document.getElementById("code").removeChild(e.target);
			document.getElementById("line").removeChild(document.getElementById("line").getElementsByTagName("p")[ypos]);
		}
	} else if (e.keyCode === 9) { // tabulation
		socket.emit("write", ypos, xpos, "\t")
		e.stopPropagation();
		e.preventDefault();
	} else { // any other key
		socket.emit("write", ypos, xpos, e.key);
		console.log(e.code + " : " + e.key);
	}
	socket.emit("cursor", ypos, xpos+1);
}
<commit_msg>Ajout de la gestion des flèches directionnel, ajout de commentaires, modification de la fonction d'activation pour positionner le curseur en plus d'activer la ligne, restructuration du code, correction d'une erreur d'indentation<commit_after>var socket;

function main() {
	newLine();
	socket = io.connect();
	socket.emit("clientType", "host");
}

// Crée une nouvelle ligne de code
function newLine(ypos) {
	var dLine = document.getElementById("line");
	var lines = dLine.getElementsByTagName("p");

	if (ypos === undefined) ypos = lines.length; // Si la ligne n'a pas été donnée, on ajoute la nouvelle ligne à la fin

	// Ajoute une ligne de code avec la gestion événementielle et les attributs
	var dCode = document.getElementById("code");
	var lCode = dCode.getElementsByTagName("p");
	var pCode = document.createElement("p");
	pCode.setAttribute("contenteditable", "true");
	pCode.addEventListener("focus", function(e) {
		if (e.isTrusted) activate(document.getElementById("code").getElementsByTagName("p").toArray().indexOf(e.target));
	});
	pCode.addEventListener("blur", function(e) {
		if (e.isTrusted) activate(null, null);
	});
	pCode.addEventListener("keypress", keyPressed);

	// Positionne la ligne de code
	if (ypos < lCode.length) {
		dCode.insertBefore(pCode, lCode[ypos]);
	} else {
		dCode.appendChild(pCode);
	}

	dLine.appendChild(document.createElement("p"));
	updateLine();
	resetWidth();
	return ypos;
}

// Supprime une ligne de code donnée
function removeLine(ypos) {
	var dLine = document.getElementById("line");
	var lines = dLine.getElementsByTagName("p");
	var dCode = document.getElementById("code");
	var lCode = dCode.getElementsByTagName("p");
	if (ypos >= 0 && ypos < lines.length) {
		dLine.removeChild(lines[ypos]);
		dCode.removeChild(lCode[ypos]);
		updateLine(); // Met à jour les numéro de ligne et leur taille
		resetWidth(); // Met à jour la taille de la zone code
	}
}

// Active la ligne donnée et place le curseur à la position donnée
function activate(ypos, xpos) {
	var lCode = document.getElementById("code").getElementsByTagName("p");
	var lines = document.getElementById("line").getElementsByTagName("p");
	for (var i = 0; i < lines.length; i++) {
		if (i === ypos) {
			//Positionne le curseur
			if(xpos) {
				var sel = window.getSelection();
				var range = document.createRange();
				range.setStart(lCode[i], xpos);
				sel.removeAllRanges();
				sel.addRange(range);
			}
			// Active la ligne
			lCode[i].className = "active";
			lines[i].className = "active";
			lCode[i].dispatchEvent(new Event("focus", {"bubbles":true}));

		} else if (lCode[i].className === "active" || lines[i].className === "active") {
			// Désactive la ligne
			lCode[i].removeAttribute("class");
			lines[i].removeAttribute("class");
		}
	}
	return lCode[ypos];
}

// Recalcule la longueure de la zone code en fonction de la zone ligne pour que ligne + code ~= 100%
function resetWidth() {
	document.getElementById("code").style.width = "calc(100% - " + document.getElementById("line").offsetWidth + "px - 10px)";
}

// Met à jour le numéro des lignes
function updateLine() {
	for (var i = 0, lines = document.getElementById("line").getElementsByTagName("p"); i < lines.length; i++) {
		lines[i].innerHTML = (i+1).toString().fill(" ", lines[lines.length - 1].textContent.length).replaceAll(" ", " ");
	}
}

// Gestion de la touche qui vient d'être tapée dans la zone de texte.
function keyPressed(e) {
	var lines = document.getElementById("code").getElementsByTagName("p")
	var ypos = lines.toArray().indexOf(e.target);
	var xpos = getSelection().anchorOffset;
	// console.log("ypos: " + ypos + ", xpos: " + xpos + ", char: " + e.key + " (" + e.code + ")");
	if (e.key === "Enter") {
		activate(newLine(ypos + 1), 1);
		lines[ypos+1].textContent = lines[ypos].textContent.slice(xpos);
		lines[ypos].textContent = lines[ypos].textContent.slice(0, xpos);
		e.preventDefault();
		socket.emit("write", ypos, xpos, "\n")
	} else if (e.code === "Backspace" || e.code === "Delete") {
		if (e.target.textContent.length) socket.emit("erase", ypos, e.keyCode === 8 ? xpos - 1 : xpos, 1);
		else if (lines.length > 1){
			socket.emit("eraseLine", ypos);
			activate(ypos-1, lines[ypos-1].textContent.length);
			document.getElementById("code").removeChild(e.target);
			document.getElementById("line").removeChild(document.getElementById("line").getElementsByTagName("p")[ypos]);
		}
	} else if (e.code === "Tab") {
		socket.emit("write", ypos, xpos, "\t")
		e.preventDefault();
	} else if (e.code.slice(0,5) == "Arrow") {
		switch (e.code.slice(5)) {
			case "Left":
				if(xpos === 0 && ypos > 0) {
					e.preventDefault;
					activate(ypos-1, lines[ypos-1].textContent.length);
					socket.emit("cursor", ypos-1, lines[ypos-1].textContent.length);
				} else if (xpos > 0) {
					socket.emit("cursor", ypos, xpos-1)
				}
				break;
			case "Right":
				if(xpos === lines[ypos].textContent.length && ypos < lines.length - 1) {
					e.preventDefault;
					activate(ypos+1, 0);
					socket.emit("cursor", ypos+1, 0);
				} else if (xpos < lines[ypos].textContent.length) {
					socket.emit("cursor", ypos, xpos+1)
				}
				break;
			case "Up":
				if (ypos > 0) {
					socket.emit("cursor", ypos-1, xpos);
					activate(ypos-1, xpos <= lines[ypos-1].textContent.length ? xpos : lines[ypos-1].textContent.length);
				}
				break;
			case "Down":
				if (ypos < lines.length - 1) {
					activate(ypos+1, xpos <= lines[ypos+1].textContent.length ? xpos : lines[ypos+1].textContent.length);
					socket.emit("cursor", ypos+1, xpos);
				}
				break;
		}
	} else { // any other key
		socket.emit("write", ypos, xpos, e.key);
		socket.emit("cursor", ypos, xpos+1);
	}
}
<|endoftext|>


<commit_before>;(function ($, window, document, undefined) {

  var pluginName = "gray",
      defaults = {
        propertyName: "value"
      };

  // The actual plugin constructor
  function Plugin ( element, options ) {
    this.element = element;
    this.settings = $.extend( {}, defaults, options );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  Plugin.prototype = {
    init: function () {
      // TODO: better feature detection
      if (isIE10 || isIE11) {
        this.switchImage();
      }
    },
    isIE10: function() {
      return Function('/*@cc_on return document.documentMode===10.0@*/')();
    },
    isIE11: function() {
      return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
    },
    switchImage: function () {
      var width,
          height,
          url,
          template,
          element = $(this.element);

      width  = element.width();
      height = element.height();
      url    = this.element.src;

      // TODO: use templating here
      template = $(
        '<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 '+width+' '+height+'" width="'+width+'" height="'+height+'">' +
          '<defs>' +
            '<filter id="gray">' +
              '<feComposite in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />' +
              '<feColorMatrix type="saturate" values="0" />' +
            '</filter>' +
          '</defs>' +
          '<image filter="url("#gray")" x="0" y="0" width="'+width+'" height="'+height+'" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="'+url+'" />' +
        '</svg>');

      element.replaceWith(template);
    }
  };

  $.fn[ pluginName ] = function ( options ) {
    this.each(function() {
      if ( !$.data( this, "plugin_" + pluginName ) ) {
        $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
      }
    });
    return this;
  };

})( jQuery, window, document );<commit_msg>javascript error<commit_after>;(function ($, window, document, undefined) {

  var pluginName = "gray",
      defaults = {
        propertyName: "value"
      };

  // The actual plugin constructor
  function Plugin ( element, options ) {
    this.element = element;
    this.settings = $.extend( {}, defaults, options );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  Plugin.prototype = {
    init: function () {
      // TODO: better feature detection
      if (this.isIE10 || this.isIE11) {
        this.switchImage();
      }
    },
    isIE10: function() {
      return Function('/*@cc_on return document.documentMode===10.0@*/')();
    },
    isIE11: function() {
      return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
    },
    switchImage: function () {
      var width,
          height,
          url,
          template,
          element = $(this.element);

      width  = element.width();
      height = element.height();
      url    = this.element.src;

      // TODO: use templating here
      template = $(
        '<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 '+width+' '+height+'" width="'+width+'" height="'+height+'">' +
          '<defs>' +
            '<filter id="gray">' +
              '<feComposite in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />' +
              '<feColorMatrix type="saturate" values="0" />' +
            '</filter>' +
          '</defs>' +
          '<image filter="url("#gray")" x="0" y="0" width="'+width+'" height="'+height+'" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="'+url+'" />' +
        '</svg>');

      element.replaceWith(template);
    }
  };

  $.fn[ pluginName ] = function ( options ) {
    this.each(function() {
      if ( !$.data( this, "plugin_" + pluginName ) ) {
        $.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
      }
    });
    return this;
  };

})( jQuery, window, document );<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import {Form} from 'formsy-react';
import classNames from 'classnames';

class FormEx extends Form {
  static defaultProps = {
    prefixCls: 'ant-form'
  };

  static propTypes = {
    prefixCls: React.PropTypes.string,
    inline: PropTypes.boolean,
    horizontal: PropTypes.boolean
  };

  constructor({prefixCls, inline, horizontal, className, ...props}, context) {
    const cn = classNames({
      [`${prefixCls}-horizontal`]: horizontal,
      [`${prefixCls}-inline`]: inline,
      [className]: !!className
    });
    super({...props, className: cn}, context);
  }

  render() {
    return super.render();
  }
}

export default FormEx;
<commit_msg>fix form ii<commit_after>import React, {Component, PropTypes} from 'react';
import {Form} from 'formsy-react';
import classNames from 'classnames';

class FormEx extends Form {
  static defaultProps = {
    ...Form.defaultProps,
    prefixCls: 'ant-form'
  };

  static propTypes = {
    prefixCls: React.PropTypes.string,
    inline: PropTypes.boolean,
    horizontal: PropTypes.boolean
  };

  render() {
    const form = super.render();
    const {prefixCls, inline, horizontal, className, ...props} = form.props;
    const cn = classNames({
      [`${prefixCls}-horizontal`]: horizontal,
      [`${prefixCls}-inline`]: inline,
      [className]: !!className
    });

    return React.cloneElement(form, {...props, className: cn});
  }
}

export default FormEx;
<|endoftext|>


<commit_before>/*global require: false, module: false, console: false */
'use strict';
var _ = require('underscore');

// merge, dropping undefined props
//var m = (...objs) => _.pick(_.extend.apply(null, [{}, ...objs]), (v, k) => v !== undefined);

function cases([tag, ...data], c) {
	return c[tag](...data);
}

function nullval() {
	return 'null';
}

function boolean() {
	return 'boolean';
}

function string(toHTML, opts, sType) {
	return cases(sType, {
		'value': (value) => `<span class="nowrap">"${_.escape(value)}"</span>`,
		'pattern': (pat) => `<span class="nowrap">${_.escape(pat)}</span>`,
		undefined: () => 'string'
	});
}

function minb(v) {
    return _.isUndefined(v) ? '-∞' : v;
}

function maxb(v) {
    return _.isUndefined(v) ? '∞' : v;
}

function number(toHTML, opts, nType) {
	return cases(nType, {
		'value': (value) => `${value}`,
		'interval': ([min, max]) => `<span class="it">number [${minb(min)}, ${maxb(max)}]</span>`,
		undefined: () => 'number'
	});
}

function annotation(toHTML, schema) {
	// eslint is flagging role is as unused?? an eslint bug?
	var [type, {role}, ref] = schema; //eslint-disable-line no-unused-vars
	return type === 'annotation' ? `<span>${toHTML(ref)} <label class='role'>${_.escape(role)}</label></span>` : toHTML(schema);
}

function tuple(toHTML, opts, ...schs) {
	var r = _.partial(annotation, toHTML);
	return `<span class="align-top">[</span>${_.map(schs, r).join(', ')}]`;
}

function list(toHTML, opts, sch) {
	var r = _.partial(annotation, toHTML);
	return `<span class="align-top">[</span>${r(sch)}, ...]`;
}

function linkKey (id) {
	return `<a class="it" href="#${id}">${id}</a>`;
}

function stringKey(type) {
	return cases(type, {
		'value': (value) => value,
		'pattern': (pat) => pat,
		undefined: () => '/.*/'
	});
}

// The goal here is to vertically align the ':' which appears between keys and their
// values, while keeping the open brace left of all the keys. Do this by creating
// three inline blocks (open brace, keys, values), and setting nowrap on the container.

var table = (className, ...children) => `<table class='${className}'><tbody>${children.join('')}</tbody></table>`;
var row = (...children) => `<tr>${children.join('')}</tr>`;
var td = (className, children) => `<td class=${className}>${children}</td>`;
function objRow(toHTML, first, last, [, {title}, stringSchema], sch) {
    return row(
            td('obj-name', first ? '{' : ''),
            td('obj-keys', `${title ? linkKey(title) : _.escape(stringKey(stringSchema))} :`),
            td('obj-vals', toHTML(sch) + (last ? '}' : '')));
}

function object(toHTML, opts, ...props) {
    return table('obj', ..._.map(props, ([key, sch], i) =>
                objRow(toHTML, i === 0, i === props.length - 1, key, sch)));
}

function dict(toHTML, opts, [[, {title}, stringSchema], sch]) {
	return table('obj', row(
				td('obj-name', '{'),
				td('obj-keys', `${title ? linkKey(title) : _.escape(stringKey(stringSchema))} :`),
				td('obj-vals', `${toHTML(sch)}, ...}`)));
}

var or = (toHTML, opts, ...schs) => `<p class="inline-block">${_.map(schs, toHTML).join(' | ')}</p>`;

var partialAll = (o, ...args) => _.mapObject(o, f => _.partial(f, ...args));

function toHTML(sch, top = []) {
	var [, {title, description}] = sch,
		h = (title ? `<h3 id="${title}"}>${title}</h3>` : '') +
			(description ? `<p class='subtitle'>${description}</p>` : '');
	function render(s) {
		var [, {title}] = s;
		if (sch === s || top.indexOf(s) === -1) {
			return cases(s, partialAll({
				'string': string,
				'number': number,
				'tuple': tuple,
				'list': list,
				'object': object,
				'dict': dict,
				'or': or,
				'null': nullval,
				'boolean': boolean,
				'annotation': () => {throw new Error('annotation should only appear in collection types');}
			}, render));
		} else {
			if (!title) {
				console.warn('Missing title for top-level schema');
			}
			return title ? `<a href="#${title}"><em>${title}</em></a>` : '';
		}
	}
	return h + render(sch);
}

// How to handle padding with nested elements?
// Only put padding on top-level elements?
var css =
`\n`;

module.exports = {
    toHTML: toHTML,
    css: css
};
<commit_msg>Don't wrap alternatives.<commit_after>/*global require: false, module: false, console: false */
'use strict';
var _ = require('underscore');

// merge, dropping undefined props
//var m = (...objs) => _.pick(_.extend.apply(null, [{}, ...objs]), (v, k) => v !== undefined);

function cases([tag, ...data], c) {
	return c[tag](...data);
}

function nullval() {
	return 'null';
}

function boolean() {
	return 'boolean';
}

function string(toHTML, opts, sType) {
	return cases(sType, {
		'value': (value) => `<span class="nowrap">"${_.escape(value)}"</span>`,
		'pattern': (pat) => `<span class="nowrap">${_.escape(pat)}</span>`,
		undefined: () => 'string'
	});
}

function minb(v) {
    return _.isUndefined(v) ? '-∞' : v;
}

function maxb(v) {
    return _.isUndefined(v) ? '∞' : v;
}

function number(toHTML, opts, nType) {
	return cases(nType, {
		'value': (value) => `${value}`,
		'interval': ([min, max]) => `<span class="it">number [${minb(min)}, ${maxb(max)}]</span>`,
		undefined: () => 'number'
	});
}

function annotation(toHTML, schema) {
	// eslint is flagging role is as unused?? an eslint bug?
	var [type, {role}, ref] = schema; //eslint-disable-line no-unused-vars
	return type === 'annotation' ? `<span>${toHTML(ref)} <label class='role'>${_.escape(role)}</label></span>` : toHTML(schema);
}

function tuple(toHTML, opts, ...schs) {
	var r = _.partial(annotation, toHTML);
	return `<span class="align-top">[</span>${_.map(schs, r).join(', ')}]`;
}

function list(toHTML, opts, sch) {
	var r = _.partial(annotation, toHTML);
	return `<span class="align-top">[</span>${r(sch)}, ...]`;
}

function linkKey (id) {
	return `<a class="it" href="#${id}">${id}</a>`;
}

function stringKey(type) {
	return cases(type, {
		'value': (value) => value,
		'pattern': (pat) => pat,
		undefined: () => '/.*/'
	});
}

// The goal here is to vertically align the ':' which appears between keys and their
// values, while keeping the open brace left of all the keys. Do this by creating
// three inline blocks (open brace, keys, values), and setting nowrap on the container.

var table = (className, ...children) => `<table class='${className}'><tbody>${children.join('')}</tbody></table>`;
var row = (...children) => `<tr>${children.join('')}</tr>`;
var td = (className, children) => `<td class=${className}>${children}</td>`;
function objRow(toHTML, first, last, [, {title}, stringSchema], sch) {
    return row(
            td('obj-name', first ? '{' : ''),
            td('obj-keys', `${title ? linkKey(title) : _.escape(stringKey(stringSchema))} :`),
            td('obj-vals', toHTML(sch) + (last ? '}' : '')));
}

function object(toHTML, opts, ...props) {
    return table('obj', ..._.map(props, ([key, sch], i) =>
                objRow(toHTML, i === 0, i === props.length - 1, key, sch)));
}

function dict(toHTML, opts, [[, {title}, stringSchema], sch]) {
	return table('obj', row(
				td('obj-name', '{'),
				td('obj-keys', `${title ? linkKey(title) : _.escape(stringKey(stringSchema))} :`),
				td('obj-vals', `${toHTML(sch)}, ...}`)));
}

var span = className => el => `<span class="${className}">${el}</span>`;

var inlineSpan = span('inline-block');
var nowrapSpan = span('nowrap');

var or = (toHTML, opts, ...schs) =>
	`<p class="inline-block">${_.map(schs, s => inlineSpan(toHTML(s))).join(' | ')}</p>`;

var partialAll = (o, ...args) => _.mapObject(o, f => _.partial(f, ...args));

function toHTML(sch, top = []) {
	var [, {title, description}] = sch,
		h = (title ? `<h3 id="${title}"}>${title}</h3>` : '') +
			(description ? `<p class='subtitle'>${description}</p>` : '');
	function render(s) {
		var [, {title}] = s;
		if (sch === s || top.indexOf(s) === -1) {
			return cases(s, partialAll({
				'string': string,
				'number': number,
				'tuple': tuple,
				'list': list,
				'object': object,
				'dict': dict,
				'or': or,
				'null': nullval,
				'boolean': boolean,
				'annotation': () => {throw new Error('annotation should only appear in collection types');}
			}, render));
		} else {
			if (!title) {
				console.warn('Missing title for top-level schema');
			}
			return title ? `<a href="#${title}"><em>${title}</em></a>` : '';
		}
	}
	return h + render(sch);
}

// How to handle padding with nested elements?
// Only put padding on top-level elements?
var css =
`\n`;

module.exports = {
    toHTML: toHTML,
    css: css
};
<|endoftext|>


<commit_before>// This script contains the code necessary to load the modal with the README

//Render `data` and load it into the modal
function loadHTML(data) {
  var readmeHTML = marked(data); //Render README from markdown to HTML
  var modalContent = document.getElementById("modal-content");
  modalContent.innerHTML = readmeHTML;
}

//requestPage("README.md",loadHTML); //Read README.md

//Menu items
var menuMain = document.getElementById("menu-main");
var menuControls = document.getElementById("menu-controls");
var menuReadme = document.getElementById("menu-readme");

var selectedPage=menuMain;

function removeAnimClasses(elem) { //Remove all animation classes from elem
  var cn = elem.className;
  var ac = [" toLeft"," toRight"," fromLeft"," fromRight"]; //Animation classes
  for (var i=0;i<ac.length;i++) {
    while (cn.indexOf(ac[i])>=0) {
      cn = cn.replace(ac[i],"");
    }
  }
  elem.className=cn;
}

function animatePage(newPage) { //Move to `page`
  selectedPage.className += " toLeft";
  newPage.className += " fromRight";
  newPage.style.display = "block";

  setTimeout(function() {
    //Reset the scene
    removeAnimClasses(selectedPage);
    removeAnimClasses(newPage);
    selectedPage.style.display = "none";
    selectedPage = newPage;
  },600);

}

function animateReturn() { //Return to menu
  selectedPage.className += " toRight";
  menuMain.className += " fromLeft";
  menuMain.style.display = "block";

  setTimeout(function() {
    //Reset the scene
    removeAnimClasses(selectedPage);
    removeAnimClasses(menuMain);
    selectedPage.style.display = "none";
    selectedPage = menuMain;
  },600);
}

var button=document.getElementById("movetest");
button.onclick=function(){
  animatePage(menuControls);
}
var button2=document.getElementById("goHome");
button2.onclick=function(){
  animateReturn()
}
<commit_msg>Fix bug where both sliding views could become hidden if you were spam-clicking the buttons<commit_after>// This script contains the code necessary to load the modal with the README

//Render `data` and load it into the modal
function loadHTML(data) {
  var readmeHTML = marked(data); //Render README from markdown to HTML
  var modalContent = document.getElementById("modal-content");
  modalContent.innerHTML = readmeHTML;
}

//requestPage("README.md",loadHTML); //Read README.md

//Menu items
var menuMain = document.getElementById("menu-main");
var menuControls = document.getElementById("menu-controls");
var menuReadme = document.getElementById("menu-readme");

var selectedPage=menuMain;

function removeAnimClasses(elem) { //Remove all animation classes from elem
  var cn = elem.className;
  var ac = [" toLeft"," toRight"," fromLeft"," fromRight"]; //Animation classes
  for (var i=0;i<ac.length;i++) {
    while (cn.indexOf(ac[i])>=0) {
      cn = cn.replace(ac[i],"");
    }
  }
  elem.className=cn;
}

function animatePage(newPage) { //Move to `page`
  selectedPage.className += " toLeft";
  newPage.className += " fromRight";
  newPage.style.display = "block";

  setTimeout(function() {
    //Reset the scene
    removeAnimClasses(selectedPage);
    removeAnimClasses(newPage);
    selectedPage.style.display = "none";
    newPage.style.display = "block"; //In case of rapid button-pressing
    selectedPage = newPage;
  },600);

}

function animateReturn() { //Return to menu
  selectedPage.className += " toRight";
  menuMain.className += " fromLeft";
  menuMain.style.display = "block";

  setTimeout(function() {
    //Reset the scene
    removeAnimClasses(selectedPage);
    removeAnimClasses(menuMain);
    selectedPage.style.display = "none";
    menuMain.style.display = "block"; //In case of rapid button-pressing
    selectedPage = menuMain;
  },600);
}

var button=document.getElementById("movetest");
button.onclick=function(){
  animatePage(menuControls);
}
var button2=document.getElementById("goHome");
button2.onclick=function(){
  animateReturn()
}
<|endoftext|>


<commit_before>import { Template } from 'meteor/templating';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { careerGoalsDefineMethod } from '../../../api/career/CareerGoalCollection.methods';
import { Interests } from '../../../api/interest/InterestCollection.js';
import * as FormUtils from './form-fields/form-field-utilities.js';

// /** @module ui/components/admin/Add_Career_Goal_Widget */

const addSchema = new SimpleSchema({
  name: { type: String, optional: false },
  slug: { type: String, optional: false, custom: FormUtils.slugFieldValidator },
  description: { type: String, optional: false },
  interests: { type: [String], optional: false, minCount: 1 },
});

Template.Add_Career_Goal_Widget.onCreated(function onCreated() {
  FormUtils.setupFormWidget(this, addSchema);
});

Template.Add_Career_Goal_Widget.helpers({
  interests() {
    return Interests.find({}, { sort: { name: 1 } });
  },
});

Template.Add_Career_Goal_Widget.events({
  submit(event, instance) {
    event.preventDefault();
    const newData = FormUtils.getSchemaDataFromEvent(addSchema, event);
    instance.context.resetValidation();
    addSchema.clean(newData);
    instance.context.validate(newData);
    if (instance.context.isValid()) {
      // CareerGoals.define(newData);
      careerGoalsDefineMethod.call(newData, (error, result) => {
        if (error) {
          console.log('Error defining CareerGoal: ', error);
          FormUtils.indicateError(instance);
        }
        if (result) {
          FormUtils.indicateSuccess(instance, event);
        }
      });
    } else {
      FormUtils.indicateError(instance);
    }
  },
});
<commit_msg>Checkpoint<commit_after>import { Template } from 'meteor/templating';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { careerGoalsDefineMethod } from '../../../api/career/CareerGoalCollection.methods';
import { Interests } from '../../../api/interest/InterestCollection.js';
import * as FormUtils from './form-fields/form-field-utilities.js';

// /** @module ui/components/admin/Add_Career_Goal_Widget */

const addSchema = new SimpleSchema({
  name: { type: String, optional: false },
  slug: { type: String, optional: false, custom: FormUtils.slugFieldValidator },
  description: { type: String, optional: false },
  interests: { type: [String], optional: false, minCount: 1 },
});

Template.Add_Career_Goal_Widget.onCreated(function onCreated() {
  FormUtils.setupFormWidget(this, addSchema);
});

Template.Add_Career_Goal_Widget.helpers({
  interests() {
    return Interests.find({}, { sort: { name: 1 } });
  },
});

Template.Add_Career_Goal_Widget.events({
  submit(event, instance) {
    event.preventDefault();
    const newData = FormUtils.getSchemaDataFromEvent(addSchema, event);
    instance.context.resetValidation();
    addSchema.clean(newData);
    instance.context.validate(newData);
    if (instance.context.isValid()) {
      careerGoalsDefineMethod.call(newData, (error, result) => {
        if (error) {
          console.log('Error defining CareerGoal: ', error);
          FormUtils.indicateError(instance);
        }
        if (result) {
          FormUtils.indicateSuccess(instance, event);
        }
      });
    } else {
      FormUtils.indicateError(instance);
    }
  },
});
<|endoftext|>


<commit_before>import React from 'react';
import {
	View,
	Text,
	StyleSheet,
} from 'react-native';
import moment from 'moment';

import {
	COLOR_LGREY,
	COLOR_BLACK,
} from '../../styles/ColorConstants';

const SpecialEventsHeader = ({ timestamp }) => (
	<View
		style={styles.header}
	>
		<Text style={styles.headerText}>
			{moment(Number(timestamp)).format('MMM DD hh:mm')}
		</Text>
	</View>
);

const styles = StyleSheet.create({
	header: { justifyContent: 'flex-start', alignItems: 'center', width: 45, backgroundColor: COLOR_LGREY, borderBottomWidth: 1, borderColor: COLOR_LGREY },
	headerText: { textAlign: 'right', alignSelf: 'stretch', color: COLOR_BLACK, fontSize: 12, marginTop: 7 },
});

export default SpecialEventsHeader;
<commit_msg>Remove leading hour from session time<commit_after>import React from 'react';
import {
	View,
	Text,
	StyleSheet,
} from 'react-native';
import moment from 'moment';

import {
	COLOR_LGREY,
	COLOR_BLACK,
} from '../../styles/ColorConstants';

const SpecialEventsHeader = ({ timestamp }) => (
	<View
		style={styles.header}
	>
		<Text style={styles.headerText}>
			{moment(Number(timestamp)).format('MMM DD h:mm')}
		</Text>
	</View>
);

const styles = StyleSheet.create({
	header: { justifyContent: 'flex-start', alignItems: 'center', width: 45, backgroundColor: COLOR_LGREY, borderBottomWidth: 1, borderColor: COLOR_LGREY },
	headerText: { textAlign: 'right', alignSelf: 'stretch', color: COLOR_BLACK, fontSize: 12, marginTop: 7 },
});

export default SpecialEventsHeader;
<|endoftext|>


<commit_before>(function() {
  var input;
  var gameboard = window.GameBoard;
  var ui = window.UI;
  var Game = {
    currentPlayer: "X",
    board: gameboard,
    gamerules: window.GameRules,
    human: window.Human,

    choicePlayer: function() {
      var input = ui.askChoicePlayer();
      if (input === null || input === "") {
        return true;
      }
      else if(input == "X") {
        this.currentPlayer = "X";
      }
      else if(input == "O") {
        this.currentPlayer = "O";
      }
      else {
        ui.inputErrorMessage();
        this.choicePlayer();
      }
      return false;
    },

    play: function() {
      console.log("hi")
      var _this = this;
      if (_this.choicePlayer()) {
        return;
      }
      this.newGame();
      this.human.choiceSpot(_this.board, _this.currentPlayer);
      $("tr td").click(function() {
        _this.nextTurn();
      });
    },

    nextTurn: function() {
      if(this.gamerules.gameWin(this.board)) {
        ui.winMessage(this.winner());
        $("tr td").unbind();
        ui.toggleDisplayedButton(".btn-new", ".btn-restart");
        this.restartGame();
      }
      else if(this.gamerules.gameTie(this.board)) {
        ui.tieMessage();
        $("tr td").unbind();
        ui.toggleDisplayedButton(".btn-new", ".btn-restart");
        this.restartGame();
      }
    },

    winner: function() {
      return this.currentPlayer == "X" ? "Player1" : "Player 2";
    },

    startGame: function() {
      var _this = this;
      ui.hideButton(".btn-restart", ".btn-new");
      $(".btn-start").click(function() {
        _this.play();
      });
    },

    newGame: function() {
      var _this = this;
      ui.toggleDisplayedButton(".btn-start", ".btn-new");
      $(".btn-new").click(function() {
        _this.resetGame();
      });
    },

    restartGame: function() {
      var _this = this;
      $(".btn-restart").one("click", function() {
        ui.toggleDisplayedButton(".btn-restart", ".btn-new");
        _this.resetGame();
        _this.play();
      });
    },

    resetGame: function() {
      $("tr td").empty();
      this.board.resetBoard();
    }
  };
  window.Game = Game;
})();
<commit_msg>extra console.log delete<commit_after>(function() {
  var input;
  var gameboard = window.GameBoard;
  var ui = window.UI;
  var Game = {
    currentPlayer: "X",
    board: gameboard,
    gamerules: window.GameRules,
    human: window.Human,

    choicePlayer: function() {
      var input = ui.askChoicePlayer();
      if (input === null || input === "") {
        return true;
      }
      else if(input == "X") {
        this.currentPlayer = "X";
      }
      else if(input == "O") {
        this.currentPlayer = "O";
      }
      else {
        ui.inputErrorMessage();
        this.choicePlayer();
      }
      return false;
    },

    play: function() {
      var _this = this;
      if (_this.choicePlayer()) {
        return;
      }
      this.newGame();
      this.human.choiceSpot(_this.board, _this.currentPlayer);
      $("tr td").click(function() {
        _this.nextTurn();
      });
    },

    nextTurn: function() {
      if(this.gamerules.gameWin(this.board)) {
        ui.winMessage(this.winner());
        $("tr td").unbind();
        ui.toggleDisplayedButton(".btn-new", ".btn-restart");
        this.restartGame();
      }
      else if(this.gamerules.gameTie(this.board)) {
        ui.tieMessage();
        $("tr td").unbind();
        ui.toggleDisplayedButton(".btn-new", ".btn-restart");
        this.restartGame();
      }
    },

    winner: function() {
      return this.currentPlayer == "X" ? "Player1" : "Player 2";
    },

    startGame: function() {
      var _this = this;
      ui.hideButton(".btn-restart", ".btn-new");
      $(".btn-start").click(function() {
        _this.play();
      });
    },

    newGame: function() {
      var _this = this;
      ui.toggleDisplayedButton(".btn-start", ".btn-new");
      $(".btn-new").click(function() {
        _this.resetGame();
      });
    },

    restartGame: function() {
      var _this = this;
      $(".btn-restart").one("click", function() {
        ui.toggleDisplayedButton(".btn-restart", ".btn-new");
        _this.resetGame();
        _this.play();
      });
    },

    resetGame: function() {
      $("tr td").empty();
      this.board.resetBoard();
    }
  };
  window.Game = Game;
})();
<|endoftext|>


<commit_before>var I18n = function(options){
    for (var prop in options) {
        this[prop] = options[prop];
    };

    this.setLocale(this.locale);
};

I18n.localeCache = {};

I18n.prototype = {
    defaultLocale: "en",
    directory: __DIR__ + "/locales",
    extension: ".min.json",

    getLocale: function(){
        return this.locale;
    },

    setLocale: function(locale){
        if(!locale)
            locale = $("html").attr("lang");

        if(!locale)
            locale = this.defaultLocale;

        this.locale = locale;

        if(locale in I18n.localeCache) return;
        else this.getLocaleFileFromServer();
    },

    getLocaleFileFromServer: function(){
        localeFile = null;

        $.ajax({
            url: this.directory + "/" + this.locale + this.extension,
            async: false,
            success: function(data){
                localeFile = data;
            }
        });

        I18n.localeCache[this.locale] = localeFile;
    },

    __: function(){
        var msg = I18n.localeCache[this.locale][arguments[0]];

        if (arguments.length > 1)
            msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));

        return msg;
    },

    __n: function(singular, count){
        var msg = I18n.localeCache[this.locale][singular];

        count = parseInt(count, 10);
        if(count === 0)
            msg = msg.zero;
        else
            msg = count > 1 ? msg.other : msg.one;

        msg = vsprintf(msg, [count]);

        if (arguments.length > 2)
            msg = vsprintf(msg, Array.prototype.slice.call(arguments, 2));

        return msg;
    }
};
<commit_msg>project with id page<commit_after>var I18n = function(options){
    for (var prop in options) {
        this[prop] = options[prop];
    };

    this.setLocale(this.locale);
};

I18n.localeCache = {};

I18n.prototype = {
    defaultLocale: "en",
    directory: "//locales",
    extension: ".min.json",

    getLocale: function(){
        return this.locale;
    },

    setLocale: function(locale){
        if(!locale)
            locale = $("html").attr("lang");

        if(!locale)
            locale = this.defaultLocale;

        this.locale = locale;

        if(locale in I18n.localeCache) return;
        else this.getLocaleFileFromServer();
    },

    getLocaleFileFromServer: function(){
        localeFile = null;

        $.ajax({
            url: this.directory + "/" + this.locale + this.extension,
            async: false,
            success: function(data){
                localeFile = data;
            }
        });

        I18n.localeCache[this.locale] = localeFile;
    },

    __: function(){
        var msg = I18n.localeCache[this.locale][arguments[0]];

        if (arguments.length > 1)
            msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));

        return msg;
    },

    __n: function(singular, count){
        var msg = I18n.localeCache[this.locale][singular];

        count = parseInt(count, 10);
        if(count === 0)
            msg = msg.zero;
        else
            msg = count > 1 ? msg.other : msg.one;

        msg = vsprintf(msg, [count]);

        if (arguments.length > 2)
            msg = vsprintf(msg, Array.prototype.slice.call(arguments, 2));

        return msg;
    }
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    //tutti gli eventi ajax che evvengono in plist sono nel formato pilst.on(evento,[selettore],function(...){...});
    var plist = $("#postlist");
    var loading = N.getLangData().LOADING;
    var lang = null; /* globale dato che la uso anche altrove */
    var load = false; //gestisce i caricamenti ed evita sovrapposizioni. Dichiarata qui che è il foglio che viene incluso di default ovunque e per primo
    plist.html('
'+loading+'...
');

    var fixHeights = function() {
        plist.find(".nerdz_message").each (function() {
            var el = $(this).find('div:first');
            // TODO: switch from attr('data-parsed') to data('parsed')
            if ((el.height() >= 200 || el.find ('.gistLoad').length > 0) && !el.attr('data-parsed'))
            {
                el.data ('real-height', el.height()).addClass ("compressed");
                var n = el.next();
                n.prepend ('
>> ' + N.getLangData().EXPAND + ' <<
'); // Spaces master race.
            }
            el.attr('data-parsed','1');
        });
    };

    var onRemoveHiddenPost = function() {
        var me = $(this), target = me.data ("target"), lv = localStorage.getItem ("hid").split ("|"), serialized = "";
        $("#" + target).slideToggle (function() {
            $(this).find (".img_frame > img").each (function() {
                $(this).css ("margin-top", (117 - $(this).height()) / 2);
            });
        });
        me.parent().remove();
        for (var zxcvbn in lv)
            if (lv[zxcvbn] != target)
                serialized += lv[zxcvbn] + "|";
        if (serialized != "")
            localStorage.setItem ("hid", serialized.slice (0, -1));
        else
        {
            localStorage.removeItem ("hid");
            $("#hp-cnt").remove();
            $("#hp-title").remove();
        }
    };

    var hideHidden = function() {
        var hidden = localStorage.getItem ("hid");
        if (hidden != null)
        {
            var pids = hidden.split ("|").sort().reverse(), len = pids.length;
            while (len--)
            {
                var post = plist.find ("#" + pids[len]);
                if (post.length)
                {
                    post.hide();
                    var pLink = window[pids[len].replace (/post/, "lnk")] || "#";
                    pids[len] = $(document.createElement("li"))
                        .append ($(document.createElement("a")).attr ("href", pLink).text (decodeURIComponent (pLink.substr (1))))
                        .append ($(document.createElement("a")).data ("target", pids[len]).css ("float", "right").html ("X").click (onRemoveHiddenPost));
                }
                else
                    pids.splice (len, 1);
            }
            if (pids.length)
            {
                if (!$("#hp-cnt").length)
                {
                    // create the hidden posts box
                    $(document.createElement("div")).addClass ("title").click (function() {
                        $("#hp-cnt").slideToggle();
                    }).html (N.getStaticData().lang.HIDDEN_POSTS).attr ("id", "hp-title").appendTo ("#right_col");
                    $(document.createElement("div")).hide().addClass ("box").attr ("id", "hp-cnt")
                        .append ($(document.createElement ("ul")).html (pids)).appendTo ("#right_col");
                }
                else
                    $("#hp-cnt ul").html (pids);
            }
        }
        fixHeights();
    };

    plist.on('click',".spoiler",function(){
      if($(this).data("parsed")) return;
      $.each($(this).find("img"),function(){
        m = (117-$(this).height())/2;
        if (m>1)
          $(this).css("margin-top", m)
      })
      $(this).data("parsed","1");
    });

    plist.on('click','.more',function() {
        var me = $(this), par = me.parent(), jenk = par.prev();
        if (me.data ('busy') == 'godyes') return;
        me.data ('busy', 'godyes');
        // obtain the real height of the post and do some hardcore animations
        //jenk.removeClass ("compressed"); var realHeight = jenk.height();
        jenk.animate ({ maxHeight: jenk.data ('real-height') }, 500, function() {
            jenk.removeClass ("compressed").css ("max-height", "none");
            me.slideUp ('slow', function() {
                me.remove();
            });
        });
    });

    plist.on('click',".hide",function() {
        var pid = $(this).data('postid');
        var hidden = localStorage.getItem('hid');
        if(hidden == null) {
            localStorage.setItem('hid',pid);
        }
        else
        {
            hidden += "|"+pid;
            localStorage.setItem('hid',hidden);
        }
        //auto lock
        var lock = $("#post"+pid).find('img.imgunlocked');
        if(lock.length)
        {
            lock.eq(0).click();
        }
        $("#"+pid).slideUp (hideHidden);
    });

    $("#profilePostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").show();
        $("#nerdzlist").hide();
        $(".selectlang").css('color','');
        localStorage.removeItem("autolang");
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','profile');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#projectPostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").hide();
        $("#projlist").hide();
        $(".projlang").css('color','');
        load = false;
        N.html.project.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','project');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#nerdzselect").on('click',function() {
        $("#nerdzlist").toggle();
    });

    $("#projselect").on('click',function() {
        $("#projlist").toggle();
    });

    $(".selectlang").on('click',function() {
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        localStorage.setItem("autolang",lang);
        $(".selectlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
            $("#fast_nerdz").show();
            N.html.profile.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','profile');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            if(lang == '*') {
                $("#fast_nerdz").show();
            }
            else {
                $("#fast_nerdz").hide();
            }

            load = false;
            N.html.profile.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('mode','language');
                plist.data('type','profile');
                hideHidden();
                load = true;
            });
        }
    });

    $(".projlang").on('click',function() {
        $("#fast_nerdz").hide();
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        $(".projlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
                N.html.project.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            N.html.project.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','language');
                hideHidden();
                load = true;
            });
        }
    });

    $("#stdfrm").on('submit',function(e) {
        e.preventDefault();
        $("#pmessage").html(loading+'...');
        N.json.profile.newPost({message: $("#frmtxt").val(), to: 0 },function(data) {
            if(data.status == 'ok') {
                $("#frmtxt").val('');
                load = false;
                if(lang == '*') {
                    N.html.profile.getByLangHomePostList(0,lang,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','language');
                        hideHidden();
                        load = true;
                    });
                }
                else if(lang == 'usersifollow') {
                    N.html.profile.getFollowedHomePostList(0,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','followed');
                        hideHidden();
                        load = true;
                    });
                }
                else {
                    $("#profilePostList").click();
                }
            }

            $("#pmessage").html(data.message);

            setTimeout(function() {
                        $("#pmessage").html('');
                        },5000);
        });
    });

    //default profile posts
    if(localStorage.getItem("autolang"))
    {
        $("#nerdzselect").click();
        var el = $("#nerdzlist").find("ul").find("[data-lang='"+localStorage.getItem("autolang")+"']");
        el.click();
        el.css('color','#2370B6');
    }
    else
    {
        plist.data('location','home');
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            hideHidden();
            plist.data('type','profile');
            plist.data('mode','std');
            load = true;
        });
    }

    /* Autoload vecchi post allo scrolldown */
        //questo serve per search, che avendo l'azione iniziale nel file default.js, non condivide la variabile load. Uso sessionStorage per ovviare
    var sl = 'searchLoad'; /*search label */
    sessionStorage.setItem(sl,"0");
    var tmpDivId = "scrtxt";
    var manageScrollResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            load = true;
            sessionStorage.setItem(sl, "0"); // se sono entrato qui, sicuramente non cerco
        }
    };

    var manageScrollSearchResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            sessionStorage.setItem(sl, "1");
            load = false; // se sono entrato qui, sicuramente stavo cercando
        }
    };

    $(window).scroll(function() {
        if($(this).scrollTop()+200 >= ( $(document).height() - $(this).height() ))
        {
            var num = 10; //TODO: numero di posts, parametro?
            var hpid = plist.find("div[id^='post']").last().data('hpid');
            var mode = plist.data('mode');
            var type = plist.data('type');
            var append = '
'+loading+'...
';

            if((load || ("1" == sessionStorage.getItem(sl))) && !$("#"+tmpDivId).length)
            {
                plist.append(append);
            }

            if(load)
            {
                load = false;
                if(mode == 'std') {
                    N.html[type].getHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'followed') {
                    N.html[type].getFollowedHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'language') {
                    N.html[type].getByLangHomePostListBeforeHpid(num,lang,hpid, manageScrollResponse);
                }
            }
            //a true ci va in default.js, dopo il primo search
            if(sessionStorage.getItem(sl) == "1")
            {
                sessionStorage.setItem(sl, "0");
                if(type == 'project' && mode == 'search')
                {
                    N.html.search.globalProjectPostsBeforeHpid(num,$("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
                else if(type == 'profile' && mode == 'search')
                {
                    N.html.search.globalProfilePostsBeforeHpid(num, $("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
            }
        }
    });
});
<commit_msg>Update home.js<commit_after>$(document).ready(function() {
    //tutti gli eventi ajax che evvengono in plist sono nel formato pilst.on(evento,[selettore],function(...){...});
    var plist = $("#postlist");
    var loading = N.getLangData().LOADING;
    var lang = null; /* globale dato che la uso anche altrove */
    var load = false; //gestisce i caricamenti ed evita sovrapposizioni. Dichiarata qui che è il foglio che viene incluso di default ovunque e per primo
    plist.html('
'+loading+'...
');

    var fixHeights = function() {
        plist.find(".nerdz_message").each (function() {
            var el = $(this).find('div:first');
            // TODO: switch from attr('data-parsed') to data('parsed')
            if ((el.height() >= 200 || el.find ('.gistLoad').length > 0) && !el.attr('data-parsed'))
            {
                el.data ('real-height', el.height()).addClass ("compressed");
                var n = el.next();
                n.prepend ('
>> ' + N.getLangData().EXPAND + ' <<
'); // Spaces master race.
            }
            el.attr('data-parsed','1');
        });
    };

    var onRemoveHiddenPost = function() {
        var me = $(this), target = me.data ("target"), lv = localStorage.getItem ("hid").split ("|"), serialized = "";
        $("#" + target).slideToggle (function() {
            $(this).find (".img_frame > img").each (function() {
                $(this).css ("margin-top", (117 - $(this).height()) / 2);
            });
        });
        me.parent().remove();
        for (var zxcvbn in lv)
            if (lv[zxcvbn] != target)
                serialized += lv[zxcvbn] + "|";
        if (serialized != "")
            localStorage.setItem ("hid", serialized.slice (0, -1));
        else
        {
            localStorage.removeItem ("hid");
            $("#hp-cnt").remove();
            $("#hp-title").remove();
        }
    };

    var hideHidden = function() {
        var hidden = localStorage.getItem ("hid");
        if (hidden != null)
        {
            var pids = hidden.split ("|").sort().reverse(), len = pids.length;
            while (len--)
            {
                var post = plist.find ("#" + pids[len]);
                if (post.length)
                {
                    post.hide();
                    var pLink = window[pids[len].replace (/post/, "lnk")];
                    pids[len] = $(document.createElement("li"))
                        .append ($(document.createElement("a")).attr ("href", pLink).text (decodeURIComponent (pLink.substr (1))))
                        .append ($(document.createElement("a")).data ("target", pids[len]).css ("float", "right").html ("X").click (onRemoveHiddenPost));
                }
                else
                    pids.splice (len, 1);
            }
            if (pids.length)
            {
                if (!$("#hp-cnt").length)
                {
                    // create the hidden posts box
                    $(document.createElement("div")).addClass ("title").click (function() {
                        $("#hp-cnt").slideToggle();
                    }).html (N.getStaticData().lang.HIDDEN_POSTS).attr ("id", "hp-title").appendTo ("#right_col");
                    $(document.createElement("div")).hide().addClass ("box").attr ("id", "hp-cnt")
                        .append ($(document.createElement ("ul")).html (pids)).appendTo ("#right_col");
                }
                else
                    $("#hp-cnt ul").html (pids);
            }
        }
        fixHeights();
    };

    plist.on('click',".spoiler",function(){
      if($(this).data("parsed")) return;
      $.each($(this).find("img"),function(){
        m = (117-$(this).height())/2;
        if (m>1)
          $(this).css("margin-top", m)
      })
      $(this).data("parsed","1");
    });

    plist.on('click','.more',function() {
        var me = $(this), par = me.parent(), jenk = par.prev();
        if (me.data ('busy') == 'godyes') return;
        me.data ('busy', 'godyes');
        // obtain the real height of the post and do some hardcore animations
        //jenk.removeClass ("compressed"); var realHeight = jenk.height();
        jenk.animate ({ maxHeight: jenk.data ('real-height') }, 500, function() {
            jenk.removeClass ("compressed").css ("max-height", "none");
            me.slideUp ('slow', function() {
                me.remove();
            });
        });
    });

    plist.on('click',".hide",function() {
        var pid = $(this).data('postid');
        var hidden = localStorage.getItem('hid');
        if(hidden == null) {
            localStorage.setItem('hid',pid);
        }
        else
        {
            hidden += "|"+pid;
            localStorage.setItem('hid',hidden);
        }
        //auto lock
        var lock = $("#post"+pid).find('img.imgunlocked');
        if(lock.length)
        {
            lock.eq(0).click();
        }
        $("#"+pid).slideUp (hideHidden);
    });

    $("#profilePostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").show();
        $("#nerdzlist").hide();
        $(".selectlang").css('color','');
        localStorage.removeItem("autolang");
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','profile');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#projectPostList").on('click',function() {
        plist.html('
'+loading+'...
');
        $("#fast_nerdz").hide();
        $("#projlist").hide();
        $(".projlang").css('color','');
        load = false;
        N.html.project.getHomePostList(0,function(data) {
            plist.html(data);
            plist.data('type','project');
            plist.data('mode','std');
            hideHidden();
            load = true;
        });
    });

    $("#nerdzselect").on('click',function() {
        $("#nerdzlist").toggle();
    });

    $("#projselect").on('click',function() {
        $("#projlist").toggle();
    });

    $(".selectlang").on('click',function() {
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        localStorage.setItem("autolang",lang);
        $(".selectlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
            $("#fast_nerdz").show();
            N.html.profile.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','profile');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            if(lang == '*') {
                $("#fast_nerdz").show();
            }
            else {
                $("#fast_nerdz").hide();
            }

            load = false;
            N.html.profile.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('mode','language');
                plist.data('type','profile');
                hideHidden();
                load = true;
            });
        }
    });

    $(".projlang").on('click',function() {
        $("#fast_nerdz").hide();
        plist.html('
'+loading+'...
');
        lang = $(this).data('lang');
        $(".projlang").css('color','');
        $(this).css('color','#2370B6');
        load = false;
        if(lang == 'usersifollow')
        {
                N.html.project.getFollowedHomePostList(0,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','followed');
                hideHidden();
                load = true;
            });
        }
        else
        {
            N.html.project.getByLangHomePostList(0,lang,function(data) {
                plist.html(data);
                plist.data('type','project');
                plist.data('mode','language');
                hideHidden();
                load = true;
            });
        }
    });

    $("#stdfrm").on('submit',function(e) {
        e.preventDefault();
        $("#pmessage").html(loading+'...');
        N.json.profile.newPost({message: $("#frmtxt").val(), to: 0 },function(data) {
            if(data.status == 'ok') {
                $("#frmtxt").val('');
                load = false;
                if(lang == '*') {
                    N.html.profile.getByLangHomePostList(0,lang,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','language');
                        hideHidden();
                        load = true;
                    });
                }
                else if(lang == 'usersifollow') {
                    N.html.profile.getFollowedHomePostList(0,function(data) {
                        plist.html(data);
                        plist.data('type','profile');
                        plist.data('mode','followed');
                        hideHidden();
                        load = true;
                    });
                }
                else {
                    $("#profilePostList").click();
                }
            }

            $("#pmessage").html(data.message);

            setTimeout(function() {
                        $("#pmessage").html('');
                        },5000);
        });
    });

    //default profile posts
    if(localStorage.getItem("autolang"))
    {
        $("#nerdzselect").click();
        var el = $("#nerdzlist").find("ul").find("[data-lang='"+localStorage.getItem("autolang")+"']");
        el.click();
        el.css('color','#2370B6');
    }
    else
    {
        plist.data('location','home');
        load = false;
        N.html.profile.getHomePostList(0,function(data) {
            plist.html(data);
            hideHidden();
            plist.data('type','profile');
            plist.data('mode','std');
            load = true;
        });
    }

    /* Autoload vecchi post allo scrolldown */
        //questo serve per search, che avendo l'azione iniziale nel file default.js, non condivide la variabile load. Uso sessionStorage per ovviare
    var sl = 'searchLoad'; /*search label */
    sessionStorage.setItem(sl,"0");
    var tmpDivId = "scrtxt";
    var manageScrollResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            load = true;
            sessionStorage.setItem(sl, "0"); // se sono entrato qui, sicuramente non cerco
        }
    };

    var manageScrollSearchResponse = function(data) {
        $("#"+tmpDivId).remove();
        if(data.length > 0) {
            plist.append(data);
            hideHidden();
            sessionStorage.setItem(sl, "1");
            load = false; // se sono entrato qui, sicuramente stavo cercando
        }
    };

    $(window).scroll(function() {
        if($(this).scrollTop()+200 >= ( $(document).height() - $(this).height() ))
        {
            var num = 10; //TODO: numero di posts, parametro?
            var hpid = plist.find("div[id^='post']").last().data('hpid');
            var mode = plist.data('mode');
            var type = plist.data('type');
            var append = '
'+loading+'...
';

            if((load || ("1" == sessionStorage.getItem(sl))) && !$("#"+tmpDivId).length)
            {
                plist.append(append);
            }

            if(load)
            {
                load = false;
                if(mode == 'std') {
                    N.html[type].getHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'followed') {
                    N.html[type].getFollowedHomePostListBeforeHpid(num,hpid,manageScrollResponse);
                }
                else if(mode == 'language') {
                    N.html[type].getByLangHomePostListBeforeHpid(num,lang,hpid, manageScrollResponse);
                }
            }
            //a true ci va in default.js, dopo il primo search
            if(sessionStorage.getItem(sl) == "1")
            {
                sessionStorage.setItem(sl, "0");
                if(type == 'project' && mode == 'search')
                {
                    N.html.search.globalProjectPostsBeforeHpid(num,$("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
                else if(type == 'profile' && mode == 'search')
                {
                    N.html.search.globalProfilePostsBeforeHpid(num, $("#footersearch input[name=q]").val(), hpid, manageScrollSearchResponse);
                }
            }
        }
    });
});
<|endoftext|>