<commit_before>var shared = require('../public/js/shared.js')
var colors = require('colors')

var _sockets = null,
	_WIDTH = 15,
	_HEIGHT = 30,
	_start_width = 15,
	_start_height = 30,
	_minSpeed = 500,
	_maxSpeed = 50,
	_field,
	_player = [],
	_blockid = 0,
	_pid = 1,
	_clearedLines = 0,
	_gameloop,
	_timeout,
	x,
	i, y,
	_gameover = false

	keymap = {
		up: function (player) {
			player.rotation = (player.rotation + 1) % 4
		},
		down: function (player) {
			player.rotation--
			if (player.rotation === -1)
				player.rotation = 3
		},
		right: function (player) {
			player.position[0]++
		},
		left: function (player) {
			player.position[0]--
		},
		space: function (player) {
			while (!isColliding(player)){
				player.position[1]++
			}
			player.position[1]--
			placePiece(player)
		}
	},
	revert = {
		up: function (player) {
			player.rotation--
			if (player.rotation === -1)
				player.rotation = 3
		},
		down: function (player) {
			player.rotation = (player.rotation + 1) % 4
		},
		right: function (player) {
			player.position[0]--
		},
		left: function (player) {
			player.position[0]++
		},
		space: function (player) {

		}
	}

if (typeof module === "object" && module && typeof module.exports === "object"){

	exports.init = function (sockets) {
		_sockets = sockets
		_sockets.on('connection', newPlayer)
	}
}

