<commit_before>// Hyperspace is Asteroids in Javascript
// Authors: @kenpratt and @icco
//
// This code is dependent on the coquette library:
// http://coquette.maryrosecook.com/

function getRandom(min, max) {
  return Math.random() * (max - min) + min;
}

// http://stackoverflow.com/a/6444043/1063
function increase_brightness(hex, percent) {
  // strip the leading # if it's there
  hex = hex.replace(/^\s*#|\s*$/g, '');

  // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
  if (hex.length == 3) {
    hex = hex.replace(/(.)/g, '$1$1');
  }

  var r = parseInt(hex.substr(0, 2), 16),
      g = parseInt(hex.substr(2, 2), 16),
      b = parseInt(hex.substr(4, 2), 16);

  return '#' +
    ((0|(1<<8) + r + (256 - r) * percent / 100).toString(16)).substr(1) +
    ((0|(1<<8) + g + (256 - g) * percent / 100).toString(16)).substr(1) +
    ((0|(1<<8) + b + (256 - b) * percent / 100).toString(16)).substr(1);
}

// The main game initializer. This function sets up the game.
var Hyperspace = function() {
  this.size = {x: 1000, y: 600};
  this.c = new Coquette(this, "canvas", this.size.x, this.size.y, "#000");

  this.conn = new ServerConnection("ws://" + window.location.host + "/ws");
  this.conn.connect();

  this.playerId = null;

  this.update = function() {
    center = this.c.renderer.getViewCenter()
    for (var i = this.c.entities.all(Star).length; i < 100; i++) {
      var where = {
        x: getRandom((center.x - this.size.x/2), (center.x + this.size.x/2)),
        y: getRandom((center.y - this.size.y/2), (center.y + this.size.y/2)),
      }
      this.c.entities.create(Star, {center: where});
    }

    /* For Debugging
    for (var i in this.c.entities.all(Ship)) {
      var ship = this.c.entities.all(Ship)[i];
      console.log(ship.id, ship.center);
    }
    */
  };

  this.conn.handle("init", function(data) {
    this.playerId = data.id;
    this.addOwnShip(data);
  }.bind(this));

  this.conn.handle("position", function(data) {
    // TODO: use map to lookup by id instead of iterating
    var entities = this.c.entities.all(Ship);
    var ship = null;
    for (i in entities) {
      if (entities[i].id === data.id) {
        ship = entities[i];
        break;
      }
    }

    if (ship) {
      ship.center.x = data.x;
      ship.center.y = data.y;
    } else {
      console.log("Adding enemy ship");
      this.addEnemyShip(data);
    }
  }.bind(this));
};

var Star = function(game, settings) {
  this.c = game.c;
  for (var i in settings) {
    this[i] = settings[i];
  }
  this.zindex = -3;
  this.size = {x: 5, y: 5};
  this.update = function() {
    if (!this.c.renderer.onScreen(this)) {
      this.c.entities.destroy(this);
    }
  };
  this.draw = function(ctx) {
    ctx.fillStyle = "#cc9933";
    ctx.fillRect(this.center.x, this.center.y, this.size.x, this.size.y);
  };
};

Hyperspace.prototype.addOwnShip = function(data) {
  // Create the ship that the current player drives. It differs from all other
  // ships in that it has an update loop (called every tick) that takes in
  // directions from the keyboard.
  this.c.entities.create(Ship, {
    center: { x: data.x, y: data.y },
    id: data.id,
    color:"#f07",

    // Movement is based off of this SO article which basically reminded me how
    // vectors work: http://stackoverflow.com/a/3639025/1063
    update: function() {

      // This keeps the players ship always in the center.
      this.c.renderer.setViewCenter(this.center);

      var angleToVector = function(angle) {
        // Convert to radians.
        var r = angle * 0.01745;
        return unitVector({ x: Math.sin(r), y: -Math.cos(r) });
      };
      var magnitude = function(vector) {
        return Math.sqrt(vector.x * vector.x + vector.y * vector.y);
      };
      var unitVector = function(vector) {
        return {
          x: vector.x / magnitude(vector),
          y: vector.y / magnitude(vector)
        };
      };

      this.angle %= 360;

      // Key pressed booleans
      var forward_pressed =
        this.c.inputter.isDown(this.c.inputter.UP_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.W) ||
        this.c.inputter.isDown(this.c.inputter.COMMA);
      var down_pressed =
        this.c.inputter.isDown(this.c.inputter.DOWN_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.S) ||
        this.c.inputter.isDown(this.c.inputter.O);
      var left_pressed =
        this.c.inputter.isDown(this.c.inputter.LEFT_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.A);
      var right_pressed =
        this.c.inputter.isDown(this.c.inputter.RIGHT_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.D) ||
        this.c.inputter.isDown(this.c.inputter.E);

      // Back and forth movement
      if (forward_pressed) {
        var vector = angleToVector(this.angle);
        this.center.x += vector.x;
        this.center.y += vector.y;
      } else if (down_pressed) {
        // TODO(icco): Support breaking.
      }

      // Turning.
      if (right_pressed) {
        this.angle += 2;
      } else if (left_pressed) {
        this.angle -= 2;
      }

      if (this.lastX !== this.center.x || this.lastY !== this.center.y) {
        this.lastX = this.center.x;
        this.lastY = this.center.y;
        this.conn.send("position", {
          center: this.center,
          id: this.id,
          angle: this.angle,
          pressed: {
            right: right_pressed,
            down: down_pressed,
            left: left_pressed,
            forward: forward_pressed,
          },
        });
      }

      // Fire the lasers! Say Pew Pew Pew every time you press the space bar
      // please.
      if (this.c.inputter.isPressed(this.c.inputter.SPACE)) {
        if (this.c.entities.all(Laser).length < 30) {
          this.c.entities.create(Laser, {
            center: { x:this.center.x, y:this.center.y },
            vector: angleToVector(this.angle),
            owner: this.id,
            created: Date.now(),
          });
        }
      }
    },
  });
};

Hyperspace.prototype.addEnemyShip = function(data) {
  this.c.entities.create(Ship, {
    id: data.id,
    center: { x: data.x, y: data.y },
    color:"#0f7"
  });
};

// This defines the basic ship shape as a series of verices for a path to
// follow.
var ship_shape = [
  [ 0, -5],
  [-5,  5],
  [ 0,  2],
  [ 5,  5],
  [ 0, -5]
]

// The actual ship entity. One of these will be created for every single player
// in the game. Please set the color.
var Ship = function(game, settings) {
  this.c = game.c;
  this.conn = game.conn;
  for (var i in settings) {
    this[i] = settings[i];
  }

  // This is the size of the ship.
  this.scale = 1.5;
  this.size = { x: 10 * this.scale, y: 10 * this.scale }
  this.angle = 0;

  // This is run every tick to draw the ship.
  this.draw = function(ctx) {
    // The color of the outline of the ship.
    ctx.strokeStyle = settings.color;
    ctx.fillStyle = increase_brightness(settings.color, 10);

    // Draw the actual ship body.
    ctx.beginPath();
    for (i in ship_shape) {
      var vertex = ship_shape[i];
      var x = (vertex[0] * this.scale) + this.center.x;
      var y = (vertex[1] * this.scale) + this.center.y;
      ctx.lineTo(x, y);
    }
    ctx.stroke();
    ctx.fill();
  };
};

var Laser = function(game, settings) {
  this.c = game.c;
  this.conn = game.conn;
  this.boundingBox = this.c.collider.CIRCLE;
  this.size = { x: 3, y: 3 };
  this.zindex = -1;

  for (var i in settings) {
    this[i] = settings[i];
  }

  this.update = function() {
    var age = Date.now() - this.created;
    // Kill lazers older than three seconds.
    if (age < 3000) {
      this.center.x += (this.vector.x * 2);
      this.center.y += (this.vector.y * 2);
    } else {
      this.c.entities.destroy(this);
    }
  };

  this.draw = function(ctx) {
    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.arc(
        this.center.x, // x
        this.center.y, // y
        this.size.x, // Radius
        0, // Start Angle
        Math.PI*2, // End Angle
        true); // Anticlockwise?
    ctx.fill();
  };
};

var ServerConnection = function(url) {
  this.url = url;
  this.socket = null;
  this.handlers = {};
};

ServerConnection.prototype.connect = function() {
  this.socket = new WebSocket(this.url);
  this.socket.onopen = this.onConnect.bind(this);
  this.socket.onclose = this.onDisconnect.bind(this);
  this.socket.onmessage = this.onMessage.bind(this);
}

ServerConnection.prototype.onConnect = function() {
  console.log("websocket connected");
};

ServerConnection.prototype.onDisconnect = function() {
  console.log("websocket disconnected");
};

ServerConnection.prototype.onMessage = function(ev) {
  var raw = JSON.parse(ev.data);
  var type = raw.type;
  var data = raw.data;
  // console.log("websocket received message", type, data);

  var fn = this.handlers[type];
  if (fn) {
    fn(data);
  }
};

ServerConnection.prototype.send = function(type, data) {
  var msg = JSON.stringify({ type: type, data: data });
  if (this.socket.readyState === this.socket.OPEN) {
    // console.log("websocket sending message", type, data);
    this.socket.send(msg);
  } else {
    console.warn("websocket not connected, can't send message", type, data);
  }
};

ServerConnection.prototype.handle = function(type, fn) {
  this.handlers[type] = fn;
};

window.addEventListener('load', function() {
  // Begin the game once the page is loaded! Party like it's 1979!
  new Hyperspace();
});
<commit_msg>revert to just sendign position<commit_after>// Hyperspace is Asteroids in Javascript
// Authors: @kenpratt and @icco
//
// This code is dependent on the coquette library:
// http://coquette.maryrosecook.com/

function getRandom(min, max) {
  return Math.random() * (max - min) + min;
}

// http://stackoverflow.com/a/6444043/1063
function increase_brightness(hex, percent) {
  // strip the leading # if it's there
  hex = hex.replace(/^\s*#|\s*$/g, '');

  // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
  if (hex.length == 3) {
    hex = hex.replace(/(.)/g, '$1$1');
  }

  var r = parseInt(hex.substr(0, 2), 16),
      g = parseInt(hex.substr(2, 2), 16),
      b = parseInt(hex.substr(4, 2), 16);

  return '#' +
    ((0|(1<<8) + r + (256 - r) * percent / 100).toString(16)).substr(1) +
    ((0|(1<<8) + g + (256 - g) * percent / 100).toString(16)).substr(1) +
    ((0|(1<<8) + b + (256 - b) * percent / 100).toString(16)).substr(1);
}

// The main game initializer. This function sets up the game.
var Hyperspace = function() {
  this.size = {x: 1000, y: 600};
  this.c = new Coquette(this, "canvas", this.size.x, this.size.y, "#000");

  this.conn = new ServerConnection("ws://" + window.location.host + "/ws");
  this.conn.connect();

  this.playerId = null;

  this.update = function() {
    center = this.c.renderer.getViewCenter()
    for (var i = this.c.entities.all(Star).length; i < 100; i++) {
      var where = {
        x: getRandom((center.x - this.size.x/2), (center.x + this.size.x/2)),
        y: getRandom((center.y - this.size.y/2), (center.y + this.size.y/2)),
      }
      this.c.entities.create(Star, {center: where});
    }

    /* For Debugging
    for (var i in this.c.entities.all(Ship)) {
      var ship = this.c.entities.all(Ship)[i];
      console.log(ship.id, ship.center);
    }
    */
  };

  this.conn.handle("init", function(data) {
    this.playerId = data.id;
    this.addOwnShip(data);
  }.bind(this));

  this.conn.handle("position", function(data) {
    // TODO: use map to lookup by id instead of iterating
    var entities = this.c.entities.all(Ship);
    var ship = null;
    for (i in entities) {
      if (entities[i].id === data.id) {
        ship = entities[i];
        break;
      }
    }

    if (ship) {
      ship.center.x = data.x;
      ship.center.y = data.y;
    } else {
      console.log("Adding enemy ship");
      this.addEnemyShip(data);
    }
  }.bind(this));
};

var Star = function(game, settings) {
  this.c = game.c;
  for (var i in settings) {
    this[i] = settings[i];
  }
  this.zindex = -3;
  this.size = {x: 5, y: 5};
  this.update = function() {
    if (!this.c.renderer.onScreen(this)) {
      this.c.entities.destroy(this);
    }
  };
  this.draw = function(ctx) {
    ctx.fillStyle = "#cc9933";
    ctx.fillRect(this.center.x, this.center.y, this.size.x, this.size.y);
  };
};

Hyperspace.prototype.addOwnShip = function(data) {
  // Create the ship that the current player drives. It differs from all other
  // ships in that it has an update loop (called every tick) that takes in
  // directions from the keyboard.
  this.c.entities.create(Ship, {
    center: { x: data.x, y: data.y },
    id: data.id,
    color:"#f07",

    // Movement is based off of this SO article which basically reminded me how
    // vectors work: http://stackoverflow.com/a/3639025/1063
    update: function() {

      // This keeps the players ship always in the center.
      this.c.renderer.setViewCenter(this.center);

      var angleToVector = function(angle) {
        // Convert to radians.
        var r = angle * 0.01745;
        return unitVector({ x: Math.sin(r), y: -Math.cos(r) });
      };
      var magnitude = function(vector) {
        return Math.sqrt(vector.x * vector.x + vector.y * vector.y);
      };
      var unitVector = function(vector) {
        return {
          x: vector.x / magnitude(vector),
          y: vector.y / magnitude(vector)
        };
      };

      this.angle %= 360;

      // Key pressed booleans
      var forward_pressed =
        this.c.inputter.isDown(this.c.inputter.UP_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.W) ||
        this.c.inputter.isDown(this.c.inputter.COMMA);
      var down_pressed =
        this.c.inputter.isDown(this.c.inputter.DOWN_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.S) ||
        this.c.inputter.isDown(this.c.inputter.O);
      var left_pressed =
        this.c.inputter.isDown(this.c.inputter.LEFT_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.A);
      var right_pressed =
        this.c.inputter.isDown(this.c.inputter.RIGHT_ARROW) ||
        this.c.inputter.isDown(this.c.inputter.D) ||
        this.c.inputter.isDown(this.c.inputter.E);

      // Back and forth movement
      if (forward_pressed) {
        var vector = angleToVector(this.angle);
        this.center.x += vector.x;
        this.center.y += vector.y;
      } else if (down_pressed) {
        // TODO(icco): Support breaking.
      }

      // Turning.
      if (right_pressed) {
        this.angle += 2;
      } else if (left_pressed) {
        this.angle -= 2;
      }

      if (this.lastX !== this.center.x || this.lastY !== this.center.y) {
        this.lastX = this.center.x;
        this.lastY = this.center.y;
        this.conn.send("position", this.center);
      }

      // Fire the lasers! Say Pew Pew Pew every time you press the space bar
      // please.
      if (this.c.inputter.isPressed(this.c.inputter.SPACE)) {
        if (this.c.entities.all(Laser).length < 30) {
          this.c.entities.create(Laser, {
            center: { x:this.center.x, y:this.center.y },
            vector: angleToVector(this.angle),
            owner: this.id,
            created: Date.now(),
          });
        }
      }
    },
  });
};

Hyperspace.prototype.addEnemyShip = function(data) {
  this.c.entities.create(Ship, {
    id: data.id,
    center: { x: data.x, y: data.y },
    color:"#0f7"
  });
};

// This defines the basic ship shape as a series of verices for a path to
// follow.
var ship_shape = [
  [ 0, -5],
  [-5,  5],
  [ 0,  2],
  [ 5,  5],
  [ 0, -5]
]

// The actual ship entity. One of these will be created for every single player
// in the game. Please set the color.
var Ship = function(game, settings) {
  this.c = game.c;
  this.conn = game.conn;
  for (var i in settings) {
    this[i] = settings[i];
  }

  // This is the size of the ship.
  this.scale = 1.5;
  this.size = { x: 10 * this.scale, y: 10 * this.scale }
  this.angle = 0;

  // This is run every tick to draw the ship.
  this.draw = function(ctx) {
    // The color of the outline of the ship.
    ctx.strokeStyle = settings.color;
    ctx.fillStyle = increase_brightness(settings.color, 10);

    // Draw the actual ship body.
    ctx.beginPath();
    for (i in ship_shape) {
      var vertex = ship_shape[i];
      var x = (vertex[0] * this.scale) + this.center.x;
      var y = (vertex[1] * this.scale) + this.center.y;
      ctx.lineTo(x, y);
    }
    ctx.stroke();
    ctx.fill();
  };
};

var Laser = function(game, settings) {
  this.c = game.c;
  this.conn = game.conn;
  this.boundingBox = this.c.collider.CIRCLE;
  this.size = { x: 3, y: 3 };
  this.zindex = -1;

  for (var i in settings) {
    this[i] = settings[i];
  }

  this.update = function() {
    var age = Date.now() - this.created;
    // Kill lazers older than three seconds.
    if (age < 3000) {
      this.center.x += (this.vector.x * 2);
      this.center.y += (this.vector.y * 2);
    } else {
      this.c.entities.destroy(this);
    }
  };

  this.draw = function(ctx) {
    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.arc(
        this.center.x, // x
        this.center.y, // y
        this.size.x, // Radius
        0, // Start Angle
        Math.PI*2, // End Angle
        true); // Anticlockwise?
    ctx.fill();
  };
};

var ServerConnection = function(url) {
  this.url = url;
  this.socket = null;
  this.handlers = {};
};

ServerConnection.prototype.connect = function() {
  this.socket = new WebSocket(this.url);
  this.socket.onopen = this.onConnect.bind(this);
  this.socket.onclose = this.onDisconnect.bind(this);
  this.socket.onmessage = this.onMessage.bind(this);
}

ServerConnection.prototype.onConnect = function() {
  console.log("websocket connected");
};

ServerConnection.prototype.onDisconnect = function() {
  console.log("websocket disconnected");
};

ServerConnection.prototype.onMessage = function(ev) {
  var raw = JSON.parse(ev.data);
  var type = raw.type;
  var data = raw.data;
  // console.log("websocket received message", type, data);

  var fn = this.handlers[type];
  if (fn) {
    fn(data);
  }
};

ServerConnection.prototype.send = function(type, data) {
  var msg = JSON.stringify({ type: type, data: data });
  if (this.socket.readyState === this.socket.OPEN) {
    // console.log("websocket sending message", type, data);
    this.socket.send(msg);
  } else {
    console.warn("websocket not connected, can't send message", type, data);
  }
};

ServerConnection.prototype.handle = function(type, fn) {
  this.handlers[type] = fn;
};

window.addEventListener('load', function() {
  // Begin the game once the page is loaded! Party like it's 1979!
  new Hyperspace();
});
<|endoftext|>


<commit_before>var count = 0;
var idTest = "idTest";
function createDivFailedTest(contentDiv,className,divParent,divName,file,line,message,code) {
	idTest = "idTest"+count;

	var div = document.createElement('div');
	div.id = divName;
	div.className  = className;
	var content = document.getElementById(divParent);

	div.innerHTML = '
'+contentDiv+'
'
			+'
+'+line+'
'
			+'
'+file+'
'
			+'
'+message+'
'
			+'<input type="image" src="images/bullet_arrow_down1.png" class="classButton" data-idtest='+"#"+idTest+' >';

	content.appendChild(div);

	createDiv(code,"testInfo totalTests box",divName,idTest);
	count = count + 1;

}

function createDiv(contentDiv,className,divParent,divName) {
	var div = document.createElement('div');
	div.id = divName;
	div.className  = className;
	var content = document.getElementById(divParent);
	div.innerHTML = '
'+contentDiv+"
";
	content.appendChild(div);
}

$(document).ready(function(){

	$("#hideTestsOK").click(function(){
		$(".testOK").slideToggle();

	});

	$( ".classButton" ).click(function(){
		var idTest = $(this).data('idtest');
		$(idTest).slideToggle();

	});

	$("#runAllTests").click(function(){
		runAllTests();
	});

	runAllTests = function (){
		$.ajax({
			url:  'http://localhost/PUWI/view/prueba.php',
			dataType: "json",
			type: 'POST',
		    async: true,
			data: {parametro:'RUN'},

			success: function(request){

				$('#title').html('request: '+request['probando']+request['whoami']);
			},

			error: function(){

				alert("falla");
			}
		});
	}

});

<commit_msg>Add a title to image button<commit_after>var count = 0;
var idTest = "idTest";
function createDivFailedTest(contentDiv,className,divParent,divName,file,line,message,code) {
	idTest = "idTest"+count;

	var div = document.createElement('div');
	div.id = divName;
	div.className  = className;
	var content = document.getElementById(divParent);

	div.innerHTML = '
'+contentDiv+'
'
			+'
+'+line+'
'
			+'
'+file+'
'
			+'
'+message+'
'
			+'<input type="image" src="images/bullet_arrow_down1.png" title="Show code" class="classButton" data-idtest='+"#"+idTest+' >';

	content.appendChild(div);

	createDiv(code,"testInfo totalTests box",divName,idTest);
	count = count + 1;

}

function createDiv(contentDiv,className,divParent,divName) {
	var div = document.createElement('div');
	div.id = divName;
	div.className  = className;
	var content = document.getElementById(divParent);
	div.innerHTML = '
'+contentDiv+"
";
	content.appendChild(div);
}

$(document).ready(function(){

	$("#hideTestsOK").click(function(){
		$(".testOK").slideToggle();

	});

	$( ".classButton" ).click(function(){
		var idTest = $(this).data('idtest');
		$(idTest).slideToggle();

	});

	$("#runAllTests").click(function(){
		runAllTests();
	});

	runAllTests = function (){
		$.ajax({
			url:  'http://localhost/PUWI/view/prueba.php',
			dataType: "json",
			type: 'POST',
		    async: true,
			data: {parametro:'RUN'},

			success: function(request){

				$('#title').html('request: '+request['probando']+request['whoami']);
			},

			error: function(){

				alert("falla");
			}
		});
	}

});

<|endoftext|>


<commit_before>let new_directory_name = document.getElementById("name");
let files = document.getElementById("files");

var url_base = window.location;
var current_path;
var editable = undefined;

async function refresh_list() {

    function compareValues(a, b) {
        if (a.value === b.value) {
          return 0;
        } else {
          return a.value < b.value ? -1 : 1;
        }
    }

    current_path = window.location.hash.substr(1);
    if (current_path == "") {
        current_path = "/";
    }
    // Do the fetch first because the browser will prompt for credentials.
    const response = await fetch(new URL("/fs" + current_path, url_base),
        {
            headers: {
                "Accept": "application/json"
            },
            credentials: "include"
        }
    );
    const data = await response.json();
    var new_children = [];
    var title = document.querySelector("title");
    title.textContent = current_path;
    var path = document.querySelector("#path");
    path.textContent = current_path;
    var template = document.querySelector('#row');

    if (editable === undefined) {
        const status = await fetch(new URL("/fs/", url_base),
            {
                method: "OPTIONS",
                credentials: "include"
            }
        );
        editable = status.headers.get("Access-Control-Allow-Methods").includes("DELETE");
        new_directory_name.disabled = !editable;
        files.disabled = !editable;
        if (!editable) {
            let usbwarning = document.querySelector("#usbwarning");
            usbwarning.style.display = "block";
        }
    }

    var dirCells = [];
    var dataCells = [];
    var index = 0;

    if (window.location.path != "/fs/") {
        var clone = template.content.cloneNode(true);
        var td = clone.querySelectorAll("td");
        td[0].textContent = "🗀";
        var path = clone.querySelector("a");
        let parent = new URL("..", "file://" + current_path);
        path.href = "#" + parent.pathname;
        path.textContent = "..";
        // Remove the delete button
        td[4].replaceChildren();

        var sortdata = {};
        sortdata.value = "..";
        sortdata.index = index;
        dirCells.push(sortdata);
        index += 1;

        new_children.push(clone);
    }

    for (const f of data) {
        // Clone the new row and insert it into the table
        var clone = template.content.cloneNode(true);
        var td = clone.querySelectorAll("td");
        var icon = "⬇";
        var file_path = current_path + f.name;
        let api_url = new URL("/fs" + file_path, url_base);
        let edit_url = "/edit/#" + file_path;
        if (f.directory) {
            file_path = "#" + file_path + "/";
            api_url += "/";
        } else {
            file_path = api_url;
        }

        if (f.directory) {
            icon = "🗀";
        } else if(f.name.endsWith(".txt") ||
                  f.name.endsWith(".py") ||
                  f.name.endsWith(".js") ||
                  f.name.endsWith(".json")) {
            icon = "🖹";
        } else if (f.name.endsWith(".html")) {
            icon = "🌐";
        }
        td[0].textContent = icon;
        td[1].textContent = f.file_size;
        var path = clone.querySelector("a");
        path.href = file_path;
        path.textContent = f.name;
        td[3].textContent = (new Date(f.modified_ns / 1000000)).toLocaleString();
        var delete_button = clone.querySelector("button.delete");
        delete_button.value = api_url;
        delete_button.disabled = !editable;
        delete_button.onclick = del;

        if (editable && !f.directory) {
            edit_url = new URL(edit_url, url_base);
            let edit_link = clone.querySelector(".edit_link");
            edit_link.href = edit_url
        }

        var dataCell = td[2];

        var sortdata = {};
        sortdata.value = dataCell.textContent.toLowerCase().trim();
        sortdata.index = index;
        if (!f.directory) {
            dataCells.push(sortdata);
            index += 1;
        } else {
            dirCells.push(sortdata);
            index += 1;
        }

        new_children.push(clone);
    }

    dirCells.sort(compareValues);
    dataCells.sort(compareValues);

    var tbody = document.querySelector("tbody");

    // remove rows
    while (tbody.firstChild) {
      tbody.removeChild(tbody.lastChild);
    }

    // add sorted rows
    for (var i = 0; i < dirCells.length; i += 1) {
      tbody.appendChild(new_children[dirCells[i].index]);
    }
    for (var i = 0; i < dataCells.length; i += 1) {
      tbody.appendChild(new_children[dataCells[i].index]);
    }
}

async function find_devices() {
    const version_response = await fetch("/cp/version.json");
    if (version_response.ok) {
        url_base = new URL("/", window.location).href;
    } else {
        // TODO: Remove this when we've settled things. It is only used when this file isn't hosted
        // by a CP device.
        const response = await fetch("http://circuitpython.local/cp/devices.json");
        let url = new URL("/", response.url);
        url_base = url.href;
        const data = await response.json();
    }
    refresh_list();
}

async function mkdir(e) {
    const response = await fetch(
        new URL("/fs" + current_path + new_directory_name.value + "/", url_base),
        {
            method: "PUT",
            headers: {
                'X-Timestamp': Date.now()
            }
        }
    );
    if (response.ok) {
        refresh_list();
        new_directory_name.value = "";
        mkdir_button.disabled = true;
    }
}

async function upload(e) {
    for (const file of files.files) {
        let file_path = new URL("/fs" + current_path + file.name, url_base);
        const response = await fetch(file_path,
            {
                method: "PUT",
                headers: {
                    'Content-Type': 'application/octet-stream',
                    'X-Timestamp': file.lastModified
                },
                body: file
            }
        )
        if (response.ok) {
            refresh_list();
            files.value = "";
            upload_button.disabled = true;
        }
    }
}

async function del(e) {
    let fn = new URL(e.target.value);
    var prompt = "Delete " + fn.pathname.substr(3);
    if (e.target.value.endsWith("/")) {
        prompt += " and all of its contents?";
    } else {
        prompt += "?";
    }
    if (confirm(prompt)) {
        const response = await fetch(e.target.value,
            {
                method: "DELETE"
            }
        )
        if (response.ok) {
            refresh_list();
        }
    }
}

find_devices();

let mkdir_button = document.getElementById("mkdir");
mkdir_button.onclick = mkdir;

let upload_button = document.getElementById("upload");
upload_button.onclick = upload;

upload_button.disabled = files.files.length == 0;

files.onchange = () => {
    upload_button.disabled = files.files.length == 0;
}

mkdir_button.disabled = new_directory_name.value.length == 0;

new_directory_name.oninput = () => {
    mkdir_button.disabled = new_directory_name.value.length == 0;
}

window.onhashchange = refresh_list;
<commit_msg>Sort json data rather than index of table data<commit_after>let new_directory_name = document.getElementById("name");
let files = document.getElementById("files");

var url_base = window.location;
var current_path;
var editable = undefined;

async function refresh_list() {

    function compareValues(a, b) {
        if (a.directory == b.directory && a.name.toLowerCase() === b.name.toLowerCase()) {
          return 0;
        } else {
          return a.directory.toString().substring(3,4)+a.name.toLowerCase() <
            b.directory.toString().substring(3,4)+b.name.toLowerCase() ? -1 : 1;
        }
    }

    current_path = window.location.hash.substr(1);
    if (current_path == "") {
        current_path = "/";
    }
    // Do the fetch first because the browser will prompt for credentials.
    const response = await fetch(new URL("/fs" + current_path, url_base),
        {
            headers: {
                "Accept": "application/json"
            },
            credentials: "include"
        }
    );
    const data = await response.json();
    var new_children = [];
    var title = document.querySelector("title");
    title.textContent = current_path;
    var path = document.querySelector("#path");
    path.textContent = current_path;
    var template = document.querySelector('#row');

    if (editable === undefined) {
        const status = await fetch(new URL("/fs/", url_base),
            {
                method: "OPTIONS",
                credentials: "include"
            }
        );
        editable = status.headers.get("Access-Control-Allow-Methods").includes("DELETE");
        new_directory_name.disabled = !editable;
        files.disabled = !editable;
        if (!editable) {
            let usbwarning = document.querySelector("#usbwarning");
            usbwarning.style.display = "block";
        }
    }

    if (window.location.path != "/fs/") {
        var clone = template.content.cloneNode(true);
        var td = clone.querySelectorAll("td");
        td[0].textContent = "🗀";
        var path = clone.querySelector("a");
        let parent = new URL("..", "file://" + current_path);
        path.href = "#" + parent.pathname;
        path.textContent = "..";
        // Remove the delete button
        td[4].replaceChildren();
        new_children.push(clone);
    }

    data.sort(compareValues);

    for (const f of data) {
        // Clone the new row and insert it into the table
        var clone = template.content.cloneNode(true);
        var td = clone.querySelectorAll("td");
        var icon = "⬇";
        var file_path = current_path + f.name;
        let api_url = new URL("/fs" + file_path, url_base);
        let edit_url = "/edit/#" + file_path;
        if (f.directory) {
            file_path = "#" + file_path + "/";
            api_url += "/";
        } else {
            file_path = api_url;
        }

        if (f.directory) {
            icon = "🗀";
        } else if(f.name.endsWith(".txt") ||
                  f.name.endsWith(".py") ||
                  f.name.endsWith(".js") ||
                  f.name.endsWith(".json")) {
            icon = "🖹";
        } else if (f.name.endsWith(".html")) {
            icon = "🌐";
        }
        td[0].textContent = icon;
        td[1].textContent = f.file_size;
        var path = clone.querySelector("a");
        path.href = file_path;
        path.textContent = f.name;
        td[3].textContent = (new Date(f.modified_ns / 1000000)).toLocaleString();
        var delete_button = clone.querySelector("button.delete");
        delete_button.value = api_url;
        delete_button.disabled = !editable;
        delete_button.onclick = del;

        if (editable && !f.directory) {
            edit_url = new URL(edit_url, url_base);
            let edit_link = clone.querySelector(".edit_link");
            edit_link.href = edit_url
        }

        new_children.push(clone);
    }
    var tbody = document.querySelector("tbody");
    tbody.replaceChildren(...new_children);
}

async function find_devices() {
    const version_response = await fetch("/cp/version.json");
    if (version_response.ok) {
        url_base = new URL("/", window.location).href;
    } else {
        // TODO: Remove this when we've settled things. It is only used when this file isn't hosted
        // by a CP device.
        const response = await fetch("http://circuitpython.local/cp/devices.json");
        let url = new URL("/", response.url);
        url_base = url.href;
        const data = await response.json();
    }
    refresh_list();
}

async function mkdir(e) {
    const response = await fetch(
        new URL("/fs" + current_path + new_directory_name.value + "/", url_base),
        {
            method: "PUT",
            headers: {
                'X-Timestamp': Date.now()
            }
        }
    );
    if (response.ok) {
        refresh_list();
        new_directory_name.value = "";
        mkdir_button.disabled = true;
    }
}

async function upload(e) {
    for (const file of files.files) {
        let file_path = new URL("/fs" + current_path + file.name, url_base);
        const response = await fetch(file_path,
            {
                method: "PUT",
                headers: {
                    'Content-Type': 'application/octet-stream',
                    'X-Timestamp': file.lastModified
                },
                body: file
            }
        )
        if (response.ok) {
            refresh_list();
            files.value = "";
            upload_button.disabled = true;
        }
    }
}

async function del(e) {
    let fn = new URL(e.target.value);
    var prompt = "Delete " + fn.pathname.substr(3);
    if (e.target.value.endsWith("/")) {
        prompt += " and all of its contents?";
    } else {
        prompt += "?";
    }
    if (confirm(prompt)) {
        const response = await fetch(e.target.value,
            {
                method: "DELETE"
            }
        )
        if (response.ok) {
            refresh_list();
        }
    }
}

find_devices();

let mkdir_button = document.getElementById("mkdir");
mkdir_button.onclick = mkdir;

let upload_button = document.getElementById("upload");
upload_button.onclick = upload;

upload_button.disabled = files.files.length == 0;

files.onchange = () => {
    upload_button.disabled = files.files.length == 0;
}

mkdir_button.disabled = new_directory_name.value.length == 0;

new_directory_name.oninput = () => {
    mkdir_button.disabled = new_directory_name.value.length == 0;
}

window.onhashchange = refresh_list;
<|endoftext|>


<commit_before>//= require ./fixtures

describe('RecordService', function() {
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var RecordService = window.shared.RecordService;
  var SpecSugar = window.shared.SpecSugar;
  var Fixtures = window.shared.Fixtures;
  var eventNotesFixture = [{"id":4,"student_id":24,"educator_id":1,"event_note_type_id":1,"text":"cool!","recorded_at":"2016-02-15T18:42:45.937Z","created_at":"2016-02-15T18:42:45.943Z","updated_at":"2016-02-15T18:42:45.943Z"},{"id":5,"student_id":24,"educator_id":1,"event_note_type_id":3,"text":"this tiss thie this tiss thie this tiss thie this tiss thie this tiss thie this tiss thie this tiss thie ","recorded_at":"2016-02-15T20:01:02.086Z","created_at":"2016-02-15T20:01:02.087Z","updated_at":"2016-02-15T20:01:02.087Z"},{"id":6,"student_id":24,"educator_id":1,"event_note_type_id":5,"text":"okay!","recorded_at":"2016-02-15T20:03:28.232Z","created_at":"2016-02-15T20:03:28.233Z","updated_at":"2016-02-15T20:03:28.233Z"},{"id":7,"student_id":24,"educator_id":1,"event_note_type_id":2,"text":"yep :)","recorded_at":"2016-02-15T20:03:36.699Z","created_at":"2016-02-15T20:03:36.700Z","updated_at":"2016-02-15T20:03:36.700Z"}];

  var helpers = {
    renderInto: function(el, props) {
      var mergedProps = merge(props || {}, {
        studentFirstName: 'Tamyra',
        serviceTypesIndex: {},
        educatorsIndex: {},
        nowMoment: Fixtures.nowMoment,
        currentEducator: Fixtures.currentEducator,
        onSave: jasmine.createSpy('onSave'),
        onCancel: jasmine.createSpy('onCancel'),
        requestState: null
      });
      return ReactDOM.render(createEl(RecordService, mergedProps), el);
    },

    serviceTypes: function(el) {
      return $(el).find('.btn.service-type').toArray().map(function(el) {
        return $.trim(el.innerText);
      });
    }
  };

  SpecSugar.withTestEl('high-level integration tests', function() {
    it('renders dialog for recording services', function() {
      var el = this.testEl;
      helpers.renderInto(el);

      expect(el).toContainText('Which service?');
      expect(helpers.serviceTypes(el)).toEqual([
        'Counseling, in-house',
        'Counseling, outside',
         'Reading intervention',
         'Math intervention',
         'Attendance Officer',
         'Attendance Contract',
         'Behavior Contract'
      ]);

      expect(el).toContainText('Who is working with Tamyra?');
      expect($(el).find('.Select').length).toEqual(1);
      expect(el).toContainText('When did they start?');
      expect($(el).find('.datepicker.hasDatepicker').length).toEqual(1);
      expect($(el).find('.btn.save').length).toEqual(1);
      expect($(el).find('.btn.cancel').length).toEqual(1);
    });
  });
});<commit_msg>Remove unneeded imports<commit_after>//= require ./fixtures

describe('RecordService', function() {
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var RecordService = window.shared.RecordService;
  var SpecSugar = window.shared.SpecSugar;
  var Fixtures = window.shared.Fixtures;

  var helpers = {
    renderInto: function(el, props) {
      var mergedProps = merge(props || {}, {
        studentFirstName: 'Tamyra',
        serviceTypesIndex: {},
        educatorsIndex: {},
        nowMoment: Fixtures.nowMoment,
        currentEducator: Fixtures.currentEducator,
        onSave: jasmine.createSpy('onSave'),
        onCancel: jasmine.createSpy('onCancel'),
        requestState: null
      });
      return ReactDOM.render(createEl(RecordService, mergedProps), el);
    },

    serviceTypes: function(el) {
      return $(el).find('.btn.service-type').toArray().map(function(el) {
        return $.trim(el.innerText);
      });
    }
  };

  SpecSugar.withTestEl('high-level integration tests', function() {
    it('renders dialog for recording services', function() {
      var el = this.testEl;
      helpers.renderInto(el);

      expect(el).toContainText('Which service?');
      expect(helpers.serviceTypes(el)).toEqual([
        'Counseling, in-house',
        'Counseling, outside',
         'Reading intervention',
         'Math intervention',
         'Attendance Officer',
         'Attendance Contract',
         'Behavior Contract'
      ]);

      expect(el).toContainText('Who is working with Tamyra?');
      expect($(el).find('.Select').length).toEqual(1);
      expect(el).toContainText('When did they start?');
      expect($(el).find('.datepicker.hasDatepicker').length).toEqual(1);
      expect($(el).find('.btn.save').length).toEqual(1);
      expect($(el).find('.btn.cancel').length).toEqual(1);
    });
  });
});<|endoftext|>


<commit_before>var do_encrypt_selectors = [
   "._552m",
    "._1rv"
];

var textareaUsernameGetters = {
    '_552m' : function($textarea) {
        var $anchor = $textarea.closest('.fbNubFlyoutFooter')
                    .siblings('.titlebar').find('.titlebarText');
        if ($anchor.hasClass('noLink')) {
            var userInputs = $anchor.closest('.fbNubFlyoutTitlebar')
                .siblings('.fbNubFlyoutHeader').find('input[name="participants[]"]');
            return userInputs.map(function(index, elm) {
                return elm.value;
            });
        }
        return textareaUsernameGetters.fromAnchor($anchor);
    },
    '_1rv' : function() {
        var $anchor = $('#webMessengerHeaderName').find('a');
        return textareaUsernameGetters.fromAnchor($anchor);
    },
    'fromAnchor' : function($anchor) {
        var user_id = getURLParameter($anchor.attr('href'), 'id');
        if (user_id !== "null") return user_id;

        var friendUrl = $anchor.attr('href').split('/');
        return [friendUrl[friendUrl.length - 1]];
    }
}

$(function() {
    makeOverlays();
});

function makeOverlays() {
    $('textarea').each(function() {
        if ($(this).data('checkedOverlay')) {
            return;
        }

        var classes = $(this).attr('class').split(' ');
        var encryptClasses = classes.filter(function(elm) {
            return do_encrypt_selectors.indexOf('.' + elm) >= 0;
        });
        if (encryptClasses.length == 0) {
            $(this).data('checkedOverlay', true);
            return;
        }
        $(this).data('checkedOverlay', true);
        $(this).data('usernames', textareaUsernameGetters[encryptClasses[0]]($(this)) );

        //need a function to check if will_encrypt for usernames
        makeOverlay($(this));

    });
}

function makeOverlay($textarea) {
    if (!$textarea.is(':visible')) {
        return;
    }
    var $fakeblockArea = $textarea.clone();
    // $fakeblockArea.removeClass();
    // $fakeblockArea.removeAttr("name");
    // $fakeblockArea.removeAttr("role");
    // $fakeblockArea.removeAttr("onkeydown");
    // $fakeblockArea.removeAttr("rows");
    // $fakeblockArea.removeAttr("placeholder");
    // $fakeblockArea.removeAttr("aria-controls");
    // $fakeblockArea.removeAttr("areia-describedby");
    // $fakeblockArea.removeAttr("areia-owns");
    // $fakeblockArea.removeAttr("aria-label");
    $textarea.after($fakeblockArea).hide();

    $fakeblockArea.data('encryptedArea', $textarea);

    $fakeblockArea.keyup(function() {
        encryptHandler($(this));
        return true
    });
    var firstInput = $textarea.val();
    encryptHandler($fakeblockArea, firstInput);
    $fakeblockArea.focus();
    $fakeblockArea.val(firstInput);
}

function requestEncrypt($encryptedArea, message) {
    sendMessage({
        "action" : "encrypt",
        "message" : message,
        "usernames" : $encryptedArea.data('usernames')
    }, function(response) {
        var res = $.parseJSON(response).res;
        var msg;
        if (typeof res === "string") {
            msg = res;
        } else {
            msg = "|fakeblock|" +
                JSON.stringify(res) +
                "|endfakeblock|"
        }
        $encryptedArea.val(msg);
    });
}

function encryptHandler($unencryptedArea, message) {
    // debugger
    var message = (message) ? message : $unencryptedArea.val();

    //send message to encrypt to josh
    encrypted = requestEncrypt($unencryptedArea.data('encryptedArea'),
        message);
}

function getURLParameter(url, name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(url)||[,null])[1]
    );
}
<commit_msg>progss<commit_after>var do_encrypt_selectors = [
   "._552m",
    "._1rv"
];

var textareaUsernameGetters = {
    '_552m' : function($textarea) {
        var $anchor = $textarea.closest('.fbNubFlyoutFooter')
                    .siblings('.titlebar').find('.titlebarText');
        if ($anchor.hasClass('noLink')) {
            var userInputs = $anchor.closest('.fbNubFlyoutTitlebar')
                .siblings('.fbNubFlyoutHeader').find('input[name="participants[]"]');
            return userInputs.map(function(index, elm) {
                return elm.value;
            });
        }
        return textareaUsernameGetters.fromAnchor($anchor);
    },
    '_1rv' : function() {
        var $anchor = $('#webMessengerHeaderName').find('a');
        return textareaUsernameGetters.fromAnchor($anchor);
    },
    'fromAnchor' : function($anchor) {
        var user_id = getURLParameter($anchor.attr('href'), 'id');
        if (user_id !== "null") return user_id;

        var friendUrl = $anchor.attr('href').split('/');
        return [friendUrl[friendUrl.length - 1]];
    }
}

$(function() {
    makeOverlays();
});

function makeOverlays() {
    $('textarea').each(function() {
        if ($(this).data('checkedOverlay')) {
            return;
        }

        var classes = $(this).attr('class').split(' ');
        var encryptClasses = classes.filter(function(elm) {
            return do_encrypt_selectors.indexOf('.' + elm) >= 0;
        });
        if (encryptClasses.length == 0) {
            $(this).data('checkedOverlay', true);
            return;
        }
        $(this).data('checkedOverlay', true);
        $(this).data('usernames', textareaUsernameGetters[encryptClasses[0]]($(this)) );

        //need a function to check if will_encrypt for usernames
        makeOverlay($(this));

    });
}