function randomInt (low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

function sendBaseData() {
	_sockets.emit('base', {players: _player, field: _field, score:_clearedLines})
}

function gameover(){
	console.log('Game Over'.red.bold)
	stopGame()
	_sockets.emit('gameover', {players: _player, field: _field, score:_clearedLines})
}

function startGame(){
	clearTimeout(_gameloop)
	console.log('Starting the game'.green.underline)
	_clearedLines = 0
	_WITH = _start_width
	_HEIGHT = _start_height
	_field = shared.newMatrix(_start_width, _start_height)
	_gameover = false
	gameloop()
}

function stopGame(){
	console.log('Stopping the game'.red.underline)
	_gameover = true
	clearTimeout(_gameloop)
}

function gameloop() {
	movePiecesDown()
	sendBaseData()

	timeout = Math.floor((_minSpeed-_maxSpeed)*Math.pow(Math.E, -1/20*_clearedLines)+_maxSpeed)
	if (!_gameover){
		_gameloop = setTimeout(gameloop, timeout)
	}
	if (timeout !== _timeout){
		console.log(('Line cleared. New Speed: '+timeout+'ms').italic.yellow)
	}
	_timeout = timeout
}

function newPlayer(socket) {
	if (_player.length===0){
		startGame()
	} else {
		extendField()
	}
	pid = _pid++
	_player.push({
		pid: pid,
		name: 'rnd'
	})
	newPiece(_player[_player.length-1])
	socket.on('update', recvUpdate)
	socket.on('disconnect', recvDisconnect)
	socket['pid']=pid
	sendBaseData()
	console.log(('Player '+pid+' joined the game').cyan)
}

function newPiece(player) {
	player.position = [randomInt(0, _WIDTH-3), 0]
	player.rotation = 0
	player.type = randomInt(0, 8),
	player.id = _blockid++
	if (isColliding(player)){
		gameover()
	}
}

function recvUpdate(data) {
	if (_gameover){return}
	for (var i = 0; i < _player.length; i++) {
		if (_player[i].pid == this.pid){
			player = _player[i]
		}
	}
	keymap[data](player)
	if (isColliding(player)){
		revert[data](player)
	}
	sendBaseData()
}

function recvDisconnect(data) {
	console.log(('Player '+this.pid+' leaved the game').grey)
	indexToDelete = -1;
	for (var i = 0; i < _player.length; i++) {
		if (_player[i].pid === this.pid){
			indexToDelete = i
		}
	}
	_player.splice(indexToDelete, 1)
	if (_player.length === 0){
		stopGame()
	} else {
		reduceField()
		sendBaseData()
	}
}

function movePiecesDown() {
	for (i = 0; i < _player.length; i++) {
		_player[i].position[1]++
		if (isColliding(_player[i])){
			_player[i].position[1]--
			placePiece(_player[i])
		}
	}
}

function clearFinishedLines(){
	y = _HEIGHT-1
	while (y >= 0) {
		cleared = true
		for (x = 0; x <_WIDTH; x++) {
			if (!_field[x][y]){
				cleared = false
			}
		}
		if (cleared){
			_clearedLines++
			for (i = y-1; i >= 0; i--){
				for (x = 0; x <_WIDTH; x++) {
					_field[x][i+1] = _field[x][i]
				}
			}
		} else {
			y--
		}
	}
}

function placePiece(player){
	var x = player.position[0],
		y = player.position[1],
		matrix = shared.rotateMatrix(shared.types[player.type],player.rotation)

	for (var dy = 0; dy < matrix.length; dy++){
		for (var dx = 0; dx < matrix[0].length; dx++){
			if (matrix[dy][dx]){
				_field[dx+x][dy+y] = {type: player.type, id: player.id, owner: player.pid}
			}
		}
	}
	newPiece(player)
	clearFinishedLines();
}

function isColliding(player){
	var x = player.position[0],
		y = player.position[1],
		matrix = shared.rotateMatrix(shared.types[player.type],player.rotation)

	for (var dy = 0; dy < matrix.length; dy++){
		for (var dx = 0; dx < matrix[0].length; dx++){
			if (matrix[dy][dx]){
				if ( dx+x < 0 || dy+y < 0 || dx+x >= _WIDTH|| dy+y >= _HEIGHT || _field[dx+x][dy+y]){
					return true
				}
			}
		}
	}
	return false
}

function extendField(){
	nMatrix = shared.newMatrix(_WIDTH+1, _HEIGHT)
	for (var x = 0; x < _WIDTH; x++) {
		for (var y = 0; y < _HEIGHT; y++) {
			nMatrix[x][y] = _field[x][y]
		}
	}
	_field = nMatrix
	_WIDTH++
}

function reduceField(){

	nMatrix = shared.newMatrix(_WIDTH-1, _HEIGHT)
	for (var x = 0; x < _WIDTH-1; x++) {
		for (var y = 0; y < _HEIGHT; y++) {
			nMatrix[x][y] = _field[x][y]
		}
	}
	_WIDTH--
	_field = nMatrix

}
<commit_msg>individual score for players<commit_after>var shared = require('../public/js/shared.js')
var colors = require('colors')

var _sockets = null,
	_WIDTH = 15,
	_HEIGHT = 30,
	_start_width = 15,
	_start_height = 30,
	_minSpeed = 500,
	_maxSpeed = 50,
	_field,
	_player = [],
	_blockid = 0,
	_pid = 1,
	_clearedLines = 0,
	_gameloop,
	_timeout,
	x,
	i, y,
	_gameover = false

	keymap = {
		up: function (player) {
			player.rotation = (player.rotation + 1) % 4
		},
		down: function (player) {
			player.rotation--
			if (player.rotation === -1)
				player.rotation = 3
		},
		right: function (player) {
			player.position[0]++
		},
		left: function (player) {
			player.position[0]--
		},
		space: function (player) {
			while (!isColliding(player)){
				player.position[1]++
			}
			player.position[1]--
			placePiece(player)
		}
	},
	revert = {
		up: function (player) {
			player.rotation--
			if (player.rotation === -1)
				player.rotation = 3
		},
		down: function (player) {
			player.rotation = (player.rotation + 1) % 4
		},
		right: function (player) {
			player.position[0]--
		},
		left: function (player) {
			player.position[0]++
		},
		space: function (player) {

		}
	}

if (typeof module === "object" && module && typeof module.exports === "object"){

	exports.init = function (sockets) {
		_sockets = sockets
		_sockets.on('connection', newPlayer)
	}
}

function randomInt (low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

function sendBaseData() {
	_sockets.emit('base', {players: _player, field: _field, score:_clearedLines})
}

function gameover(){
	console.log('Game Over'.red.bold)
	stopGame()
	_sockets.emit('gameover', {players: _player, field: _field, score:_clearedLines})
}

function startGame(){
	clearTimeout(_gameloop)
	console.log('Starting the game'.green.underline)
	_clearedLines = 0
	_WITH = _start_width
	_HEIGHT = _start_height
	_field = shared.newMatrix(_start_width, _start_height)
	_gameover = false
	gameloop()
}

function stopGame(){
	console.log('Stopping the game'.red.underline)
	_gameover = true
	clearTimeout(_gameloop)
}

function gameloop() {
	movePiecesDown()
	sendBaseData()

	timeout = Math.floor((_minSpeed-_maxSpeed)*Math.pow(Math.E, -1/20*_clearedLines)+_maxSpeed)
	if (!_gameover){
		_gameloop = setTimeout(gameloop, timeout)
	}
	if (timeout !== _timeout){
		console.log(('Line cleared. New Speed: '+timeout+'ms').italic.yellow)
	}
	_timeout = timeout
}

function newPlayer(socket) {
	if (_player.length===0){
		startGame()
	} else {
		extendField()
	}
	pid = _pid++
	_player.push({
		pid: pid,
		name: 'rnd',
		score: 0
	})
	newPiece(_player[_player.length-1])
	socket.on('update', recvUpdate)
	socket.on('disconnect', recvDisconnect)
	socket['pid']=pid
	sendBaseData()
	console.log(('Player '+pid+' joined the game').cyan)
}

function newPiece(player) {
	player.position = [randomInt(0, _WIDTH-3), 0]
	player.rotation = 0
	player.type = randomInt(0, 8),
	player.id = _blockid++
	if (isColliding(player)){
		gameover()
	}
}

function recvUpdate(data) {
	if (_gameover){return}
	for (var i = 0; i < _player.length; i++) {
		if (_player[i].pid == this.pid){
			player = _player[i]
		}
	}
	keymap[data](player)
	if (isColliding(player)){
		revert[data](player)
	}
	sendBaseData()
}

function recvDisconnect(data) {
	console.log(('Player '+this.pid+' leaved the game').grey)
	indexToDelete = -1;
	for (var i = 0; i < _player.length; i++) {
		if (_player[i].pid === this.pid){
			indexToDelete = i
		}
	}
	_player.splice(indexToDelete, 1)
	if (_player.length === 0){
		stopGame()
	} else {
		reduceField()
		sendBaseData()
	}
}

function movePiecesDown() {
	for (i = 0; i < _player.length; i++) {
		_player[i].position[1]++
		if (isColliding(_player[i])){
			_player[i].position[1]--
			placePiece(_player[i])
		}
	}
}

function clearFinishedLines(player){
	y = _HEIGHT-1
	while (y >= 0) {
		cleared = true
		for (x = 0; x <_WIDTH; x++) {
			if (!_field[x][y]){
				cleared = false
			}
		}
		if (cleared){
			_clearedLines++
			player.score++
			for (i = y-1; i >= 0; i--){
				for (x = 0; x <_WIDTH; x++) {
					_field[x][i+1] = _field[x][i]
				}
			}
		} else {
			y--
		}
	}
}

function placePiece(player){
	var x = player.position[0],
		y = player.position[1],
		matrix = shared.rotateMatrix(shared.types[player.type],player.rotation)

	for (var dy = 0; dy < matrix.length; dy++){
		for (var dx = 0; dx < matrix[0].length; dx++){
			if (matrix[dy][dx]){
				_field[dx+x][dy+y] = {type: player.type, id: player.id, owner: player.pid}
			}
		}
	}
	newPiece(player)
	clearFinishedLines(player);
}

function isColliding(player){
	var x = player.position[0],
		y = player.position[1],
		matrix = shared.rotateMatrix(shared.types[player.type],player.rotation)

	for (var dy = 0; dy < matrix.length; dy++){
		for (var dx = 0; dx < matrix[0].length; dx++){
			if (matrix[dy][dx]){
				if ( dx+x < 0 || dy+y < 0 || dx+x >= _WIDTH|| dy+y >= _HEIGHT || _field[dx+x][dy+y]){
					return true
				}
			}
		}
	}
	return false
}

function extendField(){
	nMatrix = shared.newMatrix(_WIDTH+1, _HEIGHT)
	for (var x = 0; x < _WIDTH; x++) {
		for (var y = 0; y < _HEIGHT; y++) {
			nMatrix[x][y] = _field[x][y]
		}
	}
	_field = nMatrix
	_WIDTH++
}

function reduceField(){

	nMatrix = shared.newMatrix(_WIDTH-1, _HEIGHT)
	for (var x = 0; x < _WIDTH-1; x++) {
		for (var y = 0; y < _HEIGHT; y++) {
			nMatrix[x][y] = _field[x][y]
		}
	}
	_WIDTH--
	_field = nMatrix

}
<|endoftext|>


<commit_before>var particles = []
var arrows = []
var numberOfParticles = 0
var temp = 0
var wind = {
  angle: 0,
  speed: 0,
  vector: null
}

Number.prototype.map = function ( in_min , in_max , out_min , out_max ) {
    return ( this - in_min ) * ( out_max - out_min ) / ( in_max - in_min ) + out_min;
}

function calculateHSL(hsb){
    // determine the lightness in the range [0,100]
    var l = (2 - hsb.s / 100) * hsb.b / 2;
    // store the HSL components
    var hsl =
      {
        'h' : hsb.h,
        's' : hsb.s * hsb.b / (l < 50 ? l * 2 : 200 - l * 2),
        'l' : l
      };
    // correct a division-by-zero error
    if (isNaN(hsl.s)) hsl.s = 0;
    return hsl
}

function getHsb(temp){
    var hsb = {
        'h' : 0,
        's' : 80,
        'b' : 85
      };

    temp = temp > 32 ? 32 : temp < -10 ? -10 : temp

    hsb.h = 200 - temp.map(0, 40, 0, 250)

    return hsb
}

function drawBackground(hsb) {
    var hsl = calculateHSL(hsb)
    background(hsb.h, hsb.s, hsb.b)
    $('body').css('background', 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)') // css HSL
}

function boundCheck(position){
    if (position.x > width)  position.x = 0
    if (position.x < 0)      position.x = width
    if (position.y > height) position.y = 0
    if (position.y < 0)      position.y = height
}

function Particle () {
    this.position = createVector(random(width), random(height))
    this.size = random(8)
    this.opacity = random(1)

    this.draw = function(speed, i, mouseX, mouseY){

      mouse = createVector(mouseX, mouseY)
      normalizedPosition = this.position.copy()
      distance = mouse.dist(normalizedPosition)

      repulsion = createVector(normalizedPosition.x - mouse.x - sin(i), normalizedPosition.y - mouse.y - cos(i));
      repulsion.normalize()

      if (distance<30){
        this.position.add(repulsion)
      }
      else if (distance<60){
        repulsion.div(2)
        this.position.add(repulsion)
      }
      else if (distance<90){
        repulsion.div(3)
        this.position.add(repulsion)
      }
      else if (distance<120){
        repulsion.div(4)
        this.position.add(repulsion)
      }

      this.position.add(speed)

      // add some randomness
      this.position.x = this.position.x + cos(i)/10
      this.position.y = this.position.y + sin(i)/10
      this.size = this.size

      boundCheck(this.position)

      noStroke()
      fill(color(25, this.opacity))
      ellipse(this.position.x, this.position.y, this.size, this.size)
    }
}

function Arrow () {
    this.position = createVector(random(width), random(height))
    this.size = random(10)
    this.opacity = random(1)

    this.draw = function(speed, i, mouseX, mouseY){

      mouse = createVector(mouseX, mouseY)
      normalizedPosition = this.position.copy()
      distance = mouse.dist(normalizedPosition)

      repulsion = createVector(normalizedPosition.x - mouse.x - sin(i), normalizedPosition.y - mouse.y - cos(i))
      repulsion.normalize()

      if (distance<30){
        this.position.add(repulsion)
      }
      else if (distance<60){
        repulsion.div(2)
        this.position.add(repulsion)
      }
      else if (distance<90){
        repulsion.div(3)
        this.position.add(repulsion)
      }
      else if (distance<120){
        repulsion.div(4)
        this.position.add(repulsion)
      }

      this.position.add(speed)

      // add some randomness
      this.position.x = this.position.x + cos(i)/10
      this.position.y = this.position.y + sin(i)/10
      this.size = this.size

      boundCheck(this.position)

      stroke(color(255, this.opacity))
      strokeWeight(1)
      push()
      translate(this.position.x, this.position.y)
      rotate(wind.angle);
      line(0, 0, this.size*2 ,0)
      //arrow
      line(this.size*2, 0, this.size*1.4, -this.size/2)
      line(this.size*2, 0, this.size*1.4, this.size/2)
      pop();
    }
}

function setWeather(temperature, windSpeed, windDirection) {
  temp = floor(temperature)

  // convert to radians and account for meteorological degrees
  wind.angle = radians(windDirection + 90)
  wind.speed = Number(windSpeed)
  wind.vector = p5.Vector.fromAngle(wind.angle)
  // add wind magnitude
  wind.vector.mult(wind.speed)
}

function getData(){
  jQuery.ajax( {
    url: 'http://ip-api.com/json',
    type: 'GET',
    dataType: 'jsonp',
    cache: false,
    headers: { "Content-type": "application/json" },
    success: function(location) {
      jQuery.ajax( {
        url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + location.lat + '&lon=' + location.lon +  '&units=metric&APPID=4e6e342eef6a9a7f8ea3d5f3f95a7b84',
        type: 'GET',
        dataType: 'jsonp',
        cache: false,
        headers: { "Content-type": "application/json" },
        success: function(weather) {
          console.log(weather)
          setWeather(weather.main.temp, weather.wind.speed, weather.wind.deg)
        }
      });
  }
} );
}

function setup() {
    particles = []
    arrows = []
    temp = 0

    createCanvas($(window).width(), $(window).height());
    getData()

    numberOfParticles = floor(width/14)
    if(numberOfParticles>90){
      numberOfParticles = 90
    }

    for(i=0; i < numberOfParticles; i++){
      particle = new Particle()
      particles.push(particle)

      arrow = new Arrow()
      arrows.push(arrow)
    }
    colorMode(HSB, 360, 100, 100, 1)
}

function draw() {
  // if temperature was read
  if(temp && wind){
      hsb = getHsb(temp)
      drawBackground(hsb)

      // removed mobile for now
      for(i=0; i < numberOfParticles; i++){
          particles[i].draw(wind.vector, i, mouseX, mouseY)
          arrows[i].draw(wind.vector, i , mouseX, mouseY)
      }

      if(wind.speed < 2)
          $(".message").html("Barely windy")
      else if(2 <= wind.speed && wind.speed < 6)
          $(".message").html("A bit windy")
      else if(6 <= wind.speed && wind.speed < 9)
          $(".message").html("Quite windy")
      else if(9 < wind.speed && wind.speed < 12)
          $(".message").html("Really windy")
      else if(wind.speed >= 12)
          $(".message").html("Outright windy")
    }

    $('html, body').on('touchstart touchmove', function(e){
     //prevent native touch activity like scrolling
     e.preventDefault()
  	});
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight)

    particles = []
    arrows = []

    numberOfParticles = floor(width/14)
    if(numberOfParticles>90){
      numberOfParticles = 90
    }

    for(i=0; i<numberOfParticles; i++){
      particle = new Particle()
      particles.push(particle)

      arrow = new Arrow()
      arrows.push(arrow)
    }
}<commit_msg>fix issue with no wind direction<commit_after>var particles = []
var arrows = []
var numberOfParticles = 0
var temp = 0
var wind = {
  angle: 0,
  speed: 0,
  vector: null
}

Number.prototype.map = function ( in_min , in_max , out_min , out_max ) {
    return ( this - in_min ) * ( out_max - out_min ) / ( in_max - in_min ) + out_min;
}

function calculateHSL(hsb){
    // determine the lightness in the range [0,100]
    var l = (2 - hsb.s / 100) * hsb.b / 2;
    // store the HSL components
    var hsl =
      {
        'h' : hsb.h,
        's' : hsb.s * hsb.b / (l < 50 ? l * 2 : 200 - l * 2),
        'l' : l
      };
    // correct a division-by-zero error
    if (isNaN(hsl.s)) hsl.s = 0;
    return hsl
}

function getHsb(temp){
    var hsb = {
        'h' : 0,
        's' : 80,
        'b' : 85
      };

    temp = temp > 32 ? 32 : temp < -10 ? -10 : temp

    hsb.h = 200 - temp.map(0, 40, 0, 250)

    return hsb
}

function drawBackground(hsb) {
    var hsl = calculateHSL(hsb)
    background(hsb.h, hsb.s, hsb.b)
    $('body').css('background', 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)') // css HSL
}

function boundCheck(position){
    if (position.x > width)  position.x = 0
    if (position.x < 0)      position.x = width
    if (position.y > height) position.y = 0
    if (position.y < 0)      position.y = height
}

function Particle () {
    this.position = createVector(random(width), random(height))
    this.size = random(8)
    this.opacity = random(1)

    this.draw = function(speed, i, mouseX, mouseY){

      mouse = createVector(mouseX, mouseY)
      normalizedPosition = this.position.copy()
      distance = mouse.dist(normalizedPosition)

      repulsion = createVector(normalizedPosition.x - mouse.x - sin(i), normalizedPosition.y - mouse.y - cos(i));
      repulsion.normalize()

      if (distance<30){
        this.position.add(repulsion)
      }
      else if (distance<60){
        repulsion.div(2)
        this.position.add(repulsion)
      }
      else if (distance<90){
        repulsion.div(3)
        this.position.add(repulsion)
      }
      else if (distance<120){
        repulsion.div(4)
        this.position.add(repulsion)
      }

      this.position.add(speed)

      // add some randomness
      this.position.x = this.position.x + cos(i)/10
      this.position.y = this.position.y + sin(i)/10
      this.size = this.size

      boundCheck(this.position)

      noStroke()
      fill(color(25, this.opacity))
      ellipse(this.position.x, this.position.y, this.size, this.size)
    }
}

function Arrow () {
    this.position = createVector(random(width), random(height))
    this.size = random(10)
    this.opacity = random(1)

    this.draw = function(speed, i, mouseX, mouseY){

      mouse = createVector(mouseX, mouseY)
      normalizedPosition = this.position.copy()
      distance = mouse.dist(normalizedPosition)

      repulsion = createVector(normalizedPosition.x - mouse.x - sin(i), normalizedPosition.y - mouse.y - cos(i))
      repulsion.normalize()

      if (distance<30){
        this.position.add(repulsion)
      }
      else if (distance<60){
        repulsion.div(2)
        this.position.add(repulsion)
      }
      else if (distance<90){
        repulsion.div(3)
        this.position.add(repulsion)
      }
      else if (distance<120){
        repulsion.div(4)
        this.position.add(repulsion)
      }

      this.position.add(speed)

      // add some randomness
      this.position.x = this.position.x + cos(i)/10
      this.position.y = this.position.y + sin(i)/10
      this.size = this.size

      boundCheck(this.position)

      stroke(color(255, this.opacity))
      strokeWeight(1)
      push()
      translate(this.position.x, this.position.y)
      rotate(wind.angle);
      line(0, 0, this.size*2 ,0)
      //arrow
      line(this.size*2, 0, this.size*1.4, -this.size/2)
      line(this.size*2, 0, this.size*1.4, this.size/2)
      pop();
    }
}

function setWeather(temperature, windSpeed, windDirection) {
  temp = floor(temperature)

  if (!windDirection){
    windDirection = -90
  }
  // convert to radians and account for meteorological degrees
  wind.angle = radians(windDirection + 90)
  wind.speed = Number(windSpeed)

  wind.vector = p5.Vector.fromAngle(wind.angle)
  // add wind magnitude
  wind.vector.mult(wind.speed/4)
}

function getData(){
  jQuery.ajax( {
    url: 'http://ip-api.com/json',
    type: 'GET',
    dataType: 'jsonp',
    cache: false,
    headers: { "Content-type": "application/json" },
    success: function(location) {
      jQuery.ajax( {
        url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + location.lat + '&lon=' + location.lon +  '&units=metric&APPID=4e6e342eef6a9a7f8ea3d5f3f95a7b84',
        type: 'GET',
        dataType: 'jsonp',
        cache: false,
        headers: { "Content-type": "application/json" },
        success: function(weather) {
          console.log(weather)
          setWeather(weather.main.temp, weather.wind.speed, weather.wind.deg)
        }
      });
  }
} );
}

function setup() {
    particles = []
    arrows = []
    temp = 0

    createCanvas($(window).width(), $(window).height());
    getData()

    numberOfParticles = floor(width/14)
    if(numberOfParticles>90){
      numberOfParticles = 90
    }

    for(i=0; i < numberOfParticles; i++){
      particle = new Particle()
      particles.push(particle)

      arrow = new Arrow()
      arrows.push(arrow)
    }
    colorMode(HSB, 360, 100, 100, 1)
}

function draw() {
  // if temperature was read
  if(temp && wind){
      hsb = getHsb(temp)
      drawBackground(hsb)

      // removed mobile for now
      for(i=0; i < numberOfParticles; i++){
          particles[i].draw(wind.vector, i, mouseX, mouseY)
          arrows[i].draw(wind.vector, i , mouseX, mouseY)
      }

      if(wind.speed < 2)
          $(".message").html("Barely windy")
      else if(2 <= wind.speed && wind.speed < 6)
          $(".message").html("A bit windy")
      else if(6 <= wind.speed && wind.speed < 9)
          $(".message").html("Quite windy")
      else if(9 < wind.speed && wind.speed < 12)
          $(".message").html("Really windy")
      else if(wind.speed >= 12)
          $(".message").html("Outright windy")
    }

    $('html, body').on('touchstart touchmove', function(e){
     //prevent native touch activity like scrolling
     e.preventDefault()
  	});
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight)

    particles = []
    arrows = []

    numberOfParticles = floor(width/14)
    if(numberOfParticles>90){
      numberOfParticles = 90
    }

    for(i=0; i<numberOfParticles; i++){
      particle = new Particle()
      particles.push(particle)

      arrow = new Arrow()
      arrows.push(arrow)
    }
}<|endoftext|>