function makeOverlay($textarea) {
    if (!$textarea.is(':visible')) {
        return;
    }
    var $fakeblockArea = $textarea.clone();
    // $fakeblockArea.removeClass();
    // $fakeblockArea.removeAttr("name");
    // $fakeblockArea.removeAttr("role");
    // $fakeblockArea.removeAttr("onkeydown");
    // $fakeblockArea.removeAttr("rows");
    // $fakeblockArea.removeAttr("placeholder");
    // $fakeblockArea.removeAttr("aria-controls");
    // $fakeblockArea.removeAttr("areia-describedby");
    // $fakeblockArea.removeAttr("areia-owns");
    // $fakeblockArea.removeAttr("aria-label");
    // $textarea.after($fakeblockArea)//.hide();
    // $textarea.trigger("keyup").hide();
    $("body").append($fakeblockArea)
    $fakeblockArea.data('encryptedArea', $textarea);

    $fakeblockArea.keyup(function() {
        encryptHandler($(this));
    });
    // var firstInput = $textarea.val();
    // encryptHandler($fakeblockArea, firstInput);
    // $fakeblockArea.focus();
    // $fakeblockArea.val(firstInput);
}

function requestEncrypt($encryptedArea, message) {
    sendMessage({
        "action" : "encrypt",
        "message" : message,
        "usernames" : $encryptedArea.data('usernames')
    }, function(response) {
        var res = $.parseJSON(response).res;
        var msg;
        $encryptedArea.focus().trigger("keydown");
        if (typeof res === "string") {
            msg = res;
        } else {
            msg = "|fakeblock|" +
                JSON.stringify(res) +
                "|endfakeblock|"
        }
        $encryptedArea.val(msg);
    });
}