<commit_before>/* global google */
import Ember from 'ember';
import {
  moduleForComponent,
  test
} from 'ember-qunit';

moduleForComponent('street-view', {
  // specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
});

test('it renders', function(assert) {
  assert.expect(2);

  // creates the component instance
  var component = this.subject();
  assert.equal(component._state, 'preRender');

  // renders the component to the page
  this.render();
  assert.equal(component._state, 'inDOM');
});

test('that lat and lng are assigned properly', function ( assert ) {

  let component = this.subject();
  component.set('lat', 15.45);
  component.set('lng', 17.43);
  this.render();

  Ember.run( function() {
    component.createStreetView();
    assert.equal(component.lat, 15.45);
    assert.equal(component.lng, 17.43);
  } );

});

test('that options are assigned properly to the map', function( assert ) {
  let component = this.subject();
  let lat = 12.34;
  let lng = 43.21;
  let height = "600px";
  let width = "400px";
  let options = {
    position: new google.maps.LatLng(lat, lng),
    pov: {
      heading: 165,
      pitch: 4
    },
    zoom: 6
  };
  this.$().css({width: width, height: height});
  let streetView = new google.maps.StreetViewPanorama(this.$().get(0), options);
  component.set('map', streetView);
  this.render();

  Ember.run(function() {
    let map = component.map;

    //position
    assert.equal(map.position.A, options.position.A);
    assert.equal(map.position.A, 12.34);
    assert.equal(map.position.F, options.position.F);
    assert.equal(map.position.F.toFixed(2), 43.21);

    //pov
    assert.equal(map.pov.heading, options.pov.heading);
    assert.equal(map.pov.heading, 165);
    assert.equal(map.pov.pitch, options.pov.pitch);
    assert.equal(map.pov.pitch, 4);

    //zoom
    assert.equal(map.zoom, options.zoom);
    assert.equal(map.zoom, 6);
  });
});<commit_msg>add and improve unit tests<commit_after>/* global google */
import Ember from 'ember';
import {
  moduleForComponent,
  test
} from 'ember-qunit';

function latRandomizer(){
  return (Math.random() * 181) - 90;
}

function lngRandomizer() {
  return (Math.random() * 281) -180;
}

moduleForComponent('street-view', {
  // specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
});

test('it renders', function(assert) {
  assert.expect(2);

  // creates the component instance
  var component = this.subject();
  assert.equal(component._state, 'preRender');

  // renders the component to the page
  this.render();
  assert.equal(component._state, 'inDOM');
});

test('that lat and lng are assigned properly', function ( assert ) {
  let lat = latRandomizer();
  let lng = lngRandomizer();

  let component = this.subject();
  component.set('lat', lat);
  component.set('lng', lng);
  this.render();

  Ember.run( function() {
    component.createStreetView();
    assert.equal(component.lat.toFixed(3), component.map.position.G.toFixed(3));
    assert.equal(component.lng.toFixed(3), component.map.position.K.toFixed(3));
  } );

});

test('that options are assigned properly to the map', function( assert ) {
  let component = this.subject();
  let height = Math.floor(Math.random() * 1000) + "px";
  let width = Math.floor(Math.random() * 1000) + "px";

  component.set('height', height);
  component.set('width', width);
  component.set('lat', latRandomizer());
  component.set('lng', lngRandomizer());
  component.set('pov', {
    heading: Math.floor(Math.random() * 200),
    pitch: Math.floor(Math.random() * 10)
  });
  component.set('zoom', Math.floor(Math.random() * 10));

  component.set('panControl', Boolean(Math.floor(Math.random() * 2)));
  if( component.panControl === true ) {
    component.set('panControlOptions', {
      position:google.maps.ControlPosition.RIGHT_TOP
    });
  }

  component.set('zoomControl', Boolean(Math.floor(Math.random() * 2)));
  if( component.zoomControl === true ) {
    component.set('zoomControlOptions', {
      style: google.maps.ZoomControlStyle.SMALL
    });

  }

  component.set('addressControl', Boolean(Math.floor(Math.random() * 2 )));
  if( component.addressControl === true) {
    component.set('addressControlOptions', {
      position: google.maps.ControlPosition.BOTTOM_CENTER
    });
  }

  component.set('linksControl', Boolean(Math.floor(Math.random() * 2 )));

  $().css({width: width, height: height});
  this.render();

  Ember.run(function() {
    let map = component.map;

    //position
    assert.equal(map.position.G.toFixed(3), component.lat.toFixed(3));
    assert.equal(map.position.K.toFixed(3), component.lng.toFixed(3));

    //pov
    assert.equal(map.pov.heading, component.pov.heading);
    assert.equal(map.pov.pitch, component.pov.pitch);

    //zoom
    assert.equal(map.zoom, component.zoom);

    // panControl
    assert.equal(map.panControl, component.panControl);
    assert.equal(map.panControlOptions, component.panControlOptions);

    // zoomControl
    assert.equal(map.zoomControl, component.zoomControl);
    assert.equal(map.zoomControlOptions, component.zoomControlOptions);

    // addressControl
    assert.equal(map.addressControl, component.addressControl);
    assert.equal(map.addressControlOptions, component.addressControlOptions);

    // linksControl
    assert.equal(map.linksControl, component.linksControl);
  });
});<|endoftext|>


<commit_before>import React from 'react';
import md5 from 'md5';

import _File from './_File';
import configs from './configs';
import { SourceEditor } from '../EditorPane/';

export default class SourceFile extends _File {

  static defaultProps = {
    name: '.SourceFile',
    text: '',
    json: null,
    component: SourceEditor,
    sign: null,
  };

  static defaultOptions = {
    isEntryPoint: false,
    isReadOnly: false,
    isTrashed: false,
    noBabel: false,
  }

  static visible = _File.visible.concat(
    'text',
    'isScript',
    'blob'
  );

  get text() {
    return this.props.text;
  }

  get isScript() {
    return this.is('javascript');
  }

  get blob() {
    const { type, text } = this;
    return new Blob([text], { type });
  }

  get json() {
    if (!this.is('json')) {
      return null;
    }
    if (!this._json) {
      const model = Array.from(configs.values())
        .find((config) => config.test.test(this.name));
      const defaultValue = model ? model.defaultValue : {};
      try {
        this._json = Object.assign({}, defaultValue, JSON.parse(this.text));
      } catch (e) {
        return {};
      }
    }
    return this._json;
  }

  _hash = null;
  get hash() {
    return this._hash = this._hash || md5(this.text);
  }

  set(change) {
    const seed = Object.assign(this.serialize(), change);

    return new this.constructor(seed);
  }

  compose() {
    const serialized = this.serialize();
    serialized.composed = this.text;
    serialized.credits = JSON.stringify(this.credits);

    return Promise.resolve(serialized);
  }

  /**
   * @param file File|Blob
   * @return Promise gives SourceFile
   */
  static load(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        resolve(
          new SourceFile({
            type: file.type,
            name: file.name || SourceFile.defaultProps.name,
            text: e.target.result,
          })
        );
      };
      reader.readAsText(file);
    });
  }

  static shot(text) {
    return new SourceFile({ type: 'text/javascript', name: '', text });
  }

}
<commit_msg>Add credit when changed<commit_after>import React from 'react';
import md5 from 'md5';

import _File from './_File';
import configs from './configs';
import { SourceEditor } from '../EditorPane/';

export default class SourceFile extends _File {

  static defaultProps = {
    name: '.SourceFile',
    text: '',
    json: null,
    component: SourceEditor,
    sign: null,
  };

  static defaultOptions = {
    isEntryPoint: false,
    isReadOnly: false,
    isTrashed: false,
    noBabel: false,
  }

  static visible = _File.visible.concat(
    'text',
    'isScript',
    'blob'
  );

  get text() {
    return this.props.text;
  }

  get isScript() {
    return this.is('javascript');
  }

  get blob() {
    const { type, text } = this;
    return new Blob([text], { type });
  }

  get json() {
    if (!this.is('json')) {
      return null;
    }
    if (!this._json) {
      const model = Array.from(configs.values())
        .find((config) => config.test.test(this.name));
      const defaultValue = model ? model.defaultValue : {};
      try {
        this._json = Object.assign({}, defaultValue, JSON.parse(this.text));
      } catch (e) {
        return {};
      }
    }
    return this._json;
  }

  _hash = null;
  get hash() {
    return this._hash = this._hash || md5(this.text);
  }

  set(change) {
    const seed = Object.assign(this.serialize(), change);

    return new this.constructor(seed);
  }

  compose() {
    const serialized = this.serialize();
    serialized.composed = this.text;
    if (this.sign && this.sign === this.credit) {
      const sign = Object.assign({}, this.sign, {
        timestamp: new Date().getTime(),
        hash: this.hash,
      });
      serialized.credits = JSON.stringify(
        this.credits.concat(sign)
      );
    } else {
      serialized.credits = JSON.stringify(this.credits);
    }

    return Promise.resolve(serialized);
  }

  /**
   * @param file File|Blob
   * @return Promise gives SourceFile
   */
  static load(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        resolve(
          new SourceFile({
            type: file.type,
            name: file.name || SourceFile.defaultProps.name,
            text: e.target.result,
          })
        );
      };
      reader.readAsText(file);
    });
  }

  static shot(text) {
    return new SourceFile({ type: 'text/javascript', name: '', text });
  }

}
<|endoftext|>


<commit_before>/**
 * Enables or disables a feature flag in E2E tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import { wpApiFetch } from './wp-api-fetch';

/**
 * Disables a feature flag during E2E tests.
 *
 * @since n.e.x.t
 *
 * @param {string} feature The feature flag to disable.
 * @return {Promise} Promise from `page.evaluate()` call.
 */
export async function disableFeature( feature ) {
	return await wpApiFetch( {
		path: 'google-site-kit/v1/e2e/feature/set-flag',
		method: 'post',
		data: { [ feature ]: false },
	} );
}

/**
 * Enables a feature flag during E2E tests.
 *
 * @since n.e.x.t
 *
 * @param {string} feature The feature flag to enable.
 * @return {Promise} Promise from `page.evaluate()` call.
 */
export async function enableFeature( feature ) {
	return await wpApiFetch( {
		path: 'google-site-kit/v1/e2e/feature/set-flag',
		method: 'post',
		data: { [ feature ]: true },
	} );
}
<commit_msg>Fix request body issues in enableFeature and disableFeature functions.<commit_after>/**
 * Enables or disables a feature flag in E2E tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import { wpApiFetch } from './wp-api-fetch';

/**
 * Disables a feature flag during E2E tests.
 *
 * @since n.e.x.t
 *
 * @param {string} feature The feature flag to disable.
 * @return {Promise} Promise from `page.evaluate()` call.
 */