function encryptHandler($unencryptedArea, message) {
    // debugger
    var message = (message) ? message : $unencryptedArea.val();

    //send message to encrypt to josh
    encrypted = requestEncrypt($unencryptedArea.data('encryptedArea'),
        message);
}

function getURLParameter(url, name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(url)||[,null])[1]
    );
}
<|endoftext|>


<commit_before>import { makeStyles } from '@material-ui/core'
import * as R from 'ramda'
import React from 'react'

import Chip from 'src/components/Chip'
import { ActionButton } from 'src/components/buttons'
import { P, Label2 } from 'src/components/typography'
import { ReactComponent as CloseIcon } from 'src/styling/icons/action/close/zodiac.svg'
import { ReactComponent as FilterIcon } from 'src/styling/icons/button/filter/white.svg'
import { ReactComponent as ReverseFilterIcon } from 'src/styling/icons/button/filter/zodiac.svg'

import { chipStyles, styles } from './SearchFilter.styles'

const useChipStyles = makeStyles(chipStyles)
const useStyles = makeStyles(styles)

const capitalize = R.converge(R.concat(), [
  R.compose(R.toUpper, R.head),
  R.tail
])

const SearchFilter = ({ filters, onFilterDelete, setFilters, entries }) => {
  const chipClasses = useChipStyles()
  const classes = useStyles()

  return (
    <>

{'Filters:'}

          {filters.map((f, idx) => (
            <Chip
              key={idx}
              classes={chipClasses}
              label={`${capitalize(f.type)}: ${f.value}`}
              onDelete={() => onFilterDelete(f)}
              deleteIcon={<CloseIcon className={classes.button} />}
            />
          ))}

          {entries && (
            <Label2 className={classes.entries}>{`${entries} entries`}</Label2>
          )}
          <ActionButton
            color="secondary"
            Icon={ReverseFilterIcon}
            InverseIcon={FilterIcon}
            className={classes.deleteButton}
            onClick={() => setFilters([])}>
            Delete filters
          </ActionButton>

    </>
  )
}