export async function disableFeature( feature ) {
	return await wpApiFetch( {
		path: 'google-site-kit/v1/e2e/feature/set-flag',
		method: 'post',
		data: {
			feature_name: feature,
			feature_value: false,
		},
	} );
}

/**
 * Enables a feature flag during E2E tests.
 *
 * @since n.e.x.t
 *
 * @param {string} feature The feature flag to enable.
 * @return {Promise} Promise from `page.evaluate()` call.
 */
export async function enableFeature( feature ) {
	return await wpApiFetch( {
		path: 'google-site-kit/v1/e2e/feature/set-flag',
		method: 'post',
		data: {
			feature_name: feature,
			feature_value: true,
		},
	} );
}
<|endoftext|>


<commit_before>var namespace_info_table_DataTable, zk_cluster_info_table_DataTable, namespace_zkcluster_manager_table_DataTable;
var namespace_zkcluster_manager_operation = '【请务必同时只能一个人并且只使用一个浏览器来操作】  ' +
                                            '<button class="btn btn-success" id="batch-move-namespace">批量迁移</button>  ' +
                                            '<button class="btn btn-warning" id="init-namespace-zkcluster-mapping">初始化映射表</button>  ';
$(function() {

	$("#refresh_registry_center").on("click", function() {
		var $btn = $(this).button("loading");
		$.get("registry_center/refreshRegCenter", function(data) {
			if(data.success == true) {
				window.parent.location.reload(true);
			} else {
				showFailureDialogWithMsg("failure-dialog", data.message);
			}
		}).always(function() { $btn.button('reset'); });
	});

	$('[href="#namespace_info_tabpanel"]').on("click", function() {
		refreshNamespaceInfo();
    });
	$('[href="#zk_cluster_info_tabpanel"]').on("click", function() {
		refreshZkClusterInfo();
	});
	$('[href="#namespace_zkcluster_manager_tabpanel"]').on("click", function() {
		refreshNamespaceZkClusterMappingList();
    });
	if ($("#namespace_info_tabpanel").is(':visible')) {
		refreshNamespaceInfo();
	} else if ($("#zk_cluster_info_tabpanel").is(':visible')) {
		refreshZkClusterInfo();
	} else if ($("#namespace_zkcluster_manager_tabpanel").is(':visible')) {
		refreshNamespaceZkClusterMappingList();
	}

	$("#namespace_zkcluster_manager_table_select_all").on('click', function(event) {
	    if($(this).is(":checked")){
            $('.batchInput').prop('checked',true);// jquery1.9以后的版本，用attr有点问题，要用prop
        }else{
            $('.batchInput').prop('checked',false);
        }
    });

    $("#move-namespace-batch-dialog").on("shown.bs.modal", function (event) {
        $("#move-namespace-batch-dialog-confirm-btn").unbind('click').click(function() {
            var namespaces = $("#move-namespace-batch-dialog-namespace").html();
            var bootstrapKeyNew = "";
            if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
                bootstrapKeyNew = $("#move-namespace-batch-dialog-zkCluster").val();
            } else {
                bootstrapKeyNew = $("#move-namespace-batch-dialog-zkCluster-input").val();
            }
            var updateDBOnly = $("#move-namespace-batch-dialog-updateDBOnly").is(":checked");
            $("#confirm-yes-dialog-title").html('域名：
' + namespaces + '
目标集群：
' + bootstrapKeyNew + '
只更新映射表：
' + updateDBOnly + '
确认批量迁移，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    $("#move-namespace-batch-dialog").modal("hide");
                    $("#confirm-yes-dialog").modal("hide");
                    $("#move-namespace-batch-status-dialog-zkCluster").html(bootstrapKeyNew);
                    var split = namespaces.split(",");
                    if(split && split instanceof Array) {
                        var id = parseInt(Math.random() * 10000000);
                        $.post("registry_center/moveNamespaceBatch", {namespaces: namespaces, bootstrapKeyNew: bootstrapKeyNew, updateDBOnly: updateDBOnly, id: id}, function(data) {
                            if(data.success) {
                                var size = split.length;
                                $("#move-namespace-batch-status-dialog-data").html("成功：" + 0 + "
失败：" + 0 + "
忽略：" + 0 + "
未做：" + size + "
总共：" + size);
                                $("#move-namespace-batch-status-dialog-message").html("");
                                $("#move-namespace-batch-status-dialog-tips").css("display", "inline");
                                $("#move-namespace-batch-status-dialog-x").css("display", "none");
                                $("#move-namespace-batch-status-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-status-dialog").modal("show");
                                getMoveNamespaceBatchStatus(id);
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        alert("请选择要迁移的域");
                    }
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });
    });

    $("#move-namespace-batch-dialog-manual").on('click', function(event) {
        if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
            $("#move-namespace-batch-dialog-zkCluster").attr("style", "display:none");
            $("#move-namespace-batch-dialog-zkCluster-input").removeAttr("style");
            $("#move-namespace-batch-dialog-manual").attr("status", "manual");
            $("#move-namespace-batch-dialog-manual").html("在线的集群");
        } else {
            $("#move-namespace-batch-dialog-zkCluster").removeAttr("style");
            $("#move-namespace-batch-dialog-zkCluster-input").attr("style", "display:none");
            $("#move-namespace-batch-dialog-manual").attr("status", "auto");
            $("#move-namespace-batch-dialog-manual").html("手动输入");
        }
    });

    $("#confirm-yes-dialog").on("shown.bs.modal", function (event) {
        $("#giveMeYes").focus();
    });

    $("#move-namespace-batch-status-dialog-x").on("click", function() {
        $("#move-namespace-batch-status-dialog").modal("hide");
        var id = parseInt($("#move-namespace-batch-status-dialog-x").attr("id2"));
        if(!isNaN(id)) {
            $.post("registry_center/clearMoveNamespaceBatchStatus", {id: id}, function(data) {});
        }
        refreshNamespaceZkClusterMappingList();
    });

    refreshNamespaceInfo();
});

function refreshNamespaceInfo() {
    $loading.show();
	$.get("registry_center/getNamespaceInfo", {}, function(data) {
		if(namespace_info_table_DataTable) {
			namespace_info_table_DataTable.destroy();
		}
        $("#namespace_info_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var cluster = list[i];
            		var key = cluster.zkClusterKey;
            		var regCenterConfList = cluster.regCenterConfList;
            		if(regCenterConfList && regCenterConfList instanceof Array) {
            			for(var j=0; j < regCenterConfList.length; j++) {
	        				var regCenterConf = regCenterConfList[j];
			                var baseTd = "" + regCenterConf.namespace + "	"
			                    + regCenterConf.name + "	"
			                    + regCenterConf.version + "	"
			                    + key + "	";
			                $("#namespace_info_table tbody").append("
" + baseTd + "
");
            			}
            		}
	            }
	        }
	        namespace_info_table_DataTable = $("#namespace_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}

function refreshNamespaceZkClusterMappingList() {
    $loading.show();
	$.get("registry_center/getNamespaceZkclusterMappingList", {}, function(data) {
		if(namespace_zkcluster_manager_table_DataTable) {
			namespace_zkcluster_manager_table_DataTable.destroy();
		}
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);
        $("#namespace_zkcluster_manager_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var mapping = list[i];
                    var baseTd = "<input class='batchInput' type='checkbox' onclick='clickNamespace_zkcluster_manager_table_select_all(this);' namespace='" + mapping.namespace + "'/>	"
                        + "" + mapping.namespace + "	"
                        + mapping.zkClusterKey + "	";
                    $("#namespace_zkcluster_manager_table tbody").append("
" + baseTd + "
");
	            }
	        }
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
        namespace_zkcluster_manager_table_DataTable = $("#namespace_zkcluster_manager_table").DataTable({"oLanguage": language, "displayLength":100});
        $("#namespace_zkcluster_manager_table_filter label").before(namespace_zkcluster_manager_operation);

        $("#init-namespace-zkcluster-mapping").on("click", function() {
            $("#confirm-yes-dialog-title").html('确认初始化映射表，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    var $btn = $(this).button('loading');
                    $.post("registry_center/initNamespaceZkClusterMapping", {}, function(data) {
                        $("#confirm-yes-dialog").modal("hide");
                        if(data.success) {
                            showSuccessDialog();
                            refreshNamespaceZkClusterMappingList();
                        } else {
                            showFailureDialogWithMsg("failure-dialog", data.message);
                        }
                    }).always(function() {$btn.button('reset');});
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });

        $("#batch-move-namespace").on("click", function() {
            var namespaces = "";
            $(".batchInput").each(function() {
                if($(this).is(":checked")) {
                    if(namespaces == "") {
                        namespaces = $(this).attr("namespace") ;
                    } else {
                        namespaces = namespaces + "," + $(this).attr("namespace") ;
                    }
                }
            });
            if(namespaces == "") {
                showFailureDialogWithMsg("failure-dialog", "请选择要迁移的域");
            } else {
                $.get("registry_center/getZkClusterListWithOnline", {}, function(data) {
                    if(data.success) {
                        $("#move-namespace-batch-dialog-namespace").html(namespaces);
                        $.get("registry_center/getZkClusterListWithOnline", {}, function(data2) {
                            if(data2.success) {
                                var zkClusterListWithOnlineFromCfg = data2.obj;
                                var options = "";
                                if(zkClusterListWithOnlineFromCfg && zkClusterListWithOnlineFromCfg instanceof Array) {
                                    for(var i in zkClusterListWithOnlineFromCfg) {
                                        var zkClusterWithOnlineFromCfg = zkClusterListWithOnlineFromCfg[i];
                                        options += "<option value='"+ zkClusterWithOnlineFromCfg +"'>" + zkClusterWithOnlineFromCfg + "</option>";
                                    }
                                }
                                $("#move-namespace-batch-dialog-zkCluster").empty();
                                $("#move-namespace-batch-dialog-zkCluster").append(options);
                                $("#move-namespace-batch-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-dialog").modal("show");
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        showFailureDialogWithMsg("failure-dialog", data.message);
                    }
                });
            }
        });
    }).always(function() { $loading.hide(); });
}

function clickNamespace_zkcluster_manager_table_select_all(obj){
	var chooseCheckBox = $(obj).is(":checked");
	if(!chooseCheckBox){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
		return false;
	}
	var checkChoose = true;
	$(".batchInput").each(function(){
    	if(!$(this).is(":checked")){
    		checkChoose = false;
		}
	});
	if(checkChoose){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',true);// 只有全部都选中，全选复选框才置为true
	}else{
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
	}
}

function refreshZkClusterInfo() {
    $loading.show();
    $.get("registry_center/getAllZkClusterInfo", {}, function(data) {
        if(data.success) {
            if(zk_cluster_info_table_DataTable) {
                zk_cluster_info_table_DataTable.destroy();
            }
            $("#zk_cluster_info_table tbody").empty();
            var list = data.obj;
            if(list && list instanceof Array) {
                for(var i=0; i<list.length; i++) {
                    var zkClusterInfo = list[i];
                    var baseTd = "" + zkClusterInfo.zkClusterKey + "	" +
                                "" + zkClusterInfo.alias + "	" +
                                "" + zkClusterInfo.connectString + "	";
                    $("#zk_cluster_info_table tbody").append("
" + baseTd + "
");
                }
            }
            zk_cluster_info_table_DataTable = $("#zk_cluster_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}
<commit_msg>#190 set the first column unSort<commit_after>var namespace_info_table_DataTable, zk_cluster_info_table_DataTable, namespace_zkcluster_manager_table_DataTable;
var namespace_zkcluster_manager_operation = '【请务必同时只能一个人并且只使用一个浏览器来操作】  ' +
                                            '<button class="btn btn-success" id="batch-move-namespace">批量迁移</button>  ' +
                                            '<button class="btn btn-warning" id="init-namespace-zkcluster-mapping">初始化映射表</button>  ';
$(function() {

	$("#refresh_registry_center").on("click", function() {
		var $btn = $(this).button("loading");
		$.get("registry_center/refreshRegCenter", function(data) {
			if(data.success == true) {
				window.parent.location.reload(true);
			} else {
				showFailureDialogWithMsg("failure-dialog", data.message);
			}
		}).always(function() { $btn.button('reset'); });
	});

	$('[href="#namespace_info_tabpanel"]').on("click", function() {
		refreshNamespaceInfo();
    });
	$('[href="#zk_cluster_info_tabpanel"]').on("click", function() {
		refreshZkClusterInfo();
	});
	$('[href="#namespace_zkcluster_manager_tabpanel"]').on("click", function() {
		refreshNamespaceZkClusterMappingList();
    });
	if ($("#namespace_info_tabpanel").is(':visible')) {
		refreshNamespaceInfo();
	} else if ($("#zk_cluster_info_tabpanel").is(':visible')) {
		refreshZkClusterInfo();
	} else if ($("#namespace_zkcluster_manager_tabpanel").is(':visible')) {
		refreshNamespaceZkClusterMappingList();
	}

	$("#namespace_zkcluster_manager_table_select_all").on('click', function(event) {
	    if($(this).is(":checked")){
            $('.batchInput').prop('checked',true);// jquery1.9以后的版本，用attr有点问题，要用prop
        }else{
            $('.batchInput').prop('checked',false);
        }
    });

    $("#move-namespace-batch-dialog").on("shown.bs.modal", function (event) {
        $("#move-namespace-batch-dialog-confirm-btn").unbind('click').click(function() {
            var namespaces = $("#move-namespace-batch-dialog-namespace").html();
            var bootstrapKeyNew = "";
            if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
                bootstrapKeyNew = $("#move-namespace-batch-dialog-zkCluster").val();
            } else {
                bootstrapKeyNew = $("#move-namespace-batch-dialog-zkCluster-input").val();
            }
            var updateDBOnly = $("#move-namespace-batch-dialog-updateDBOnly").is(":checked");
            $("#confirm-yes-dialog-title").html('域名：
' + namespaces + '
目标集群：
' + bootstrapKeyNew + '
只更新映射表：
' + updateDBOnly + '
确认批量迁移，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    $("#move-namespace-batch-dialog").modal("hide");
                    $("#confirm-yes-dialog").modal("hide");
                    $("#move-namespace-batch-status-dialog-zkCluster").html(bootstrapKeyNew);
                    var split = namespaces.split(",");
                    if(split && split instanceof Array) {
                        var id = parseInt(Math.random() * 10000000);
                        $.post("registry_center/moveNamespaceBatch", {namespaces: namespaces, bootstrapKeyNew: bootstrapKeyNew, updateDBOnly: updateDBOnly, id: id}, function(data) {
                            if(data.success) {
                                var size = split.length;
                                $("#move-namespace-batch-status-dialog-data").html("成功：" + 0 + "
失败：" + 0 + "
忽略：" + 0 + "
未做：" + size + "
总共：" + size);
                                $("#move-namespace-batch-status-dialog-message").html("");
                                $("#move-namespace-batch-status-dialog-tips").css("display", "inline");
                                $("#move-namespace-batch-status-dialog-x").css("display", "none");
                                $("#move-namespace-batch-status-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-status-dialog").modal("show");
                                getMoveNamespaceBatchStatus(id);
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        alert("请选择要迁移的域");
                    }
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });
    });

    $("#move-namespace-batch-dialog-manual").on('click', function(event) {
        if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
            $("#move-namespace-batch-dialog-zkCluster").attr("style", "display:none");
            $("#move-namespace-batch-dialog-zkCluster-input").removeAttr("style");
            $("#move-namespace-batch-dialog-manual").attr("status", "manual");
            $("#move-namespace-batch-dialog-manual").html("在线的集群");
        } else {
            $("#move-namespace-batch-dialog-zkCluster").removeAttr("style");
            $("#move-namespace-batch-dialog-zkCluster-input").attr("style", "display:none");
            $("#move-namespace-batch-dialog-manual").attr("status", "auto");
            $("#move-namespace-batch-dialog-manual").html("手动输入");
        }
    });

    $("#confirm-yes-dialog").on("shown.bs.modal", function (event) {
        $("#giveMeYes").focus();
    });

    $("#move-namespace-batch-status-dialog-x").on("click", function() {
        $("#move-namespace-batch-status-dialog").modal("hide");
        var id = parseInt($("#move-namespace-batch-status-dialog-x").attr("id2"));
        if(!isNaN(id)) {
            $.post("registry_center/clearMoveNamespaceBatchStatus", {id: id}, function(data) {});
        }
        refreshNamespaceZkClusterMappingList();
    });

    refreshNamespaceInfo();
});

function refreshNamespaceInfo() {
    $loading.show();
	$.get("registry_center/getNamespaceInfo", {}, function(data) {
		if(namespace_info_table_DataTable) {
			namespace_info_table_DataTable.destroy();
		}
        $("#namespace_info_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var cluster = list[i];
            		var key = cluster.zkClusterKey;
            		var regCenterConfList = cluster.regCenterConfList;
            		if(regCenterConfList && regCenterConfList instanceof Array) {
            			for(var j=0; j < regCenterConfList.length; j++) {
	        				var regCenterConf = regCenterConfList[j];
			                var baseTd = "" + regCenterConf.namespace + "	"
			                    + regCenterConf.name + "	"
			                    + regCenterConf.version + "	"
			                    + key + "	";
			                $("#namespace_info_table tbody").append("
" + baseTd + "
");
            			}
            		}
	            }
	        }
	        namespace_info_table_DataTable = $("#namespace_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}

function refreshNamespaceZkClusterMappingList() {
    $loading.show();
	$.get("registry_center/getNamespaceZkclusterMappingList", {}, function(data) {
		if(namespace_zkcluster_manager_table_DataTable) {
			namespace_zkcluster_manager_table_DataTable.destroy();
		}
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);
        $("#namespace_zkcluster_manager_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var mapping = list[i];
                    var baseTd = "<input class='batchInput' type='checkbox' onclick='clickNamespace_zkcluster_manager_table_select_all(this);' namespace='" + mapping.namespace + "'/>	"
                        + "" + mapping.namespace + "	"
                        + mapping.zkClusterKey + "	";
                    $("#namespace_zkcluster_manager_table tbody").append("
" + baseTd + "
");
	            }
	        }
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
        namespace_zkcluster_manager_table_DataTable = $("#namespace_zkcluster_manager_table").DataTable({
            "oLanguage": language,
            "aoColumnDefs": [{"bSortable":false,"aTargets":[0]}], // set the first column unSort
            "aaSorting": [[1, "desc"]], // set sort from the second column
            "displayLength":100
            });
        $("#namespace_zkcluster_manager_table_filter label").before(namespace_zkcluster_manager_operation);

        $("#init-namespace-zkcluster-mapping").on("click", function() {
            $("#confirm-yes-dialog-title").html('确认初始化映射表，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    var $btn = $(this).button('loading');
                    $.post("registry_center/initNamespaceZkClusterMapping", {}, function(data) {
                        $("#confirm-yes-dialog").modal("hide");
                        if(data.success) {
                            showSuccessDialog();
                            refreshNamespaceZkClusterMappingList();
                        } else {
                            showFailureDialogWithMsg("failure-dialog", data.message);
                        }
                    }).always(function() {$btn.button('reset');});
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });

        $("#batch-move-namespace").on("click", function() {
            var namespaces = "";
            $(".batchInput").each(function() {
                if($(this).is(":checked")) {
                    if(namespaces == "") {
                        namespaces = $(this).attr("namespace") ;
                    } else {
                        namespaces = namespaces + "," + $(this).attr("namespace") ;
                    }
                }
            });
            if(namespaces == "") {
                showFailureDialogWithMsg("failure-dialog", "请选择要迁移的域");
            } else {
                $.get("registry_center/getZkClusterListWithOnline", {}, function(data) {
                    if(data.success) {
                        $("#move-namespace-batch-dialog-namespace").html(namespaces);
                        $.get("registry_center/getZkClusterListWithOnline", {}, function(data2) {
                            if(data2.success) {
                                var zkClusterListWithOnlineFromCfg = data2.obj;
                                var options = "";
                                if(zkClusterListWithOnlineFromCfg && zkClusterListWithOnlineFromCfg instanceof Array) {
                                    for(var i in zkClusterListWithOnlineFromCfg) {
                                        var zkClusterWithOnlineFromCfg = zkClusterListWithOnlineFromCfg[i];
                                        options += "<option value='"+ zkClusterWithOnlineFromCfg +"'>" + zkClusterWithOnlineFromCfg + "</option>";
                                    }
                                }
                                $("#move-namespace-batch-dialog-zkCluster").empty();
                                $("#move-namespace-batch-dialog-zkCluster").append(options);
                                $("#move-namespace-batch-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-dialog").modal("show");
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        showFailureDialogWithMsg("failure-dialog", data.message);
                    }
                });
            }
        });
    }).always(function() { $loading.hide(); });
}

function clickNamespace_zkcluster_manager_table_select_all(obj){
	var chooseCheckBox = $(obj).is(":checked");
	if(!chooseCheckBox){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
		return false;
	}
	var checkChoose = true;
	$(".batchInput").each(function(){
    	if(!$(this).is(":checked")){
    		checkChoose = false;
		}
	});
	if(checkChoose){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',true);// 只有全部都选中，全选复选框才置为true
	}else{
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
	}
}

function refreshZkClusterInfo() {
    $loading.show();
    $.get("registry_center/getAllZkClusterInfo", {}, function(data) {
        if(data.success) {
            if(zk_cluster_info_table_DataTable) {
                zk_cluster_info_table_DataTable.destroy();
            }
            $("#zk_cluster_info_table tbody").empty();
            var list = data.obj;
            if(list && list instanceof Array) {
                for(var i=0; i<list.length; i++) {
                    var zkClusterInfo = list[i];
                    var baseTd = "" + zkClusterInfo.zkClusterKey + "	" +
                                "" + zkClusterInfo.alias + "	" +
                                "" + zkClusterInfo.connectString + "	";
                    $("#zk_cluster_info_table tbody").append("
" + baseTd + "
");
                }
            }
            zk_cluster_info_table_DataTable = $("#zk_cluster_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}
<|endoftext|>


<commit_before>module.exports = ({ debug = false } = {}) => {
  function marshallErr (err) {
    let error = { message: err.message };
    if (debug) {
      error.stack = err.stack;
    }
    return error;
  }

  return async (ctx, next) => {
    try {
      await next();

      if (ctx.status >= 400) {
        let status = ctx.status;
        ctx.body = ctx.body || { errors: [ { message: ctx.response.statusMessage } ] };
        ctx.status = status;
      } else if (ctx.state.result) {
        ctx.body = ctx.state.result;
      }
    } catch (err) {
      ctx.status = err.status || 500;
      if (ctx.status >= 500) {
        console.error(`Caught error with stack: ${err.stack}`);
      }
      ctx.lastError = err;

      let errors = [];
      if (err.children) {
        errors = err.children.map(childErr => marshallErr(childErr));
      } else {
        errors.push(marshallErr(err));
      }

      ctx.body = { errors };
    }
  };
};
<commit_msg>Fix empty errors on 4xx status code when using json middleware<commit_after>module.exports = ({ debug = false } = {}) => {
  function marshallErr (err) {
    let error = { message: err.message };
    if (debug) {
      error.stack = err.stack;
    }
    return error;
  }

  return async (ctx, next) => {
    try {
      await next();

      if (ctx.status >= 400) {
        let { status, message } = ctx;
        ctx.body = ctx.body || { errors: [ { message } ] };
        ctx.status = status;
      } else if (ctx.state.result) {
        ctx.body = ctx.state.result;
      }
    } catch (err) {
      ctx.status = err.status || 500;
      if (ctx.status >= 500) {
        console.error(`Caught error with stack: ${err.stack}`);
      }
      ctx.lastError = err;

      let errors = [];
      if (err.children) {
        errors = err.children.map(childErr => marshallErr(childErr));
      } else {
        errors.push(marshallErr(err));
      }

      ctx.body = { errors };
    }
  };
};
<|endoftext|>


<commit_before>/*
 * jQuery UI Position @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Position
 */
(function( $, undefined ) {

$.ui = $.ui || {};

var rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[+-]\d+%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	center = "center",
	_position = $.fn.position;

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var target = $( options.of ),
		within  = $( options.within || window ),
		targetElem = target[0],
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {},
		atOffset,
		targetWidth,
		targetHeight,
		basePosition;

	if ( targetElem.nodeType === 9 ) {
		targetWidth = target.width();
		targetHeight = target.height();
		basePosition = { top: 0, left: 0 };
	} else if ( $.isWindow( targetElem ) ) {
		targetWidth = target.width();
		targetHeight = target.height();
		basePosition = { top: target.scrollTop(), left: target.scrollLeft() };
	} else if ( targetElem.preventDefault ) {
		// force left top to allow flipping
		options.at = "left top";
		targetWidth = targetHeight = 0;
		basePosition = { top: options.of.pageY, left: options.of.pageX };
	} else {
		targetWidth = target.outerWidth();
		targetHeight = target.outerHeight();
		basePosition = target.offset();
	}

	// force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ center ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ center ].concat( pos ) :
					[ center, center ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : center;
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : center;

		// calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	});

	// normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === center ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === center ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = [
		parseInt( offsets.at[ 0 ], 10 ) *
			( rpercent.test( offsets.at[ 0 ] ) ? targetWidth / 100 : 1 ),
		parseInt( offsets.at[ 1 ], 10 ) *
			( rpercent.test( offsets.at[ 1 ] ) ? targetHeight / 100 : 1 )
	];
	basePosition.left += atOffset[ 0 ],
	basePosition.top += atOffset[ 1 ];

	return this.each(function() {
		var elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseInt( $.curCSS( this, "marginLeft", true ) ) || 0,
			marginTop = parseInt( $.curCSS( this, "marginTop", true ) ) || 0,
			collisionWidth = elemWidth + marginLeft +
				( parseInt( $.curCSS( this, "marginRight", true ) ) || 0 ),
			collisionHeight = elemHeight + marginTop +
				( parseInt( $.curCSS( this, "marginBottom", true ) ) || 0 ),
			position = $.extend( {}, basePosition ),
			myOffset = [
				parseInt( offsets.my[ 0 ], 10 ) *
					( rpercent.test( offsets.my[ 0 ] ) ? elem.outerWidth() / 100 : 1 ),
				parseInt( offsets.my[ 1 ], 10 ) *
					( rpercent.test( offsets.my[ 1 ] ) ? elem.outerHeight() / 100 : 1 )
			],
			collisionPosition;

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === center ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === center ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		// prevent fractions (see #5280)
		position.left = Math.round( position.left );
		position.top = Math.round( position.top );

		collisionPosition = {
			left: position.left - marginLeft,
			top: position.top - marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within
				});
			}
		});

		if ( $.fn.bgiframe ) {
			elem.bgiframe();
		}
		elem.offset( $.extend( position, { using: options.using } ) );
	});
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().left,
				outerWidth = isWindow ? win.width() : win.outerWidth(),
				overLeft = win.scrollLeft() - data.collisionPosition.left + winOffset,
				overRight = data.collisionPosition.left + data.collisionWidth - outerWidth - win.scrollLeft() - winOffset;

			// element is wider than window or too far left -> align with left edge
			if ( data.collisionWidth > outerWidth || overLeft > 0 ) {
				position.left = position.left + overLeft;
			// too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left = position.left - overRight;
			// adjust based on position and margin
			} else {
				position.left = Math.max( position.left - data.collisionPosition.left, position.left );
			}
		},
		top: function( position, data ) {
			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().top,
				outerHeight = isWindow ? win.height() : win.outerHeight(),
				overTop = win.scrollTop() - data.collisionPosition.top + winOffset,
				overBottom = data.collisionPosition.top + data.collisionHeight - outerHeight - win.scrollTop() - winOffset;

			// element is taller than window or too far up -> align with top edge
			if ( data.collisionHeight > outerHeight || overTop > 0 ) {
				position.top = position.top + overTop;
			// too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top = position.top - overBottom;
			// adjust based on position and margin
			} else {
				position.top = Math.max( position.top - data.collisionPosition.top, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			if ( data.at[ 0 ] === center ) {
				return;
			}

			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().left,
				outerWidth = isWindow ? win.width() : win.outerWidth(),
				overLeft = data.collisionPosition.left - winOffset,
				overRight = data.collisionPosition.left + data.collisionWidth - outerWidth - win.scrollLeft() - winOffset,
				left = data.my[ 0 ] === "left",
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					-data.targetWidth,
				offset = -2 * data.offset[ 0 ];
			if ( overLeft < 0 || overRight > 0 ) {
				position.left += myOffset + atOffset + offset;
			}
		},
		top: function( position, data ) {
			if ( data.at[ 1 ] === center ) {
				return;
			}
			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().top,
				outerHeight = isWindow ? win.height() : win.outerHeight(),
				overTop = data.collisionPosition.top - winOffset,
				overBottom = data.collisionPosition.top + data.collisionHeight - outerHeight - win.scrollTop() - winOffset,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					-data.targetHeight,
				offset = -2 * data.offset[ 1 ];
			if ( overTop < 0 || overBottom > 0) {
				position.top += myOffset + atOffset + offset;
			}
		}
	}
};

// DEPRECATED
if ( $.uiBackCompat !== false ) {
	// offset option
	(function( $ ) {
		var _position = $.fn.position;
		$.fn.position = function( options ) {
			if ( !options || !( "offset" in options ) ) {
				return _position.call( this, options );
			}
			var offset = options.offset.split( " " ),
				at = options.at.split( " " );
			if ( offset.length === 1 ) {
				offset[ 1 ] = offset[ 0 ];
			}
			if ( /^\d/.test( offset[ 0 ] ) ) {
				offset[ 0 ] = "+" + offset[ 0 ];
			}
			if ( /^\d/.test( offset[ 1 ] ) ) {
				offset[ 1 ] = "+" + offset[ 1 ];
			}
			if ( at.length === 1 ) {
				if ( /left|center|right/.test( at[ 0 ] ) ) {
					at[ 1 ] = "center";
				} else {
					at[ 1 ] = at[ 0 ];
					at[ 0 ] = "center";
				}
			}
			return _position.call( this, $.extend( options, {
				at: at[ 0 ] + offset[ 0 ] + " " + at[ 1 ] + offset[ 1 ],
				offset: undefined
			} ) );
		}
	}( jQuery ) );
}

}( jQuery ) );<commit_msg>Replace comma with semi-colon. How'd that get there?<commit_after>/*
 * jQuery UI Position @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Position
 */
(function( $, undefined ) {

$.ui = $.ui || {};

var rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[+-]\d+%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	center = "center",
	_position = $.fn.position;

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var target = $( options.of ),
		within  = $( options.within || window ),
		targetElem = target[0],
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {},
		atOffset,
		targetWidth,
		targetHeight,
		basePosition;

	if ( targetElem.nodeType === 9 ) {
		targetWidth = target.width();
		targetHeight = target.height();
		basePosition = { top: 0, left: 0 };
	} else if ( $.isWindow( targetElem ) ) {
		targetWidth = target.width();
		targetHeight = target.height();
		basePosition = { top: target.scrollTop(), left: target.scrollLeft() };
	} else if ( targetElem.preventDefault ) {
		// force left top to allow flipping
		options.at = "left top";
		targetWidth = targetHeight = 0;
		basePosition = { top: options.of.pageY, left: options.of.pageX };
	} else {
		targetWidth = target.outerWidth();
		targetHeight = target.outerHeight();
		basePosition = target.offset();
	}

	// force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ center ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ center ].concat( pos ) :
					[ center, center ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : center;
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : center;

		// calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	});

	// normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === center ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === center ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = [
		parseInt( offsets.at[ 0 ], 10 ) *
			( rpercent.test( offsets.at[ 0 ] ) ? targetWidth / 100 : 1 ),
		parseInt( offsets.at[ 1 ], 10 ) *
			( rpercent.test( offsets.at[ 1 ] ) ? targetHeight / 100 : 1 )
	];
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each(function() {
		var elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseInt( $.curCSS( this, "marginLeft", true ) ) || 0,
			marginTop = parseInt( $.curCSS( this, "marginTop", true ) ) || 0,
			collisionWidth = elemWidth + marginLeft +
				( parseInt( $.curCSS( this, "marginRight", true ) ) || 0 ),
			collisionHeight = elemHeight + marginTop +
				( parseInt( $.curCSS( this, "marginBottom", true ) ) || 0 ),
			position = $.extend( {}, basePosition ),
			myOffset = [
				parseInt( offsets.my[ 0 ], 10 ) *
					( rpercent.test( offsets.my[ 0 ] ) ? elem.outerWidth() / 100 : 1 ),
				parseInt( offsets.my[ 1 ], 10 ) *
					( rpercent.test( offsets.my[ 1 ] ) ? elem.outerHeight() / 100 : 1 )
			],
			collisionPosition;

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === center ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === center ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		// prevent fractions (see #5280)
		position.left = Math.round( position.left );
		position.top = Math.round( position.top );

		collisionPosition = {
			left: position.left - marginLeft,
			top: position.top - marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within
				});
			}
		});

		if ( $.fn.bgiframe ) {
			elem.bgiframe();
		}
		elem.offset( $.extend( position, { using: options.using } ) );
	});
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().left,
				outerWidth = isWindow ? win.width() : win.outerWidth(),
				overLeft = win.scrollLeft() - data.collisionPosition.left + winOffset,
				overRight = data.collisionPosition.left + data.collisionWidth - outerWidth - win.scrollLeft() - winOffset;

			// element is wider than window or too far left -> align with left edge
			if ( data.collisionWidth > outerWidth || overLeft > 0 ) {
				position.left = position.left + overLeft;
			// too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left = position.left - overRight;
			// adjust based on position and margin
			} else {
				position.left = Math.max( position.left - data.collisionPosition.left, position.left );
			}
		},
		top: function( position, data ) {
			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().top,
				outerHeight = isWindow ? win.height() : win.outerHeight(),
				overTop = win.scrollTop() - data.collisionPosition.top + winOffset,
				overBottom = data.collisionPosition.top + data.collisionHeight - outerHeight - win.scrollTop() - winOffset;

			// element is taller than window or too far up -> align with top edge
			if ( data.collisionHeight > outerHeight || overTop > 0 ) {
				position.top = position.top + overTop;
			// too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top = position.top - overBottom;
			// adjust based on position and margin
			} else {
				position.top = Math.max( position.top - data.collisionPosition.top, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			if ( data.at[ 0 ] === center ) {
				return;
			}

			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().left,
				outerWidth = isWindow ? win.width() : win.outerWidth(),
				overLeft = data.collisionPosition.left - winOffset,
				overRight = data.collisionPosition.left + data.collisionWidth - outerWidth - win.scrollLeft() - winOffset,
				left = data.my[ 0 ] === "left",
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					-data.targetWidth,
				offset = -2 * data.offset[ 0 ];
			if ( overLeft < 0 || overRight > 0 ) {
				position.left += myOffset + atOffset + offset;
			}
		},
		top: function( position, data ) {
			if ( data.at[ 1 ] === center ) {
				return;
			}
			var win = data.within,
				isWindow = $.isWindow( data.within[0] ),
				winOffset = isWindow ? 0 : win.offset().top,
				outerHeight = isWindow ? win.height() : win.outerHeight(),
				overTop = data.collisionPosition.top - winOffset,
				overBottom = data.collisionPosition.top + data.collisionHeight - outerHeight - win.scrollTop() - winOffset,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					-data.targetHeight,
				offset = -2 * data.offset[ 1 ];
			if ( overTop < 0 || overBottom > 0) {
				position.top += myOffset + atOffset + offset;
			}
		}
	}
};

// DEPRECATED
if ( $.uiBackCompat !== false ) {
	// offset option
	(function( $ ) {
		var _position = $.fn.position;
		$.fn.position = function( options ) {
			if ( !options || !( "offset" in options ) ) {
				return _position.call( this, options );
			}
			var offset = options.offset.split( " " ),
				at = options.at.split( " " );
			if ( offset.length === 1 ) {
				offset[ 1 ] = offset[ 0 ];
			}
			if ( /^\d/.test( offset[ 0 ] ) ) {
				offset[ 0 ] = "+" + offset[ 0 ];
			}
			if ( /^\d/.test( offset[ 1 ] ) ) {
				offset[ 1 ] = "+" + offset[ 1 ];
			}
			if ( at.length === 1 ) {
				if ( /left|center|right/.test( at[ 0 ] ) ) {
					at[ 1 ] = "center";
				} else {
					at[ 1 ] = at[ 0 ];
					at[ 0 ] = "center";
				}
			}
			return _position.call( this, $.extend( options, {
				at: at[ 0 ] + offset[ 0 ] + " " + at[ 1 ] + offset[ 1 ],
				offset: undefined
			} ) );
		}
	}( jQuery ) );
}

}( jQuery ) );<|endoftext|>