export default SearchFilter
<commit_msg>fix: entries label weight, use string utils func instead of custom<commit_after>import { makeStyles } from '@material-ui/core'
import React from 'react'

import Chip from 'src/components/Chip'
import { ActionButton } from 'src/components/buttons'
import { P, Label3 } from 'src/components/typography'
import { ReactComponent as CloseIcon } from 'src/styling/icons/action/close/zodiac.svg'
import { ReactComponent as FilterIcon } from 'src/styling/icons/button/filter/white.svg'
import { ReactComponent as ReverseFilterIcon } from 'src/styling/icons/button/filter/zodiac.svg'
import { onlyFirstToUpper } from 'src/utils/string'

import { chipStyles, styles } from './SearchFilter.styles'

const useChipStyles = makeStyles(chipStyles)
const useStyles = makeStyles(styles)

const SearchFilter = ({ filters, onFilterDelete, setFilters, entries }) => {
  const chipClasses = useChipStyles()
  const classes = useStyles()

  return (
    <>

{'Filters:'}

          {filters.map((f, idx) => (
            <Chip
              key={idx}
              classes={chipClasses}
              label={`${onlyFirstToUpper(f.type)}: ${f.value}`}
              onDelete={() => onFilterDelete(f)}
              deleteIcon={<CloseIcon className={classes.button} />}
            />
          ))}

          {
            <Label3 className={classes.entries}>{`${entries ??
              0} entries`}</Label3>
          }
          <ActionButton
            color="secondary"
            Icon={ReverseFilterIcon}
            InverseIcon={FilterIcon}
            className={classes.deleteButton}
            onClick={() => setFilters([])}>
            Delete filters
          </ActionButton>

    </>
  )
}

export default SearchFilter
<|endoftext|>


<commit_before>var http = require('http');
var net = require('net');
var config = require('../lib/config');
var util = require('../lib/util');
var zlib = require('../../../lib/util/zlib');
var getSender = require('ws-parser').getSender;
var hparser = require('hparser');

var formatHeaders = hparser.formatHeaders;
var getRawHeaders = hparser.getRawHeaders;
var STATUS_CODE_RE = /^[^\s]+\s+(\d+)/i;
var MAX_LENGTH = 1024 * 512;

function parseHeaders(headers, rawHeaderNames) {
  if (!headers || typeof headers != 'string') {
    return {};
  }

  var reqHeaders = util.parseRawJson(headers);
  if (reqHeaders) {
    return util.lowerCaseify(reqHeaders, rawHeaderNames);
  }

  return util.parseHeaders(headers, rawHeaderNames);
}

function getMethod(method) {
  if (typeof method !== 'string') {
    return 'GET';
  }
  return method.toUpperCase();
}

function isWebSocket(options) {
  var p = options.protocol;
  return p === 'ws:' || p === 'wss:';
}

var crypto = require('crypto');
function isConnect(options) {
  if (options.method === 'CONNECT') {
    return true;
  }
  var p = options.protocol;
  return p === 'connect:' || p === 'socket:' || p === 'tunnel:' || p === 'conn:';
}

function drain(socket) {
  socket.on('error', util.noop);
  socket.on('data', util.noop);
}

function handleConnect(options, cb) {
  options.headers['x-whistle-policy'] = 'tunnel';
  config.connect({
    host: options.hostname,
    port: options.port,
    proxyHost: '127.0.0.1',
    proxyPort: config.port,
    headers: options.headers
  }, function(socket) {
    drain(socket);
    var data = util.toBuffer(options.body, getCharset(options.headers));
    if (data && data.length) {
      socket.write(data);
    }
    cb && cb();
  }).on('error', cb || util.noop);
}

function getReqRaw(options) {
  var headers = options.headers;
  var statusLine = options.method +' ' + (options.path || '/') +' ' + 'HTTP/1.1';
  var raw = [statusLine, getRawHeaders(headers)];
  return raw.join('\r\n') + '\r\n\r\n';
}

function handleWebSocket(options, cb) {
  if (options.protocol === 'https:' || options.protocol === 'wss:') {
    options.headers[config.HTTPS_FIELD] = 1;
  }
  var binary = !!options.headers['x-whistle-frame-binary'];
  delete options.headers['x-whistle-frame-binary'];
  var socket = net.connect(config.port, '127.0.0.1', function() {
    socket.write(getReqRaw(options));
    var handleResponse = function(resData) {
      resData = resData + '';
      var index = resData.indexOf('\r\n\r\n') !== -1;
      if (index !== -1) {
        socket.removeListener('data', handleResponse);
        socket.headers = parseHeaders(resData.slice(0, index));
        var sender = getSender(socket);
        var data = util.toBuffer(options.body, getCharset(socket.headers) || getCharset(options.headers));
        if (data && data.length) {
          sender.send(data, {
            mask: true,
            binary: binary
          }, util.noop);
        }
      }
      if (cb) {
        var statusCode = 0;
        if (STATUS_CODE_RE.test(resData)) {
          statusCode = RegExp.$1;
        }
        cb(null, {
          statusCode: statusCode,
          headers: socket.headers || {},
          body: ''
        });
      }
    };
    socket.on('data', handleResponse);
  });
  if (cb) {
    socket.on('error', cb);
  } else {
    drain(socket);
  }
}

function handleHttp(options, cb) {
  if (options.protocol === 'https:') {
    options.headers[config.HTTPS_FIELD] = 1;
  }
  options.protocol = null;
  options.hostname = null;
  options.host = '127.0.0.1';
  options.port = config.port;
  http.request(options, function(res) {
    if (cb) {
      res.on('error', cb);
      var buffer;
      res.on('data', function(data) {
        if (buffer !== null) {
          buffer = buffer ? Buffer.concat([buffer, data]) : data;
          if (buffer.length > MAX_LENGTH) {
            buffer = null;
          }
        }
      });
      res.on('end', function() {
        zlib.unzip(res.headers['content-encoding'], buffer, function(err, body) {
          cb(null, {
            statusCode: res.statusCode,
            headers: res.headers,
            body: err ? err.stack : util.decodeBuffer(body)
          });
        });
      });
    } else {
      drain(res);
    }
  }).on('error', cb || util.noop).end(options.body);
}

function getCharset(headers) {
  var charset = headers && headers['x-whistle-charset'];
  return charset || util.getCharset(headers['content-type']);
}

module.exports = function(req, res) {
  var fullUrl = req.body.url;
  if (!fullUrl || typeof fullUrl !== 'string') {
    return res.json({ec: 0});
  }

  fullUrl = util.encodeNonAsciiChar(fullUrl.replace(/#.*$/, ''));
  var options = util.parseUrl(util.setProtocol(fullUrl));
  if (!options.host) {
    return res.json({ec: 0});
  }

  var rawHeaderNames = {};
  var headers = parseHeaders(req.body.headers, rawHeaderNames);
  delete headers[config.WEBUI_HEAD];
  if (!headers['user-agent']) {
    headers['user-agent'] = config.PROXY_UA;
  }
  headers[config.WHISTLE_REQ_FROM_HEADER] = 'W2COMPOSER';
  headers.host = options.host;
  var clientIp = util.getClientIp(req);
  if (!util.isLocalAddress(clientIp)) {
    headers[config.CLIENT_IP_HEAD] = clientIp;
  }
  headers[config.CLIENT_PORT_HEAD] = util.getClientPort(req);
  options.method = getMethod(req.body.method);

  var isConn = isConnect(options);
  var isWs = !isConn && (isWebSocket(options)
    || (/upgrade/i.test(headers.connection) && /websocket/i.test(headers.upgrade)));
  if (isWs) {
    headers.connection = 'Upgrade';
    headers.upgrade = 'websocket';
    headers['sec-websocket-version'] = 13;
    headers['sec-websocket-key'] = crypto.randomBytes(16).toString('base64');
  } else {
    headers.connection = 'close';
    delete headers.upgrade;
  }

  var base64 = req.body.base64;
  var body = base64 || req.body.body;
  if (body && (isWs || isConn || util.hasRequestBody(options))) {
    body = util.toBuffer(body, base64 ? 'base64' : getCharset(headers));
    options.body = body;
    if ('content-length' in headers) {
      if (isWs || isConn) {
        delete headers['content-length'];
      } else {
        headers['content-length'] = body ? body.length : 0;
      }
    }
  } else {
    delete headers['content-length'];
  }
  delete headers['content-encoding'];
  options.headers = formatHeaders(headers, rawHeaderNames);
  var done;
  var handleResponse = req.query.needResponse ? function(err, data) {
    if (done) {
      return;
    }
    done = true;
    if (err) {
      res.json({ec: 2, em: err.stack});
      return;
    }
    res.json({ec: 0, em: 'success', res: data});
  } : null;
  if (isWs) {
    options.method = 'GET';
    if (handleResponse) {
      return handleWebSocket(options, handleResponse);
    }
    handleWebSocket(options);
  } else if (isConn) {
    if (handleResponse) {
      return handleConnect(options, handleResponse);
    }
    handleConnect(options);
  } else  {
    if (handleResponse) {
      return handleHttp(options, handleResponse);
    }
    handleHttp(options);
  }

  res.json({ec: 0, em: 'success'});
};
<commit_msg>refactor: Composer<commit_after>var http = require('http');
var net = require('net');
var config = require('../lib/config');
var util = require('../lib/util');
var zlib = require('../../../lib/util/zlib');
var getSender = require('ws-parser').getSender;
var hparser = require('hparser');

var formatHeaders = hparser.formatHeaders;
var getRawHeaders = hparser.getRawHeaders;
var STATUS_CODE_RE = /^[^\s]+\s+(\d+)/i;
var MAX_LENGTH = 1024 * 512;

function parseHeaders(headers, rawHeaderNames) {
  if (!headers || typeof headers != 'string') {
    return {};
  }

  var reqHeaders = util.parseRawJson(headers);
  if (reqHeaders) {
    return util.lowerCaseify(reqHeaders, rawHeaderNames);
  }

  return util.parseHeaders(headers, rawHeaderNames);
}

function getMethod(method) {
  if (typeof method !== 'string') {
    return 'GET';
  }
  return method.toUpperCase();
}

function isWebSocket(options) {
  var p = options.protocol;
  return p === 'ws:' || p === 'wss:';
}

var crypto = require('crypto');
function isConnect(options) {
  if (options.method === 'CONNECT') {
    return true;
  }
  var p = options.protocol;
  return p === 'connect:' || p === 'socket:' || p === 'tunnel:' || p === 'conn:';
}

function drain(socket) {
  socket.on('error', util.noop);
  socket.on('data', util.noop);
}

function handleConnect(options, cb) {
  options.headers['x-whistle-policy'] = 'tunnel';
  config.connect({
    host: options.hostname,
    port: options.port,
    proxyHost: '127.0.0.1',
    proxyPort: config.port,
    headers: options.headers
  }, function(socket) {
    drain(socket);
    var data = util.toBuffer(options.body, getCharset(options.headers));
    if (data && data.length) {
      socket.write(data);
    }
    cb && cb();
  }).on('error', cb || util.noop);
}

function getReqRaw(options) {
  var headers = options.headers;
  var statusLine = options.method +' ' + (options.path || '/') +' ' + 'HTTP/1.1';
  var raw = [statusLine, getRawHeaders(headers)];
  return raw.join('\r\n') + '\r\n\r\n';
}

function handleWebSocket(options, cb) {
  if (options.protocol === 'https:' || options.protocol === 'wss:') {
    options.headers[config.HTTPS_FIELD] = 1;
  }
  var binary = !!options.headers['x-whistle-frame-binary'];
  delete options.headers['x-whistle-frame-binary'];
  var socket = net.connect(config.port, '127.0.0.1', function() {
    socket.write(getReqRaw(options));
    var handleResponse = function(resData) {
      resData = resData + '';
      var index = resData.indexOf('\r\n\r\n') !== -1;
      if (index !== -1) {
        socket.removeListener('data', handleResponse);
        socket.headers = parseHeaders(resData.slice(0, index));
        var sender = getSender(socket);
        var data = util.toBuffer(options.body, getCharset(socket.headers) || getCharset(options.headers));
        if (data && data.length) {
          sender.send(data, {
            mask: true,
            binary: binary
          }, util.noop);
        }
      }
      if (cb) {
        var statusCode = 0;
        if (STATUS_CODE_RE.test(resData)) {
          statusCode = parseInt(RegExp.$1, 10);
        }
        cb(null, {
          statusCode: statusCode,
          headers: socket.headers || {},
          body: ''
        });
      }
    };
    socket.on('data', handleResponse);
  });
  if (cb) {
    socket.on('error', cb);
  } else {
    drain(socket);
  }
}

function handleHttp(options, cb) {
  if (options.protocol === 'https:') {
    options.headers[config.HTTPS_FIELD] = 1;
  }
  options.protocol = null;
  options.hostname = null;
  options.host = '127.0.0.1';
  options.port = config.port;
  http.request(options, function(res) {
    if (cb) {
      res.on('error', cb);
      var buffer;
      res.on('data', function(data) {
        if (buffer !== null) {
          buffer = buffer ? Buffer.concat([buffer, data]) : data;
          if (buffer.length > MAX_LENGTH) {
            buffer = null;
          }
        }
      });
      res.on('end', function() {
        zlib.unzip(res.headers['content-encoding'], buffer, function(err, body) {
          cb(null, {
            statusCode: res.statusCode,
            headers: res.headers,
            body: err ? err.stack : util.decodeBuffer(body)
          });
        });
      });
    } else {
      drain(res);
    }
  }).on('error', cb || util.noop).end(options.body);
}

function getCharset(headers) {
  var charset = headers && headers['x-whistle-charset'];
  return charset || util.getCharset(headers['content-type']);
}

module.exports = function(req, res) {
  var fullUrl = req.body.url;
  if (!fullUrl || typeof fullUrl !== 'string') {
    return res.json({ec: 0});
  }

  fullUrl = util.encodeNonAsciiChar(fullUrl.replace(/#.*$/, ''));
  var options = util.parseUrl(util.setProtocol(fullUrl));
  if (!options.host) {
    return res.json({ec: 0});
  }

  var rawHeaderNames = {};
  var headers = parseHeaders(req.body.headers, rawHeaderNames);
  delete headers[config.WEBUI_HEAD];
  if (!headers['user-agent']) {
    headers['user-agent'] = config.PROXY_UA;
  }
  headers[config.WHISTLE_REQ_FROM_HEADER] = 'W2COMPOSER';
  headers.host = options.host;
  var clientIp = util.getClientIp(req);
  if (!util.isLocalAddress(clientIp)) {
    headers[config.CLIENT_IP_HEAD] = clientIp;
  }
  headers[config.CLIENT_PORT_HEAD] = util.getClientPort(req);
  options.method = getMethod(req.body.method);

  var isConn = isConnect(options);
  var isWs = !isConn && (isWebSocket(options)
    || (/upgrade/i.test(headers.connection) && /websocket/i.test(headers.upgrade)));
  if (isWs) {
    headers.connection = 'Upgrade';
    headers.upgrade = 'websocket';
    headers['sec-websocket-version'] = 13;
    headers['sec-websocket-key'] = crypto.randomBytes(16).toString('base64');
  } else {
    headers.connection = 'close';
    delete headers.upgrade;
  }

  var base64 = req.body.base64;
  var body = base64 || req.body.body;
  if (body && (isWs || isConn || util.hasRequestBody(options))) {
    body = util.toBuffer(body, base64 ? 'base64' : getCharset(headers));
    options.body = body;
    if ('content-length' in headers) {
      if (isWs || isConn) {
        delete headers['content-length'];
      } else {
        headers['content-length'] = body ? body.length : 0;
      }
    }
  } else {
    delete headers['content-length'];
  }
  delete headers['content-encoding'];
  options.headers = formatHeaders(headers, rawHeaderNames);
  var done;
  var handleResponse = req.query.needResponse ? function(err, data) {
    if (done) {
      return;
    }
    done = true;
    if (err) {
      res.json({ec: 2, em: err.stack});
      return;
    }
    res.json({ec: 0, em: 'success', res: data});
  } : null;
  if (isWs) {
    options.method = 'GET';
    if (handleResponse) {
      return handleWebSocket(options, handleResponse);
    }
    handleWebSocket(options);
  } else if (isConn) {
    if (handleResponse) {
      return handleConnect(options, handleResponse);
    }
    handleConnect(options);
  } else  {
    if (handleResponse) {
      return handleHttp(options, handleResponse);
    }
    handleHttp(options);
  }

  res.json({ec: 0, em: 'success'});
};
<|endoftext|>


<commit_before>"use strict";

$(function () {

  get('/bots/for/' + Screen_Name.screen_name(), function (err, result) {
    if (err) {
      log('Error in /bots: ', err);
      return;
    }

    WWW_Applet.run_these(result.bots);
  });

}); // ==== jquery on dom ready

// ================================================================
// ================== WWW_Applet ==================================
// ================================================================

var WWW_Applet = function () { };

WWW_Applet.run_these = function (list) {
  _.each(list, function (o) {
    log("Running WWW applet: ", o.screen_name)
    if (o.o_code.life)
      WWW_Applet.run(o, o.o_code.life);
    else
      log("Skipping applet because life property not found.", o);
  });
};

WWW_Applet.Whitespace = /\s+/ig;
WWW_Applet.INVALID_CHARS = /[^a-zA-Z0-9]+/g;

WWW_Applet.canonize_function_name = function (str) {
  if (!_.isString(str))
    return str;
  return $.trim(str.toLowerCase().replace(WWW_Applet.Whitespace, ' '));
};

WWW_Applet.run = function (meta, o) {
  var a    = new WWW_Applet();
  a.meta   = meta;
  a.applet = o;
  a.stack  = [];
  a.dom_ns_string = a.meta.screen_name.replace(WWW_Applet.INVALID_CHARS, '_');
  a.run();
};

// ================================================================
// ================== "Instance" Methods ==========================
// ================================================================

WWW_Applet.prototype.quit  = function (str, val) {
  var me = this;
  log(me.meta.screen_name, ' is quitting because ', str, val);
};

WWW_Applet.prototype.run = function () {
  var me = this;
  var cmds = me.applet.slice();
  while (cmds.length) {
    var call = WWW_Applet.canonize_function_name(cmds.shift());
    var args = cmds.shift();
    if (!_.isString(call))
      return me.quit("not a function name:", call);
    if (!WWW_Applet.FUNC_NAMES[call])
      return me.quit('function not found:', call);
    if (!_.isArray(args))
      return me.quit("not arguments:", args);
    WWW_Applet.FUNC_NAMES[call].apply(me, args);
  }
};

WWW_Applet.prototype.dom_ns = function (str) {
  var me = this;
  if (str === '#Sidebar')
    return str;
  return str.replace('#', '#' + me.dom_ns_string + '_');
};

WWW_Applet.prototype.dom_by_id = function (str) {
  var me = this;
  return $(me.dom_ns(str));
};

WWW_Applet.FUNC_NAMES = {};

function define(str, func) {
  WWW_Applet.FUNC_NAMES[str] = func;
  return WWW_Applet;
}

define("box", function (id) {
  var me = this;
  me.stack.push(me.dom_by_id(id));
  return me;
});

define('create box at top',  function (id) {
  var me = this;
  var box = $('
');
  box.attr('id', me.dom_ns(id).replace('#', ''));
  var last = _.last(me.stack);
  me.stack.push(box);
  last.prepend(box);

  return me;
});

define('list', function () {
  var me = this;
  me.stack.push(_.toArray(arguments));
  return me;
});

define('random item', function () {
  var me = this;
  var list = _.last(me.stack);
  var item = list[Math.floor(Math.random()*list.length)];
  me.stack.push(item);
  return me;
});

define('is text of', function (id) {
  var me = this;
  var ele = $(me.dom_ns(id));

  ele.text(_.last(me.stack));
  me.stack.push(ele);
  return me;
});

<commit_msg>Added: css attr sanitization, css attr setting, padding.<commit_after>"use strict";

$(function () {

  get('/bots/for/' + Screen_Name.screen_name(), function (err, result) {
    if (err) {
      log('Error in /bots: ', err);
      return;
    }

    WWW_Applet.run_these(result.bots);
  });

}); // ==== jquery on dom ready

// ================================================================
// ================== WWW_Applet ==================================
// ================================================================

var WWW_Applet = function () { };

WWW_Applet.run_these = function (list) {
  _.each(list, function (o) {
    log("Running WWW applet: ", o.screen_name)
    if (o.o_code.life)
      WWW_Applet.run(o, o.o_code.life);
    else
      log("Skipping applet because life property not found.", o);
  });
};

WWW_Applet.Whitespace = /\s+/ig;
WWW_Applet.INVALID_CHARS = /[^a-zA-Z0-9]+/g;

WWW_Applet.canonize_function_name = function (str) {
  if (!_.isString(str))
    return str;
  return $.trim(str.toLowerCase().replace(WWW_Applet.Whitespace, ' '));
};

WWW_Applet.run = function (meta, o) {
  var a    = new WWW_Applet();
  a.meta   = meta;
  a.applet = o;
  a.stack  = [];
  a.dom_ns_string = a.meta.screen_name.replace(WWW_Applet.INVALID_CHARS, '_');
  a.run();
};

WWW_Applet.FUNC_NAMES = {};

// ================================================================
// ================== Helpers =====================================
// ================================================================

function define(str, func) {
  WWW_Applet.FUNC_NAMES[str] = func;
  return WWW_Applet;
}

WWW_Applet.INVALID_CSS_CHARS = /[^a-zA-Z0-9\#\_\ ]+/ig;

function css_attr(str) {
  return str.replace(WWW_Applet.INVALID_CSS_CHARS, '');
}

function css(ele, str, val) {
  return $(ele).css(str, css_attr(val));
}

// ================================================================
// ================== "Instance" Methods ==========================
// ================================================================

WWW_Applet.prototype.quit  = function (str, val) {
  var me = this;
  log(me.meta.screen_name, ' is quitting because ', str, val);
};

WWW_Applet.prototype.run = function () {
  var me = this;
  var cmds = me.applet.slice();
  while (cmds.length) {
    var call = WWW_Applet.canonize_function_name(cmds.shift());
    var args = cmds.shift();
    if (!_.isString(call))
      return me.quit("not a function name:", call);
    if (!WWW_Applet.FUNC_NAMES[call])
      return me.quit('function not found:', call);
    if (!_.isArray(args))
      return me.quit("not arguments:", args);
    WWW_Applet.FUNC_NAMES[call].apply(me, args);
  }
};

WWW_Applet.prototype.dom_ns = function (str) {
  var me = this;
  if (str === '#Sidebar')
    return str;
  return str.replace('#', '#' + me.dom_ns_string + '_');
};

WWW_Applet.prototype.dom_by_id = function (str) {
  var me = this;
  return $(me.dom_ns(str));
};

define("box", function (id) {
  var me = this;
  me.stack.push(me.dom_by_id(id));
  return me;
});

define('create box at top',  function (id) {
  var me = this;
  var box = $('
');
  box.attr('id', me.dom_ns(id).replace('#', ''));
  var last = _.last(me.stack);
  me.stack.push(box);
  last.prepend(box);

  return me;
});

define('list', function () {
  var me = this;
  me.stack.push(_.toArray(arguments));
  return me;
});

define('random item', function () {
  var me = this;
  var list = _.last(me.stack);
  var item = list[Math.floor(Math.random()*list.length)];
  me.stack.push(item);
  return me;
});

define('is text of', function (id) {
  var me = this;
  var ele = $(me.dom_ns(id));

  ele.text(_.last(me.stack));
  me.stack.push(ele);
  return me;
});

define('padding', function (str) {
  var me = this;
  css( _.last(me.stack), 'padding', str);
  return me;
});

<|endoftext|>


<commit_before>
if( ! JSHC.Internal )JSHC.Internal = new Object();
if( ! JSHC.Internal.Prelude )JSHC.Internal.Prelude = new Object();
if( ! JSHC.Internal.Types )JSHC.Internal.Types = new Object();
// primtive operations for use in the Prelude.

////////////////////////////////////////////////////////////////////////////////

/*
    the optional name is the name used in as-patterns
*/
JSHC.Internal.WildPat = function(varname){
    assert.ok(typeof varname == "string" || varname === undefined);
    this.varname = varname;
    this.name = "WildPat";
};

JSHC.Internal.IntegerPat = function(number){
    assert.ok(typeof number == "number" );
    this.number = number;
    this.name = "IntegerPat";
};

JSHC.Internal.NamePat = function(varname){
    assert.ok(typeof varname == "string");
    this.varname = varname;
    this.name = "NamePat";
};

JSHC.Internal.ConPat = function(dacon,args){
    assert.ok(typeof dacon == "string");
    assert.ok(args instanceof Array);
    this.dacon = dacon;
    this.args = args;
    this.name = "ConPat";
};

JSHC.Internal.TuplePat = function(args){
    assert.ok(args instanceof Array);
    this.args = args;
    this.name = "TuplePat";
};

JSHC.Internal.undefined = function() {
    throw new JSHC.RuntimeError("undefined")
};

JSHC.Internal.int32maxbound = Math.pow(2,31)-1;
JSHC.Internal.int32minbound = -Math.pow(2,31);
JSHC.Internal.int16maxbound = Math.pow(2,15)-1;
JSHC.Internal.int16minbound = -Math.pow(2,15);
JSHC.Internal.int8maxbound = Math.pow(2,7)-1;
JSHC.Internal.int8minbound = -Math.pow(2,7);

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32add = function(a,b){
    var r = a + b;
    if( r > JSHC.Internal.int32maxbound || r < JSHC.Internal.int32minbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" + "+b);
    return r;
};

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32sub = function(a,b){
    var r = a - b;
    if( r > JSHC.Internal.int32maxbound || r < JSHC.Internal.int32minbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" - "+b);
    return r;
};

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32mul = function(a,b){
    var r = a * b;
    if( r > JSHC.Internal.int32maxbound || r < JSHC.Internal.int32minbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" * "+b);
    return r;
};

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32div = function(a,b){
    if( b == 0 ){
        throw new JSHC.RuntimeError("Data.Int.Int32 division by 0 in "+a+" / "+b);
    }
    var r = Math.floor(a / b);
    assert.ok(r >= JSHC.Internal.int32minbound);
    // NOTE: minbound/-1 will be out of bounds since > maxbound.
    if( r > JSHC.Internal.int32maxbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" / "+b);
    return r;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32eq = function(a,b){
    return a===b;
};

//JSHC.Internal.int32show = function(a){
//    return new String(a);
//}

// :: String -> Int32
//JSHC.Internal.int32read = function(s){
//    return new Number(s);
//    // TOOD: must give some reasonable exception when not a number.
//}

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32lt = function (a,b) {
    return a < b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32gt = function (a,b) {
    return a > b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32le = function (a,b) {
    return a <= b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32ge = function (a,b) {
    return a >= b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32eq = function (a,b) {
    return a == b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32ne = function (a,b) {
    return a != b;
};

//JSHC.Internal.int32comp = function(fun) {
//    return (function(a) {
//    return function (b) {
//        if ( fun( (a instanceof JSHC.Thunk)? a.v : a , (b instanceof JSHC.Thunk)? b.v : b ) ) {
//            return ["True"];
//        } else {
//            return ["False"];
//        }
//    }} );
//}

JSHC.Internal.seq = function (a,b) {
    return b;
};

////////////////////////////////////////////////////////////////////////////////

//match evaluated exp against pat
//returns: an array with any bound variables if successful, Boolean false if failed
JSHC.Internal.match = function(exp, alts) {
//    alert("match called with exp:\n\n" + JSHC.showAST(exp) + "\n\nand alts\n\n" + JSHC.showAST(alts))

    if( !(exp instanceof JSHC.Thunk) ){
        exp = new JSHC.Thunk(exp);
    }

    // array of thunks from the matching expressions
    var binds;

//    JSHC.alert("matching:", exp, "\nto:", alts);

    var match_ = function (exp, pat) {
//    JSHC.alert("checking exp:", exp, "\nagainst pat:", pat);
        switch (pat.name) {
            case "NamePat":
                binds.push(exp);
                return true;

            case "IntegerPat":
                return exp.v === pat.number;

            case "WildPat":
                return true;

            //case "dacon":
            //    return (pat.p[0] === exp[0] && pat.p.length === exp.length);

            case "ConPat":
                exp = exp.v;

                var res = exp instanceof JSHC.Internal.Datatype;
                if( res === false )return res;
                res = pat.dacon == exp.dacon && pat.args.length === exp.args.length;

                for (var i = 0; i < pat.args.length; i++) {
                    //if (exp[i] instanceof JSHC.Thunk)
                        res = res && match_(exp.args[i],pat.args[i]);
                    //else
                    //    res = res && match_(exp[i],pat.p[i]);
                }
                return res;

            case "TuplePat":
                exp = exp.v;

                var res = exp instanceof JSHC.Internal.Types["()"];
                if( res === false )return res;
                res = pat.args.length === exp.args.length;

                for (var i = 0; i < pat.args.length; i++) {
                    //if (exp[i] instanceof JSHC.Thunk)
                        res = res && match_(exp.args[i],pat.args[i]);
                    //else
                    //    res = res && match_(exp[i],pat.p[i]);
                }
                return res;

            default:
                throw new Error("match_ needs definition for: " + pat.name);
        }
    }

    for (var i = 0; i < alts.length; i++) {
        binds = [];
        if (match_(exp, alts[i].p)) {
            assert.ok(alts[i].f instanceof Function, "rhs of pattern is not a function!");
//            alert("matched something: " + alts[i].f);
//            alert("with binds: " + binds);
            return alts[i].f.apply(undefined,binds);
        }
    }

    throw new Error("Unhandled case in pattern match! " + JSHC.showAST(exp) + " alts:\n\n" + JSHC.showAST(alts)); //TODO: proper error reporting would be?

}

////////////////////////////////////////////////////////////////////////////////

/*
  Arbitrary datatype
*/
JSHC.Internal.Datatype = function(){
};

/*
   default instance of Show for data types
*/
JSHC.Internal.Datatype.prototype.toString = function(){
    var buf = [];
    buf.push(this.dacon.toString());
    buf.push(" ");
    for(var i=0 ; i<this.args.length ; i++){
        buf.push(this.args[i].toString());
        buf.push(" ");
    }
    buf.pop();   // remove last space
    return buf.join("");
};

/*
  List datatype
*/
JSHC.Internal.Types["[]"] = function(dacon,args){
    assert.ok(typeof dacon == "string");
    assert.ok(args instanceof Array);
    this.dacon = dacon;
    this.args = args;
};
JSHC.Internal.Types["[]"].prototype = new JSHC.Internal.Datatype();

/*
  List toString
*/
JSHC.Internal.Types["[]"].prototype.toString = function(){
    var buf = [];
    buf.push("[");
    if( this.dacon == ":" ){
        buf.push(this.args[0].toString());
        var rest = this.args[1].v;  // evaluate the rest
        while(true){
            if( rest.dacon == "[]" ){
                break;
            }
            assert.ok( rest.dacon == ":" );
            buf.push(",");
            buf.push(rest.args[0].toString());
            rest = rest.args[1].v;  // evaluate the rest
        }
    } else if( this.dacon == "[]" ){
        // do nothing
    } else {
        throw new JSHC.RuntimeError("invalid dacon in List toString");
    }
    buf.push("]");
    return buf.join("");
};

/*
  List Cons constructor
*/
JSHC.Internal.Types["[].:"] = function(a){
    return function(b){
        assert.ok( a instanceof JSHC.Thunk );
        assert.ok( b instanceof JSHC.Thunk );
        return new JSHC.Internal.Types["[]"](":",[a,b]);
    }
};

/*
  List Nil constructor
*/
JSHC.Internal.Types["[].[]"] = function(){
    return new JSHC.Internal.Types["[]"]("[]",[]);
};

/*
  Unit/Tuple datatypes
*/
JSHC.Internal.Types["()"] = function(args){
    assert.ok(args instanceof Array);
    this.args = args;
};
JSHC.Internal.Types["()"].prototype = new JSHC.Internal.Datatype();

/*
  Unit/Tuple toString
*/
JSHC.Internal.Types["()"].prototype.toString = function(){
    var buf = [];
    buf.push("(");
    for(var i=0 ; i<this.args.length ; i++){
        buf.push(this.args[i].toString());
        buf.push(",");
    }
    buf.pop();   // remove last space
    buf.push(")");
    return buf.join("");
};

////////////////////////////////////////////////////////////////////////////////
<commit_msg>datatype: toString: parentheses<commit_after>
if( ! JSHC.Internal )JSHC.Internal = new Object();
if( ! JSHC.Internal.Prelude )JSHC.Internal.Prelude = new Object();
if( ! JSHC.Internal.Types )JSHC.Internal.Types = new Object();
// primtive operations for use in the Prelude.

////////////////////////////////////////////////////////////////////////////////

/*
    the optional name is the name used in as-patterns
*/
JSHC.Internal.WildPat = function(varname){
    assert.ok(typeof varname == "string" || varname === undefined);
    this.varname = varname;
    this.name = "WildPat";
};

JSHC.Internal.IntegerPat = function(number){
    assert.ok(typeof number == "number" );
    this.number = number;
    this.name = "IntegerPat";
};

JSHC.Internal.NamePat = function(varname){
    assert.ok(typeof varname == "string");
    this.varname = varname;
    this.name = "NamePat";
};

JSHC.Internal.ConPat = function(dacon,args){
    assert.ok(typeof dacon == "string");
    assert.ok(args instanceof Array);
    this.dacon = dacon;
    this.args = args;
    this.name = "ConPat";
};

JSHC.Internal.TuplePat = function(args){
    assert.ok(args instanceof Array);
    this.args = args;
    this.name = "TuplePat";
};

JSHC.Internal.undefined = function() {
    throw new JSHC.RuntimeError("undefined")
};

JSHC.Internal.int32maxbound = Math.pow(2,31)-1;
JSHC.Internal.int32minbound = -Math.pow(2,31);
JSHC.Internal.int16maxbound = Math.pow(2,15)-1;
JSHC.Internal.int16minbound = -Math.pow(2,15);
JSHC.Internal.int8maxbound = Math.pow(2,7)-1;
JSHC.Internal.int8minbound = -Math.pow(2,7);

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32add = function(a,b){
    var r = a + b;
    if( r > JSHC.Internal.int32maxbound || r < JSHC.Internal.int32minbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" + "+b);
    return r;
};

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32sub = function(a,b){
    var r = a - b;
    if( r > JSHC.Internal.int32maxbound || r < JSHC.Internal.int32minbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" - "+b);
    return r;
};

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32mul = function(a,b){
    var r = a * b;
    if( r > JSHC.Internal.int32maxbound || r < JSHC.Internal.int32minbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" * "+b);
    return r;
};

// :: Int32 -> Int32 -> Int32
JSHC.Internal.int32div = function(a,b){
    if( b == 0 ){
        throw new JSHC.RuntimeError("Data.Int.Int32 division by 0 in "+a+" / "+b);
    }
    var r = Math.floor(a / b);
    assert.ok(r >= JSHC.Internal.int32minbound);
    // NOTE: minbound/-1 will be out of bounds since > maxbound.
    if( r > JSHC.Internal.int32maxbound )throw new JSHC.RuntimeError("Data.Int.Int32 out of bounds in "+a+" / "+b);
    return r;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32eq = function(a,b){
    return a===b;
};

//JSHC.Internal.int32show = function(a){
//    return new String(a);
//}

// :: String -> Int32
//JSHC.Internal.int32read = function(s){
//    return new Number(s);
//    // TOOD: must give some reasonable exception when not a number.
//}

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32lt = function (a,b) {
    return a < b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32gt = function (a,b) {
    return a > b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32le = function (a,b) {
    return a <= b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32ge = function (a,b) {
    return a >= b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32eq = function (a,b) {
    return a == b;
};

// :: Int32 -> Int32 -> Bool
JSHC.Internal.int32ne = function (a,b) {
    return a != b;
};

//JSHC.Internal.int32comp = function(fun) {
//    return (function(a) {
//    return function (b) {
//        if ( fun( (a instanceof JSHC.Thunk)? a.v : a , (b instanceof JSHC.Thunk)? b.v : b ) ) {
//            return ["True"];
//        } else {
//            return ["False"];
//        }
//    }} );
//}

JSHC.Internal.seq = function (a,b) {
    return b;
};

////////////////////////////////////////////////////////////////////////////////

//match evaluated exp against pat
//returns: an array with any bound variables if successful, Boolean false if failed
JSHC.Internal.match = function(exp, alts) {
//    alert("match called with exp:\n\n" + JSHC.showAST(exp) + "\n\nand alts\n\n" + JSHC.showAST(alts))

    if( !(exp instanceof JSHC.Thunk) ){
        exp = new JSHC.Thunk(exp);
    }

    // array of thunks from the matching expressions
    var binds;

//    JSHC.alert("matching:", exp, "\nto:", alts);

    var match_ = function (exp, pat) {
//    JSHC.alert("checking exp:", exp, "\nagainst pat:", pat);
        switch (pat.name) {
            case "NamePat":
                binds.push(exp);
                return true;

            case "IntegerPat":
                return exp.v === pat.number;

            case "WildPat":
                return true;

            //case "dacon":
            //    return (pat.p[0] === exp[0] && pat.p.length === exp.length);

            case "ConPat":
                exp = exp.v;

                var res = exp instanceof JSHC.Internal.Datatype;
                if( res === false )return res;
                res = pat.dacon == exp.dacon && pat.args.length === exp.args.length;

                for (var i = 0; i < pat.args.length; i++) {
                    //if (exp[i] instanceof JSHC.Thunk)
                        res = res && match_(exp.args[i],pat.args[i]);
                    //else
                    //    res = res && match_(exp[i],pat.p[i]);
                }
                return res;

            case "TuplePat":
                exp = exp.v;

                var res = exp instanceof JSHC.Internal.Types["()"];
                if( res === false )return res;
                res = pat.args.length === exp.args.length;

                for (var i = 0; i < pat.args.length; i++) {
                    //if (exp[i] instanceof JSHC.Thunk)
                        res = res && match_(exp.args[i],pat.args[i]);
                    //else
                    //    res = res && match_(exp[i],pat.p[i]);
                }
                return res;

            default:
                throw new Error("match_ needs definition for: " + pat.name);
        }
    }

    for (var i = 0; i < alts.length; i++) {
        binds = [];
        if (match_(exp, alts[i].p)) {
            assert.ok(alts[i].f instanceof Function, "rhs of pattern is not a function!");
//            alert("matched something: " + alts[i].f);
//            alert("with binds: " + binds);
            return alts[i].f.apply(undefined,binds);
        }
    }

    throw new Error("Unhandled case in pattern match! " + JSHC.showAST(exp) + " alts:\n\n" + JSHC.showAST(alts)); //TODO: proper error reporting would be?

}

////////////////////////////////////////////////////////////////////////////////

/*
  Arbitrary datatype
*/
JSHC.Internal.Datatype = function(){
};

/*
   default instance of Show for data types
*/
JSHC.Internal.Datatype.prototype.toString = function(){
    var buf = [];
    buf.push(this.dacon.toString());
    buf.push(" ");
    for(var i=0 ; i<this.args.length ; i++){
        buf.push("(");
        buf.push(this.args[i].toString());
        buf.push(")");
        buf.push(" ");
    }
    buf.pop();   // remove last space
    return buf.join("");
};

/*
  List datatype
*/
JSHC.Internal.Types["[]"] = function(dacon,args){
    assert.ok(typeof dacon == "string");
    assert.ok(args instanceof Array);
    this.dacon = dacon;
    this.args = args;
};
JSHC.Internal.Types["[]"].prototype = new JSHC.Internal.Datatype();

/*
  List toString
*/
JSHC.Internal.Types["[]"].prototype.toString = function(){
    var buf = [];
    buf.push("[");
    if( this.dacon == ":" ){
        buf.push(this.args[0].toString());
        var rest = this.args[1].v;  // evaluate the rest
        while(true){
            if( rest.dacon == "[]" ){
                break;
            }
            assert.ok( rest.dacon == ":" );
            buf.push(",");
            buf.push(rest.args[0].toString());
            rest = rest.args[1].v;  // evaluate the rest
        }
    } else if( this.dacon == "[]" ){
        // do nothing
    } else {
        throw new JSHC.RuntimeError("invalid dacon in List toString");
    }
    buf.push("]");
    return buf.join("");
};

/*
  List Cons constructor
*/
JSHC.Internal.Types["[].:"] = function(a){
    return function(b){
        assert.ok( a instanceof JSHC.Thunk );
        assert.ok( b instanceof JSHC.Thunk );
        return new JSHC.Internal.Types["[]"](":",[a,b]);
    }
};

/*
  List Nil constructor
*/
JSHC.Internal.Types["[].[]"] = function(){
    return new JSHC.Internal.Types["[]"]("[]",[]);
};

/*
  Unit/Tuple datatypes
*/
JSHC.Internal.Types["()"] = function(args){
    assert.ok(args instanceof Array);
    this.args = args;
};
JSHC.Internal.Types["()"].prototype = new JSHC.Internal.Datatype();

/*
  Unit/Tuple toString
*/
JSHC.Internal.Types["()"].prototype.toString = function(){
    var buf = [];
    buf.push("(");
    for(var i=0 ; i<this.args.length ; i++){
        buf.push(this.args[i].toString());
        buf.push(",");
    }
    buf.pop();   // remove last space
    buf.push(")");
    return buf.join("");
};

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>'use strict';

var renderer, scene, camera, controls;
var geometry, material;

var world;

var sphereShape, cMaterial;

function init() {
	//renderer
	renderer = new THREE.WebGLRenderer();
	renderer.setSize(window.innerWidth, window.innerHeight);
	renderer.setClearColor(0x52026e, 1);
	document.body.appendChild(renderer.domElement);

	//scene
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera(40, window.innerWidth/window.innerHeight, 1, 1000);
	camera.position.set(0,-50,200);
	camera.lookAt(new THREE.Vector3(0,0,0));

	controls = new THREE.TrackballControls(camera);
	controls.noZoom = false;
	controls.noPan = false;
	controls.noRotate = false;
	controls.keys = [65, 83, 32];
	controls.staticMoving = true;
	controls.dynamicDampingFactor = 0.3;

	//world
	world = new CANNON.World();
	world.broadphase = new CANNON.NaiveBroadphase();
	world.gravity.set(0,-100,0);

	//sphere
	geometry = new THREE.SphereGeometry(1, 32, 32);
	material = new THREE.MeshBasicMaterial({
		wireframe: true,
	});

	sphereShape = new CANNON.Sphere(1);
	cMaterial = new CANNON.Material('slipperyMaterial');

	var planeShape = new CANNON.Plane();

	var planeBody1 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody1.quaternion.setFromAxisAngle(new CANNON.Vec3(0,1,0), -Math.PI/2);
	planeBody1.position.set(25,0,0);
	world.add(planeBody1);

	var planeBody2 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody2.quaternion.setFromAxisAngle(new CANNON.Vec3(0,1,0), Math.PI/2);
	planeBody2.position.set(-25,0,0);
	world.add(planeBody2);

	var planeBody3 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody3.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0), -Math.PI/2);
	planeBody3.position.set(0,-25,0);
	world.add(planeBody3);

	var planeBody4 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody4.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0), Math.PI/2);
	planeBody4.position.set(0,25,0);
	world.add(planeBody4);

}

function createSphere(x , y, z) {
	var mesh = new THREE.Mesh(geometry, material);
	scene.add(mesh);

	var sphereBody = new CANNON.RigidBody(1, sphereShape, cMaterial);
	sphereBody.position.set(x, y, z);
	world.add(sphereBody);
}

function update() {
	if(scene.children.length < 200) {
		createSphere(Math.random() * 10, 10 + Math.random() * 10, Math.random() * 10);
	}

	var rand = Math.random() * 100 - Math.random() * 100;

	world.gravity.set( rand - rand * rand / 100, rand, 0);

	for(var i=0,j=scene.children.length;i<j;i++) {
		world.bodies[i].position.copy(scene.children[i].position);
		world.bodies[i].quaternion.copy(scene.children[i].quaternion);
	}

	world.step(1.0/60);
}

function animate() {
	window.requestAnimationFrame(animate);

	//update
	update();

	controls.update();

	//rendering stuff
	renderer.render(scene, camera);
}

init();
animate();<commit_msg>blah blah<commit_after>'use strict';

var renderer, scene, camera, controls;
var geometry, material;

var world;

var sphereShape, cMaterial;

function init() {
	//renderer
	renderer = new THREE.WebGLRenderer();
	renderer.setSize(window.innerWidth, window.innerHeight);
	renderer.setClearColor(0x52026e, 1);
	document.body.appendChild(renderer.domElement);

	//scene
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera(40, window.innerWidth/window.innerHeight, 1, 1000);
	camera.position.set(0,-75,500);
	camera.lookAt(new THREE.Vector3(0,-75,0));

	controls = new THREE.TrackballControls(camera);
	controls.noZoom = false;
	controls.noPan = false;
	controls.noRotate = false;
	controls.keys = [65, 83, 32];
	controls.staticMoving = true;
	controls.dynamicDampingFactor = 0.3;

	//world
	world = new CANNON.World();
	world.broadphase = new CANNON.NaiveBroadphase();
	world.gravity.set(0,-9.82,0);

	//sphere
	geometry = new THREE.SphereGeometry(1, 32, 32);
	material = new THREE.MeshBasicMaterial({
		wireframe: true,
	});

	sphereShape = new CANNON.Sphere(1);
	cMaterial = new CANNON.Material('slipperyMaterial');

	var planeShape = new CANNON.Plane();

	var planeBody1 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody1.quaternion.setFromAxisAngle(new CANNON.Vec3(0,1,0), -Math.PI/2);
	planeBody1.position.set(25,0,0);
	world.add(planeBody1);

	var planeBody2 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody2.quaternion.setFromAxisAngle(new CANNON.Vec3(0,1,0), Math.PI/2);
	planeBody2.position.set(-25,0,0);
	world.add(planeBody2);

	var planeBody3 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody3.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0), -Math.PI/2);
	planeBody3.position.set(0,-100,0);
	world.add(planeBody3);

	var planeBody4 = new CANNON.RigidBody(0, planeShape, cMaterial);
	planeBody4.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0), Math.PI/2);
	planeBody4.position.set(0,25,0);
	world.add(planeBody4);

}

function createSphere(x , y, z) {
	var mesh = new THREE.Mesh(geometry, material);
	scene.add(mesh);

	var sphereBody = new CANNON.RigidBody(1, sphereShape, cMaterial);
	sphereBody.position.set(x, y, z);
	world.add(sphereBody);
}

function update() {
	if(scene.children.length < 500) {
		createSphere(Math.random() * 10, 10 + Math.random() * 10, Math.random() * 10);
	}

	for(var i=scene.children.length; i>=0;i--) {
		if(world.bodies[i].position.y < -95 ) {
			world.remove(world.bodies[i]);
			scene.remove(scene.children[i]);
		}
	}

	for(var i=0,j=scene.children.length;i<j;i++) {
		world.bodies[i].position.copy(scene.children[i].position);
		world.bodies[i].quaternion.copy(scene.children[i].quaternion);
	}

	world.step(1.0/60);
}

function animate() {
	window.requestAnimationFrame(animate);

	//update
	update();

	controls.update();

	//rendering stuff
	renderer.render(scene, camera);
}

init();
animate();<|endoftext|>