<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'Memento',

  constants: {
    SEPARATOR:    ':',
    PARAMS_BEGIN: '{',
    PARAMS_END:   '}',

    OUTPUTTER: foam.json.Outputter.create({
      strict: false,
      pretty: false
    })
  },

  properties: [
    {
      class: 'Boolean',
      name: 'feedback_',
      documentation: 'Internal flag to prevent feedback loops'
    },
    {
      name: 'value',
      value: '',
      postSet: function(o, n) {
        this.parseValue();
      }
    },
    {
      name: 'head',
      value: '',
      postSet: function(o, n) {
        if ( this.feedback_ ) return;
        this.feedback_ = true;
        this.value     = this.combine();
        this.feedback_ = false;
      }
    },
    {
      name: 'tail',
      postSet: function(o, n) {
        if ( this.feedback_ ) return;
        this.feedback_       = true;
        this.changeIndicator = ! this.changeIndicator;
        this.value           = this.combine();
        this.feedback_       = false;
      },
      value: null
    },
    {
      name: 'parent'
    },
    {
      name: 'changeIndicator',
      postSet: function() {
        if ( this.parent ) {
          this.parent.feedback_       = true;
          this.parent.changeIndicator = ! this.parent.changeIndicator;
          this.parent.feedback_       = false;
        }
      }
    },
    {
      name: 'params',
      documentation: 'This property used to store parameters to configure a view. For example, for a table view such parameters could be search value or filter values.',
      postSet: function() {
        if ( this.feedback_ ) return;
        this.feedback_ = true;
        var obj = {};
        if ( this.params ) {
          this.params = decodeURI(this.params);
          obj = foam.json.parseString(this.params);
        }
        this.paramsObj = obj;
        this.feedback_ = false;
      },
      value: ''
    },
    {
      name: 'paramsObj',
      documentation: `
        paramsObj short names:
          c  for columns
          f  for filters
          n  for name
          o  for order as in orderBy
          r  for number of record to which table will be scrolled to
          s  for search
          sT for selected tab
          sV for selected view
      `,
      postSet: function() {
        if ( this.feedback_ ) return;
        this.feedback_ = true;
        if ( Object.keys(this.paramsObj).length !== 0 ) {
          this.params = this.OUTPUTTER.stringify(this.paramsObj);
        } else {
          this.params = '';
        }
        this.changeIndicator = ! this.changeIndicator;
        this.value = this.combine();
        this.feedback_ = false;
      },
      factory: function() {
        return {};
      }
    }
  ],

  methods: [
    function combine() {
      var params =  this.params ?  this.SEPARATOR + this.params : '';
      var tail = this.tail ? this.SEPARATOR + this.tail.combine() : '';
      return this.head + params + tail;
    },
    function parseValue() {
      if ( this.feedback_ ) return;
      this.feedback_ = true;
      var i = this.value.indexOf(this.SEPARATOR);

      var params = '';
      if ( i === -1 ) {
        this.head = this.value;
        this.tail = null;
      } else {
        this.head     = this.value.substring(0, i);
        var tailStr   = this.value.substring(i+1);
        var tailIndex = this.value.indexOf(this.SEPARATOR, i+1);
        if ( tailStr.includes(this.PARAMS_BEGIN) && tailStr.includes(this.PARAMS_END) && ( tailIndex === -1 || this.value.indexOf(this.PARAMS_BEGIN, i+1) < tailIndex ) ) {
          if ( this.value.indexOf(this.PARAMS_BEGIN) === i + 1 ) {
            this.feedback_ = false;
            var paramEndIndex = tailStr.indexOf(this.PARAMS_END + this.SEPARATOR);
            paramEndIndex = paramEndIndex == -1 ? tailStr.length : paramEndIndex + 1;
            params = tailStr.substring(tailStr.indexOf(this.PARAMS_BEGIN), paramEndIndex);
            this.feedback_ = true;
            if ( paramEndIndex !== -1 && paramEndIndex !== tailStr.length ) {
              this.tail = this.cls_.create({ value: tailStr.substring(paramEndIndex + 1), parent: this });
            }
          } else {
            this.tail = this.cls_.create({ value: tailStr, parent: this });
          }
        } else {
          this.tail = this.cls_.create({ value: tailStr, parent: this });
        }
      }
      this.feedback_ = false;
      this.params    = params;
    }
  ]
});
<commit_msg>Fix broken build.<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'Memento',

  constants: [
    { name: 'SEPARATOR',    value: ':'},
    { name: 'PARAMS_BEGIN', value: '{'},
    { name: 'PARAMS_END',   value: '}'},

    {
      name: 'OUTPUTTER',
      factory: function() { return foam.json.Outputter.create({
        strict: false,
        pretty: false
      });}
    }
  ],

  properties: [
    {
      class: 'Boolean',
      name: 'feedback_',
      documentation: 'Internal flag to prevent feedback loops'
    },
    {
      name: 'value',
      value: '',
      postSet: function(o, n) {
        this.parseValue();
      }
    },
    {
      name: 'head',
      value: '',
      postSet: function(o, n) {
        if ( this.feedback_ ) return;
        this.feedback_ = true;
        this.value     = this.combine();
        this.feedback_ = false;
      }
    },
    {
      name: 'tail',
      postSet: function(o, n) {
        if ( this.feedback_ ) return;
        this.feedback_       = true;
        this.changeIndicator = ! this.changeIndicator;
        this.value           = this.combine();
        this.feedback_       = false;
      },
      value: null
    },
    {
      name: 'parent'
    },
    {
      name: 'changeIndicator',
      postSet: function() {
        if ( this.parent ) {
          this.parent.feedback_       = true;
          this.parent.changeIndicator = ! this.parent.changeIndicator;
          this.parent.feedback_       = false;
        }
      }
    },
    {
      name: 'params',
      documentation: 'This property used to store parameters to configure a view. For example, for a table view such parameters could be search value or filter values.',
      postSet: function() {
        if ( this.feedback_ ) return;
        this.feedback_ = true;
        var obj = {};
        if ( this.params ) {
          this.params = decodeURI(this.params);
          obj = foam.json.parseString(this.params);
        }
        this.paramsObj = obj;
        this.feedback_ = false;
      },
      value: ''
    },
    {
      name: 'paramsObj',
      documentation: `
        paramsObj short names:
          c  for columns
          f  for filters
          n  for name
          o  for order as in orderBy
          r  for number of record to which table will be scrolled to
          s  for search
          sT for selected tab
          sV for selected view
      `,
      postSet: function() {
        if ( this.feedback_ ) return;
        this.feedback_ = true;
        if ( Object.keys(this.paramsObj).length !== 0 ) {
          this.params = this.OUTPUTTER.stringify(this.paramsObj);
        } else {
          this.params = '';
        }
        this.changeIndicator = ! this.changeIndicator;
        this.value = this.combine();
        this.feedback_ = false;
      },
      factory: function() {
        return {};
      }
    }
  ],

  methods: [
    function combine() {
      var params =  this.params ?  this.SEPARATOR + this.params : '';
      var tail = this.tail ? this.SEPARATOR + this.tail.combine() : '';
      return this.head + params + tail;
    },
    function parseValue() {
      if ( this.feedback_ ) return;
      this.feedback_ = true;
      var i = this.value.indexOf(this.SEPARATOR);

      var params = '';
      if ( i === -1 ) {
        this.head = this.value;
        this.tail = null;
      } else {
        this.head     = this.value.substring(0, i);
        var tailStr   = this.value.substring(i+1);
        var tailIndex = this.value.indexOf(this.SEPARATOR, i+1);
        if ( tailStr.includes(this.PARAMS_BEGIN) && tailStr.includes(this.PARAMS_END) && ( tailIndex === -1 || this.value.indexOf(this.PARAMS_BEGIN, i+1) < tailIndex ) ) {
          if ( this.value.indexOf(this.PARAMS_BEGIN) === i + 1 ) {
            this.feedback_ = false;
            var paramEndIndex = tailStr.indexOf(this.PARAMS_END + this.SEPARATOR);
            paramEndIndex = paramEndIndex == -1 ? tailStr.length : paramEndIndex + 1;
            params = tailStr.substring(tailStr.indexOf(this.PARAMS_BEGIN), paramEndIndex);
            this.feedback_ = true;
            if ( paramEndIndex !== -1 && paramEndIndex !== tailStr.length ) {
              this.tail = this.cls_.create({ value: tailStr.substring(paramEndIndex + 1), parent: this });
            }
          } else {
            this.tail = this.cls_.create({ value: tailStr, parent: this });
          }
        } else {
          this.tail = this.cls_.create({ value: tailStr, parent: this });
        }
      }
      this.feedback_ = false;
      this.params    = params;
    }
  ]
});
<|endoftext|>


<commit_before>var map;
var players;
var player = {markers: [], lat: 0, lng: 0};
var socket;

function setEventHandlers() {
    console.log("connection");
    socket.on("connect", onSocketConnected);
    socket.on("disconnect", onSocketDisconnect);
    socket.on("new player", onNewPlayer);
    socket.on("move player", onMovePlayer);
    socket.on("remove player", onRemovePlayer);
}
function onNewPlayer(p){
    var newPlayer = {id :p.id, markers: [], lat: p.lat, lng: p.lng, hunted: p.hunted};
    players.push(newPlayer);
    console.log("new player");
    initTrace(player, newPlayer);
   // players = [];
}
function onSocketConnected() {
    console.log("Connected to socket server");
    socket.emit("new player", player);
};

function onSocketDisconnect() {
    console.log("Disconnected from socket server");
};

function onMovePlayer(data) {
    for (var i; i<players.length; i++){
        if(players[i].id == data.id){
            players[i] = {id :data.id, markers: [], lat: data.lat, lng: data.lng};
        }
    }
};

function onRemovePlayer(data) {

};

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.640},
      zoom: 19,
      scrollwheel: false,
      zoomControl: false,
      mapTypeControl: false,
      scaleControl: false,
      streetViewControl: false,
      rotateControl: false,
      fullscreenControl: false,
      draggable: false,
      keyboardShortcuts: false
    });
    var icon = {
        url: "img/face.png", // url
        scaledSize: new google.maps.Size(64, 141), // scaled size
        origin: new google.maps.Point(0,0), // origin
        anchor: new google.maps.Point(32, 128) // anchor
    };

    var faceMarker = new google.maps.Marker({
                                                map: map,
                                                icon: icon
                                            });

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        player = {markers: [], lat: pos.lat, lng: pos.lng};
        faceMarker.setPosition(pos);
        map.setCenter(pos);
      }, function() {
        handleLocationError(true, faceMarker, map.getCenter());
      });
    } else {
        handleLocationError(false, faceMarker, map.getCenter());
    }
    players = [];
    initMarkers();
    setInterval(function() {
	   getPosition(faceMarker);
       updateTrace();
    }, 1000);
    socket = io.connect();
    setEventHandlers();
}

function getPosition(faceMarker) {
    navigator.geolocation.getCurrentPosition(function(position) {
	var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
	};
	faceMarker.setPosition(pos);
	map.setCenter(pos);
    }, function() {
	   handleLocationError(true, faceMarker, map.getCenter());
    });
}
function smokeBomb(){
    document.getElementById('myCanvas').style.display = "block";
    /*for (var i = 0; i < players[playerIndex].markers.length ; i++){
        players[playerIndex].markers[i].setMap(null);
    }
    setTimeout(function() { makeVisibleAgain(playerIndex); }, 5000);*/
    setTimeout(function() { makeVisibleAgain(); }, 5000);
}

function makeVisibleAgain(){
    document.getElementById('myCanvas').style.display = "none";
    /*for (var i = 0; i < players[playerIndex].markers.length ; i++){
        players[playerIndex].markers[i].setMap(map);
    }*/
}

function initMarkers(){
    for (var i = 0; i < players.length; i++){
        initTrace(player, players[i]);
    }
}
function initTrace(player, targetPlayer){
    console.log("init trace " + targetPlayer.lat + " and lng " + targetPlayer.lng);
    nbOfPointers = 100; //getDistance(player, targetPlayer);
    xDistance = (targetPlayer.lat - player.lat)/nbOfPointers;
    yDistance = (targetPlayer.lng - player.lng)/nbOfPointers;
    var flightPlanCoordinates = [];
    var angle = Math.atan2(targetPlayer.lng - player.lng , targetPlayer.lat - player.lat)* (180 / Math.PI );
    var image = {
        path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
        rotation: angle
    };
    nbOfShownPointers = nbOfPointers/10;
    for (var i = 0; i < nbOfShownPointers; i++){

        console.log("lat is " + (player.lat + (xDistance *i)) + "  lng is " + (player.lng + (yDistance *i)));
        var p = {lat: player.lat + (xDistance *i), lng: player.lng + (yDistance *i)};
        var marker = new google.maps.Marker({
          position: p,
          map: map,
          icon: image
        });
        targetPlayer.markers.push(marker);
    }
}
function updateTrace(player){
    for (var j = 0; j < players.length; j++)
        for (var i = 0; i < players[j].markers.length; i++){
            var p = {lat: players[j].lat + (xDistance *i), lng: players[j].lng + (yDistance *i)};
            players[j].markers[i] = new google.maps.Marker({
              position: p,
              map: map,
              //icon: image
            });
        }
    }
function handleLocationError(browserHasGeolocation, faceMarker, pos) {
    faceMarker.setPosition(pos);
    console.log(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
}

// Create an array to store our particles
var particles = [];

// The amount of particles to render
var particleCount = 30;

// The maximum velocity in each direction
var maxVelocity = 2;

// The target frames per second (how often do we want to update / redraw the scene)
var targetFPS = 33;

// Set the dimensions of the canvas as variables so they can be used.
var canvasWidth = 400;
var canvasHeight = 400;

// Create an image object (only need one instance)
var imageObj = new Image();

// Once the image has been downloaded then set the image on all of the particles
imageObj.onload = function() {
    particles.forEach(function(particle) {
            particle.setImage(imageObj);
    });
};

// Once the callback is arranged then set the source of the image
imageObj.src = "http://www.blog.jonnycornwell.com/wp-content/uploads/2012/07/Smoke10.png";

// A function to create a particle object.
function Particle(context) {

    // Set the initial x and y positions
    this.x = 0;
    this.y = 0;

    // Set the initial velocity
    this.xVelocity = 0;
    this.yVelocity = 0;

    // Set the radius
    this.radius = 5;

    // Store the context which will be used to draw the particle
    this.context = context;

    // The function to draw the particle on the canvas.
    this.draw = function() {

        // If an image is set draw it
        if(this.image){
            this.context.drawImage(this.image, this.x-128, this.y-128);
            // If the image is being rendered do not draw the circle so break out of the draw function
            return;
        }
        // Draw the circle as before, with the addition of using the position and the radius from this object.
        this.context.beginPath();
        this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
        this.context.fillStyle = "rgba(0, 255, 255, 1)";
        this.context.fill();
        this.context.closePath();
    };

    // Update the particle.
    this.update = function() {
        // Update the position of the particle with the addition of the velocity.
        this.x += this.xVelocity;
        this.y += this.yVelocity;

        // Check if has crossed the right edge
        if (this.x >= canvasWidth) {
            this.xVelocity = -this.xVelocity;
            this.x = canvasWidth;
        }
        // Check if has crossed the left edge
        else if (this.x <= 0) {
            this.xVelocity = -this.xVelocity;
            this.x = 0;
        }

        // Check if has crossed the bottom edge
        if (this.y >= canvasHeight) {
            this.yVelocity = -this.yVelocity;
            this.y = canvasHeight;
        }

        // Check if has crossed the top edge
        else if (this.y <= 0) {
            this.yVelocity = -this.yVelocity;
            this.y = 0;
        }
    };

    // A function to set the position of the particle.
    this.setPosition = function(x, y) {
        this.x = x;
        this.y = y;
    };

    // Function to set the velocity.
    this.setVelocity = function(x, y) {
        this.xVelocity = x;
        this.yVelocity = y;
    };

    this.setImage = function(image){
        this.image = image;
    }
}

// A function to generate a random number between 2 values
function generateRandom(min, max){
    return Math.random() * (max - min) + min;
}

// The canvas context if it is defined.
var context;

// Initialise the scene and set the context if possible
function init() {
    var canvas = document.getElementById('myCanvas');
    if (canvas.getContext) {

        // Set the context variable so it can be re-used
        context = canvas.getContext('2d');

        // Create the particles and set their initial positions and velocities
        for(var i=0; i < particleCount; ++i){
            var particle = new Particle(context);

            // Set the position to be inside the canvas bounds
            particle.setPosition(generateRandom(0, canvasWidth), generateRandom(0, canvasHeight));

            // Set the initial velocity to be either random and either negative or positive
            particle.setVelocity(generateRandom(-maxVelocity, maxVelocity), generateRandom(-maxVelocity, maxVelocity));
            particles.push(particle);
        }
    }
    else {
        alert("Please use a modern browser");
    }
}

// The function to draw the scene
function draw() {

    // Go through all of the particles and draw them.
    particles.forEach(function(particle) {
        particle.draw();
    });
}

// Update the scene
function update() {
    particles.forEach(function(particle) {
        particle.update();
    });
}

// Initialize the scene
init();

// If the context is set then we can draw the scene (if not then the browser does not support canvas)
if (context) {
    setInterval(function() {
        // Update the scene befoe drawing
        update();

        // Draw the scene
        draw();
    }, 1000 / targetFPS);
}

<commit_msg>fixed updating position<commit_after>var map;
var players;
var player = {markers: [], lat: 0, lng: 0};
var socket;

function setEventHandlers() {
    console.log("connection");
    socket.on("connect", onSocketConnected);
    socket.on("disconnect", onSocketDisconnect);
    socket.on("new player", onNewPlayer);
    socket.on("move player", onMovePlayer);
    socket.on("remove player", onRemovePlayer);
}
function onNewPlayer(p){
    var newPlayer = {id :p.id, markers: [], lat: p.lat, lng: p.lng, hunted: p.hunted};
    players.push(newPlayer);
    console.log("new player");
    initTrace(player, newPlayer);
   // players = [];
}
function onSocketConnected() {
    console.log("Connected to socket server");
    socket.emit("new player", player);
};

function onSocketDisconnect() {
    console.log("Disconnected from socket server");
};

function onMovePlayer(data) {
    for (var i; i<players.length; i++){
        if(players[i].id == data.id){
            players[i] = {id :data.id, markers: [], lat: data.lat, lng: data.lng};
        }
    }
};

function onRemovePlayer(data) {

};

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.640},
      zoom: 19,
      scrollwheel: false,
      zoomControl: false,
      mapTypeControl: false,
      scaleControl: false,
      streetViewControl: false,
      rotateControl: false,
      fullscreenControl: false,
      draggable: false,
      keyboardShortcuts: false
    });
    var icon = {
        url: "img/face.png", // url
        scaledSize: new google.maps.Size(64, 141), // scaled size
        origin: new google.maps.Point(0,0), // origin
        anchor: new google.maps.Point(32, 128) // anchor
    };

    var faceMarker = new google.maps.Marker({
                                                map: map,
                                                icon: icon
                                            });

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        player = {markers: [], lat: pos.lat, lng: pos.lng};
        faceMarker.setPosition(pos);
        map.setCenter(pos);
      }, function() {
        handleLocationError(true, faceMarker, map.getCenter());
      });
    } else {
        handleLocationError(false, faceMarker, map.getCenter());
    }
    players = [];
    initMarkers();
    setInterval(function() {
	getPosition(faceMarker);
	updateTrace();
	socket.emit('update position', player);
    }, 1000);
    socket = io.connect();
    setEventHandlers();
}

function getPosition(faceMarker) {
    navigator.geolocation.getCurrentPosition(function(position) {
	var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
	};
	faceMarker.setPosition(pos);
	map.setCenter(pos);
    }, function() {
	   handleLocationError(true, faceMarker, map.getCenter());
    });
}
function smokeBomb(){
    document.getElementById('myCanvas').style.display = "block";
    /*for (var i = 0; i < players[playerIndex].markers.length ; i++){
        players[playerIndex].markers[i].setMap(null);
    }
    setTimeout(function() { makeVisibleAgain(playerIndex); }, 5000);*/
    setTimeout(function() { makeVisibleAgain(); }, 5000);
}

function makeVisibleAgain(){
    document.getElementById('myCanvas').style.display = "none";
    /*for (var i = 0; i < players[playerIndex].markers.length ; i++){
        players[playerIndex].markers[i].setMap(map);
    }*/
}

function initMarkers(){
    for (var i = 0; i < players.length; i++){
        initTrace(player, players[i]);
    }
}
function initTrace(player, targetPlayer){
    console.log("init trace " + targetPlayer.lat + " and lng " + targetPlayer.lng);
    nbOfPointers = 100; //getDistance(player, targetPlayer);
    xDistance = (targetPlayer.lat - player.lat)/nbOfPointers;
    yDistance = (targetPlayer.lng - player.lng)/nbOfPointers;
    var flightPlanCoordinates = [];
    var angle = Math.atan2(targetPlayer.lng - player.lng , targetPlayer.lat - player.lat)* (180 / Math.PI );
    var image = {
        path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
        rotation: angle
    };
    nbOfShownPointers = nbOfPointers/10;
    for (var i = 0; i < nbOfShownPointers; i++){

        console.log("lat is " + (player.lat + (xDistance *i)) + "  lng is " + (player.lng + (yDistance *i)));
        var p = {lat: player.lat + (xDistance *i), lng: player.lng + (yDistance *i)};
        var marker = new google.maps.Marker({
          position: p,
          map: map,
          icon: image
        });
        targetPlayer.markers.push(marker);
    }
}
function updateTrace(player){
    for (var j = 0; j < players.length; j++)
        for (var i = 0; i < players[j].markers.length; i++){
            var p = {lat: players[j].lat + (xDistance *i), lng: players[j].lng + (yDistance *i)};
            players[j].markers[i] = new google.maps.Marker({
              position: p,
              map: map,
              //icon: image
            });
        }
    }
function handleLocationError(browserHasGeolocation, faceMarker, pos) {
    faceMarker.setPosition(pos);
    console.log(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
}

// Create an array to store our particles
var particles = [];

// The amount of particles to render
var particleCount = 30;

// The maximum velocity in each direction
var maxVelocity = 2;

// The target frames per second (how often do we want to update / redraw the scene)
var targetFPS = 33;

// Set the dimensions of the canvas as variables so they can be used.
var canvasWidth = 400;
var canvasHeight = 400;

// Create an image object (only need one instance)
var imageObj = new Image();

// Once the image has been downloaded then set the image on all of the particles
imageObj.onload = function() {
    particles.forEach(function(particle) {
            particle.setImage(imageObj);
    });
};

// Once the callback is arranged then set the source of the image
imageObj.src = "http://www.blog.jonnycornwell.com/wp-content/uploads/2012/07/Smoke10.png";

// A function to create a particle object.
function Particle(context) {

    // Set the initial x and y positions
    this.x = 0;
    this.y = 0;

    // Set the initial velocity
    this.xVelocity = 0;
    this.yVelocity = 0;

    // Set the radius
    this.radius = 5;

    // Store the context which will be used to draw the particle
    this.context = context;

    // The function to draw the particle on the canvas.
    this.draw = function() {

        // If an image is set draw it
        if(this.image){
            this.context.drawImage(this.image, this.x-128, this.y-128);
            // If the image is being rendered do not draw the circle so break out of the draw function
            return;
        }
        // Draw the circle as before, with the addition of using the position and the radius from this object.
        this.context.beginPath();
        this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
        this.context.fillStyle = "rgba(0, 255, 255, 1)";
        this.context.fill();
        this.context.closePath();
    };

    // Update the particle.
    this.update = function() {
        // Update the position of the particle with the addition of the velocity.
        this.x += this.xVelocity;
        this.y += this.yVelocity;

        // Check if has crossed the right edge
        if (this.x >= canvasWidth) {
            this.xVelocity = -this.xVelocity;
            this.x = canvasWidth;
        }
        // Check if has crossed the left edge
        else if (this.x <= 0) {
            this.xVelocity = -this.xVelocity;
            this.x = 0;
        }

        // Check if has crossed the bottom edge
        if (this.y >= canvasHeight) {
            this.yVelocity = -this.yVelocity;
            this.y = canvasHeight;
        }

        // Check if has crossed the top edge
        else if (this.y <= 0) {
            this.yVelocity = -this.yVelocity;
            this.y = 0;
        }
    };

    // A function to set the position of the particle.
    this.setPosition = function(x, y) {
        this.x = x;
        this.y = y;
    };

    // Function to set the velocity.
    this.setVelocity = function(x, y) {
        this.xVelocity = x;
        this.yVelocity = y;
    };

    this.setImage = function(image){
        this.image = image;
    }
}

// A function to generate a random number between 2 values
function generateRandom(min, max){
    return Math.random() * (max - min) + min;
}

// The canvas context if it is defined.
var context;

// Initialise the scene and set the context if possible
function init() {
    var canvas = document.getElementById('myCanvas');
    if (canvas.getContext) {

        // Set the context variable so it can be re-used
        context = canvas.getContext('2d');

        // Create the particles and set their initial positions and velocities
        for(var i=0; i < particleCount; ++i){
            var particle = new Particle(context);

            // Set the position to be inside the canvas bounds
            particle.setPosition(generateRandom(0, canvasWidth), generateRandom(0, canvasHeight));

            // Set the initial velocity to be either random and either negative or positive
            particle.setVelocity(generateRandom(-maxVelocity, maxVelocity), generateRandom(-maxVelocity, maxVelocity));
            particles.push(particle);
        }
    }
    else {
        alert("Please use a modern browser");
    }
}

// The function to draw the scene
function draw() {

    // Go through all of the particles and draw them.
    particles.forEach(function(particle) {
        particle.draw();
    });
}

// Update the scene
function update() {
    particles.forEach(function(particle) {
        particle.update();
    });
}

// Initialize the scene
init();

// If the context is set then we can draw the scene (if not then the browser does not support canvas)
if (context) {
    setInterval(function() {
        // Update the scene befoe drawing
        update();

        // Draw the scene
        draw();
    }, 1000 / targetFPS);
}

<|endoftext|>


<commit_before>/* jshint undef: true, strict:false, trailing:false, unused:false, -W110 */
/* global $,_,document,window,console,escape,Backbone,exports,WebSocket,process,_NODE_AJAX,angular,jQuery */

///  @title indx-offline.js
///  @author Max Van Kleek
///  @since 2014
///  @see http://github.com/sociam/indx
///  @see http://indx.es
///
///  Javascript ORM client for INDX that makes it easy to
///  read and write objects from one or more INDX data store(s).

///  #### Copying
///  Copyright (C) 2011-2014 Max Van Kleek
///
///  This program is free software: you can redistribute it and/or modify
///  it under the terms of the GNU Affero General Public License, version 3,
///  as published by the Free Software Foundation.
///
///  This program is distributed in the hope that it will be useful,
///  but WITHOUT ANY WARRANTY; without even the implied warranty of
///  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
///  GNU Affero General Public License for more details.
///
///  You should have received a copy of the GNU Affero General Public License
///  along with this program.  If not, see <http://www.gnu.org/licenses/>.
///

angular
	.module('indx')
	.factory('local',function(utils) {

		// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
		var u = utils, log = utils.log, error = utils.error, debug = utils.debug, jQ = jQuery;

		var IndxModel = Backbone.Model.extend({
			/// @arg {String} p - Property to fetch
			/// @return {value || undefined} - Returns this.get('property')[0] if the property exists
			/// returns the id of this object
			getFirst:function(p) { return this.get(p,[])[0]; },
			peek: function(p) { return this.get(p,[])[0]; },
			// @arg {String} p - Property to push on to
			// @arg {value} v - Value to push onto end of p
			// Pushes v onto array of p if exists otherwise creates new array
			push:function(p,v) {
				var ov = this.get(p);
				if (ov !== undefined) {
					ov.push(v);
					return this.trigger('change:'+p,ov);
				}
				this.set(p,[v]);
			},
			// @arg {String} p - Property to push on to
			// @arg {value} v - Value to push onto end of p
			// Pops last element off of property p
			pop:function(p) {
				var result = this.get(p,[]).pop();
				this.trigger('change:'+p,this.get(p));
				return result;
			},
			_allValuesToArrays:function(o) {
				if (!_(o).isObject()) { utils.error(' not an object', o); return o; }
				var this_ = this;
				// ?!?! this isn't doing anything (!!)
				return u.dict(_(o).map(function(v,k) {
					var val = this_._valueToArray(k,v);
					if (u.defined(val)) { return [k,val]; }
					return undefined;
				}).filter(u.defined));
			},
			set:function(k,v,options) {
				// set is tricky because it can be called like
				// set('foo',123) or set({foo:123})
				if (typeof k === 'string') { v = this._valueToArray(k,v);	}
				else {	k = this._allValuesToArrays(k);	}
				return Backbone.Model.prototype.set.apply(this,[k,v,options]);
			},
			fetch:function() {
				console.log('fetch!!!'0;
				return Backbone.model.fetch.apply(this, arguments);
			},
			save:function() {
				console.log('save!!!'0;
				return Backbone.model.save.apply(this, arguments);
			}
		});

		function deleteDB(dbid) {
		    try {
		        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
		        var dbreq = indexedDB.deleteDatabase(dbid);
		        dbreq.onsuccess = function (event) {
		            var db = event.result;
		        };
		        dbreq.onerror = function (event) {
		            console.error("indexedDB.delete Error: " + event.message);
		        };
		    }
		    catch (e) {
		        console.error("Error: " + e.message);
		        //prefer change id of database to start ont new instance
		        console.log("fallback to new database name :" + dbid);
		    }
		}

		var Store = Backbone.Model.extend({
			initialize:function() {
				this.collections_by_boxid = {};
				this.deferreds_by_boxid = {};
			},
			_makeBox:function(bid, make_indexes) {
				u.assert(bid !== undefined, "box id has to be defined");
				var db = {
			 		id:bid,
			 		description:'indx local store',
				 	migrations: [
				 		{
				 			version:1,
				 			migrate:function(transaction, next){
				 				var store = transaction.db.createObjectStore(bid);
				 				next();
				 			}
				 		}
				 	]
				};
				if (make_indexes !== undefined) {
					db.migrations.push({
						version:2,
						migrate:function(transaction, next) {
							try {
								var store = transaction.objectStore(bid);
								make_indexes.map(function(field) {
									store.createIndex(field + "index", field, { unique: false });
						        });
						        next();
						    } catch(e) { console.error(e); }
						}
					});
				}
			 	var DBModel = IndxModel.extend({ database: db, storeName:bid	}),
				 	Collection = Backbone.Collection.extend({
				 		database:db,
				 		storeName:bid,
				 		model: DBModel,
				 		getObj:function(id) {
				 			if (this.get(id) !== undefined) {
				 				return u.dresolve(this.get(id));
				 			}
				 			console.log('doesnt exist, making new ');
				 			return u.dresolve(new this.model({id:id}));
				 		}
				 	});
				this.collections_by_boxid[bid] = Collection;

			 	var collection = new Collection(), d = u.deferred();
			 	collection.fetch().then(function() {
			 		d.resolve(collection);
			 	}).fail(d.reject);
			 	return d.promise();
			},
			getBox:function(bid, make_indexes) {
				if (this.deferreds_by_boxid[bid]) {
					return this.deferreds_by_boxid[bid];
				}
				this.deferreds_by_boxid[bid] = this._makeBox(bid, make_indexes);
				return this.deferreds_by_boxid[bid];
			}
		});

		var s,
		getStore = function() {
				if (!s) { s = new Store(); }
				return s;
		},
		test3 = function(id) {
			var s = getStore();
			var boxid = id || u.guid(6);
			s.getBox(boxid,['name']).then(function(box) {
				var a = window.as = [];
				var ds = u.range(100).map(function(i) {
					var guid = u.guid(6), d_ = u.deferred();
					box.getObj(guid).then(function(x) {
						a.push(x);
						console.log('got obj >> ', x.id);
						x.set({name:['hello','hi', 'goodbye'][i%3], date:i});
						x.save().then(d_.resolve);
					});
					return d_.promise();
				});
				u.when(ds).then(function() {
					var query = new s.collections_by_boxid[boxid]();
					query.fetch({
						conditions: {name:'hello'},
						success: function () {
							console.log('wins ', query.models.length, query.models);
							console.log(query.models.map(function(x) { return x.id; }));
                            // equal(query.models.length, 2, "Should have 2 elements");
                            // deepEqual(theater.pluck("title"), ["Bonjour", "Ciao"], "Should have [\"Bonjour\", \"Ciao\"]");
                        },
						error: function (object, error) {
                            console.error('couldnt query -- ', object, error);
                        }
					}).then(function() {
						console.log('hello and hi hits ', query.length);
					}).fail(function(r) {
						console.error(r);
					});
				}).fail(function(x) { console.error('sad '); });
			}).fail(function(err) {	console.error('couldnt get box '); 	});
		};
		setTimeout(function() { test3(); }, 100);

		return {
			getStore : getStore,
			test : function(boxid) {
				var s = this.getStore();
				s.getBox(boxid || 'a').then(function(box) {
					window.box = box;
					var ds = [];
					u.range(10).map(function(x) {
						var uid = u.guid(10);
						// var result = box.create({id:uid, test:u.guid(5), message:'hello'});
						var obj = new box.model({id:uid, test:u.guid(5), message:'hello'});
						ds.push(obj.save());
					});
					u.when(ds)
						.then(function(x) { console.log('all done!'); })
						.fail(function(e) { console.error(e); });
				}).fail(function(err) {
					console.error('couldnt get box ');
				});
			},
			test2 : function(boxid) {
				var s = this.getStore();
				s.getBox(boxid || 'a').then(function(box) {
					var guid = u.guid();
					box.getObj(guid).then(function(x) {
						console.log('created x >> ');
						u.assert(x.id == guid, 'ids didnt match');
						x.set({baby:true});
						x.save();
					});
				}).fail(function(err) {
					console.error('couldnt get box ');
				});
			},
			test3 : test3,
			deleteDB:deleteDB
		};

	});
	<commit_msg>indexeddb adapter<commit_after>/* jshint undef: true, strict:false, trailing:false, unused:false, -W110 */
/* global $,_,document,window,console,escape,Backbone,exports,WebSocket,process,_NODE_AJAX,angular,jQuery */

///  @title indx-offline.js
///  @author Max Van Kleek
///  @since 2014
///  @see http://github.com/sociam/indx
///  @see http://indx.es
///
///  Javascript ORM client for INDX that makes it easy to
///  read and write objects from one or more INDX data store(s).

///  #### Copying
///  Copyright (C) 2011-2014 Max Van Kleek
///
///  This program is free software: you can redistribute it and/or modify
///  it under the terms of the GNU Affero General Public License, version 3,
///  as published by the Free Software Foundation.
///
///  This program is distributed in the hope that it will be useful,
///  but WITHOUT ANY WARRANTY; without even the implied warranty of
///  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
///  GNU Affero General Public License for more details.
///
///  You should have received a copy of the GNU Affero General Public License
///  along with this program.  If not, see <http://www.gnu.org/licenses/>.
///

angular
	.module('indx')
	.factory('local',function(utils) {

		// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
		var u = utils, log = utils.log, error = utils.error, debug = utils.debug, jQ = jQuery;

		function deleteDB(dbid) {
		    try {
		        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
		        var dbreq = indexedDB.deleteDatabase(dbid);
		        dbreq.onsuccess = function (event) {
		            var db = event.result;
		        };
		        dbreq.onerror = function (event) {
		            console.error("indexedDB.delete Error: " + event.message);
		        };
		    }
		    catch (e) {
		        console.error("Error: " + e.message);
		        //prefer change id of database to start ont new instance
		        console.log("fallback to new database name :" + dbid);
		    }
		}
		var IndxModel = Backbone.Model.extend({
			initialize:function(attrs, options) {
				this.box = options.box;
			},
			save:function() {
				return this.box.save(this);
			},
			fetch:function() {
				console.log('fetch unnecessary --  ');
				return;
			}
		});
		var IndxCollection = Backbone.Collection.extend({
			model:IndxModel
		});

		var Box = Backbone.Model.extend({
			initialize:function(attribs) {
				var bid = attribs.id;
				var db = {
			 		id:bid,
			 		description:'indx local store',
				 	migrations: [
				 		{
				 			version:1,
				 			migrate:function(transaction, next){
				 				var store = transaction.db.createObjectStore(bid);
				 				next();
				 			}
				 		}
				 	]
				};
				if (attribs.make_indexes !== undefined) {
					db.migrations.push({
						version:2,
						migrate:function(transaction, next) {
							try {
								var store = transaction.objectStore(bid);
								attribs.make_indexes.map(function(field) {
									store.createIndex(field + "index", field, { unique: false });
						        });
						        next();
						    } catch(e) { console.error(e); }
						}
					});
				}
				// internal models only!
				this.model = Backbone.Model.extend({ database: db, storeName:bid });
				// cache for external models
				this._objcache = new IndxCollection();
			},
			_createModelForID: function(id) {
				var m = new IndxModel({id:id},{box: this});
				this._objcache.add(m);
				return m;
			},
			save:function(models) {
				console.log('save >> ', models);
				var this_ = this, newmodels = [], saving = {};
				var serialise = function(val, saving, newmodels) {
					if (!_.isObject(val)) {	return val;	}
					if (_.isArray(val)) {
						return val.map(function(v) { return serialise(v,saving,newmodels); });
					}
					if (_.isObject(val) && val.id !== undefined) {
						var sobj = { "@id": val.id };
						if (saving[val.id] === undefined && newmodels.indexOf(val) <= 0) {
							console.log('newmodels push');
							newmodels.push(val);
						}
						return sobj;
					}
					u.assert(false, "didnt know how to serialise");
					return undefined;
				}, dosave = function(models, dfds, newmodels) {
					console.log('dosave models >> ', models);
					return u.when(models.map(function(model) {
						var lm = new this_.model({id:model.id});
						dfds[model.id] = u.deferred();
						_(model.attributes).map(function(v,k) {	lm.set(k,serialise(v, dfds, newmodels));	});
						lm.save().then(dfds[model.id].resolve).fail(dfds[model.id].reject);
						return dfds[model.id];
					}));
				}, recurse = function(saving, newmodels) {
					var modchunk = newmodels.splice(0, newmodels.length);
					var d = u.deferred();
					dosave(modchunk, saving, newmodels).then(function() {
						if (newmodels.length > 0) {
							recurse(saving, newmodels).then(d.resolve).fail(d.reject);
							return;
						}
						d.resolve(); // resolve righ taway to go on to the next level
					}).fail(d.reject);
					return d.promise();
				};

				// prime the saving/newmodels pump
				(_(models).isArray() ? models : [models]).map(function(m) {
					serialise(m, saving, newmodels);
				});
				console.log("after priming >> ", saving, newmodels);
				recurse(saving, newmodels);
				return u.when(saving);
			},
			getObj:function(objid) {
				// getObj always returns a promise
				// console.debug(' getObj() >> ', objid);

				u.assert(typeof objid === 'string' || typeof objid === 'number' || _.isArray(objid), "objid has to be a number or string or an array of such things");

				var ids = _.isArray(objid) ? objid : [objid], this_ = this,
					fetching = {}, newids = [], skeletons = {}, objcache = this._objcache;

				var deserialise_obj = function(id, skelmodels, deferredset, newids_) {
					// case 1 : deserialising now
					if (skelmodels[id] !== undefined) { return skelmodels[id];	}
					// case 2: already deserialised
					var cachedobj;
					if ((cachedobj = objcache.get(id)) !== undefined) {
						deferredset[id] = u.dresolve(cachedobj); // create a new placeholder
						skelmodels[id] = cachedobj;
						return cachedobj;
					}
					// case 3 : not deserialised yet
					skelmodels[id] = this_._createModelForID(id);
					deferredset[id] = u.deferred(); // create a new placeholder
					newids_.push(id);
					return skelmodels[id];
				};
				var deserialise = function(s_obj, into_model, deferredset, silent, skels, newids_) {
					// resolves all of the properties into things that we have or
					// know about
					var _des = function(val) {
						// object
						if (!_.isObject(val)) {	return val;	}
						if (_.isObject(val) && val.hasOwnProperty('@id')) {
							return deserialise_obj(val['@id'], skels, deferredset, newids_);
						}
						console.error('couldnt deserialise ', val);
						return undefined;
					};
					_(s_obj).map(function(vals, key) {
						into_model.set(key,_.isArray(vals) ? vals.map(_des) : _des(vals),{silent: silent});
					});
				};
				var fetch = function(ids, skels, deferredset, newids_) {
					var d = u.deferred();
					var fetches = ids.map(function(id) {
						var inner_m = new this_.model({id:id}),
							di = u.deferred();
						inner_m.fetch().then(function() {
							console.log('fetched inner_m!! ', inner_m.id, inner_m.attributes);
							deserialise(inner_m.attributes, skels[id], deferredset, true, skels, newids_);
							deferredset[id].resolve(skels[id]);
							di.resolve(skels[id]);
						}).fail(function(e) {
							console.error('didnt exist, new object');
							// deserialise(inner_m.attributes, skels[id], deferredset, true, skels, newids_);
							deferredset[id].resolve(skels[id]);
							di.resolve(skels[id]);
						});
						//

						return di.promise();
					});
					u.when(fetches).then(d.resolve).fail(d.reject);
					return d.promise();
				};

				// prime the newids / deferreds with all of the next guys we have to fetch
				ids.map(function(id) {
					deserialise_obj(id, skeletons, fetching, newids);
				});
				var ds = _(fetching).values();

				var recurse = function(ids) {
					var idchunk = newids.splice(0,newids.length);
					var d = u.deferred();
					fetch(idchunk, skeletons, fetching, newids).then(function() {
						if (newids.length > 0) {
							recurse(newids).then(d.resolve).fail(d.reject);
							return;
						}
						d.resolve(); // resolve righ taway to go on to the next level
					}).fail(d.reject);
					return d.promise();
				};

				var d0 = u.deferred();
				recurse(newids).then(function() {
					if (_.isArray(objid)) {
						u.when(objid.map(function(x) { return fetching[x]; })).then(d0.resolve).fail(d0.reject);
					} else {
						fetching[objid].then(d0.resolve).fail(d0.reject);
					}
				}).fail(d0.reject);
				return d0.promise();
			},

		});

		var Store = Backbone.Model.extend({
			initialize:function() {
				this.boxes =  new Backbone.Collection({model:Box});
			},
			getBox:function(bid, make_indexes) {
				if (!this.boxes.get(bid)) {
					this.boxes.add(new Box({id:bid,make_indexes:make_indexes}));
				}
				return u.dresolve(this.boxes.get(bid));
			}
		});

		var s,
			getStore = function() {
				if (!s) { s = new Store(); }
				return s;
			},
			tests = {
				test3 : function(id) {
					var s = getStore();
					var boxid = id || u.guid(6);
					s.getBox(boxid,['name']).then(function(box) {
						var a = window.as = [];
						var ds = u.range(100).map(function(i) {
							var guid = u.guid(6), d_ = u.deferred();
							box.getObj(guid).then(function(x) {
								a.push(x);
								console.log('got obj >> ', x.id);
								x.set({name:['hello','hi', 'goodbye'][i%3], date:i});
								x.save().then(d_.resolve);
							});
							return d_.promise();
						});
						u.when(ds).then(function() {
							var query = new s.collections_by_boxid[boxid]();
							query.fetch({
								conditions: {name:'hello'},
								success: function () {
									console.log('wins ', query.models.length, query.models);
									console.log(query.models.map(function(x) { return x.id; }));
		                            // equal(query.models.length, 2, "Should have 2 elements");
		                            // deepEqual(theater.pluck("title"), ["Bonjour", "Ciao"], "Should have [\"Bonjour\", \"Ciao\"]");
		                        },
								error: function (object, error) {
		                            console.error('couldnt query -- ', object, error);
		                        }
							}).then(function() {
								console.log('hello and hi hits ', query.length);
							}).fail(function(r) {
								console.error(r);
							});
						}).fail(function(x) { console.error('sad '); });
					}).fail(function(err) {	console.error('couldnt get box '); 	});
				},
				test : function(boxid) {
					var s = getStore(), ds = {}, d = u.deferred();
					s.getBox(boxid || 'a').then(function(box) {
						window.box = box;
						var ds = [];
						u.range(10).map(function(x) {
							var uid = u.guid(10);
							ds[uid] = u.deferred();
							box.getObj(uid).then(function(obj) {
								console.log('getObj completed >> ', obj.attributes);
								obj.set({name:'hello', thing:u.guid()});
								obj.save().then(ds[uid].resolve).fail(ds[uid].reject);
							});
						});
						u.when(_(ds).values()).then(function(x) {
							console.log('all done!');
							d.resolve(_(ds).keys());
						}).fail(function(e) {
							console.error(e);
							d.reject();
						});
					}).fail(function(err) {
						console.error('couldnt get box ');
					});
					return d.promise();
				},
				test2 : function(boxid) {
					var s = getStore(), ds = {}, d = u.deferred();
					s.getBox(boxid || 'a').then(function(box) {
						var ds = [], uids = u.range(10).map(function(x) {
							var uid = u.guid(10);
							ds[uid] = u.deferred();
							return uid;
						});
						box.getObj(uids).then(function(objs) {
							console.log('getObjs completed >> ', objs);
							objs.map(function(obj) {
								obj.set({name:'hello', first:objs[0],all:objs,thing:u.guid()});
							});
							objs.map(function(obj) {
								obj.save().then(ds[obj.id].resolve).fail(ds[obj.id].reject);
							});
						});
						u.when(_(ds).values()).then(function(x) {
							console.log('all done!');
							d.resolve(_(ds).keys());
						}).fail(function(e) {
							console.error(e);
							d.reject();
						});
					}).fail(function(err) {
						console.error('couldnt get box ');
					});
					return d.promise();
				}
			};

		setTimeout(function() {
			tests.test2().then(function(ids) {
				getStore().getBox('a').then(function(b) {
					console.log('test continuation >>');
					window.b = b;
					console.log('getting object >> ', ids[0]);
					b.getObj(ids[0]).then(function(o) {
						window.oo = o;
						console.log('object >> ', o);
					});
				}).fail(function() { console.error('sad'); });
			});
		}, 100);

		return {
			getStore : getStore,
			tests : tests,
			deleteDB:deleteDB
		};
	});
	<|endoftext|>


<commit_before>/**
 * @description Checking file size.
 */

"use strict";

import 'babel-polyfill';
import fs from 'fs';
import clc from 'cli-color';
import filesize from 'filesize';

/**
 * @param {string} filePath - The file of the target.
 * @return {Promise}
 */
const getSize = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stats) => {
      if (err) {
        reject(err);
      }

      resolve(stats.size); // Byte
    });
  });
};

/**
 * @description Check file size and print message.
 * @param {string} filePath - The file of the target
 * @param {number} limitSize - Threshold for the file.
 */
const checkFileSize = async (filePath, limitSize) => {
  const fileSize         = await getSize(filePath);
  const readableFileSize = filesize(fileSize);

  if (Number(limitSize) < fileSize) {
    console.log(`[${clc.red('NG')}] ${filePath} ${fileSize}`);
    return;
  }

  console.log(`[${clc.green('OK')}] ${filePath} ${fileSize}`);
};

export default checkFileSize;
<commit_msg>fix: use readable string for showing file size<commit_after>/**
 * @description Checking file size.
 */

"use strict";

import 'babel-polyfill';
import fs from 'fs';
import clc from 'cli-color';
import filesize from 'filesize';

/**
 * @param {string} filePath - The file of the target.
 * @return {Promise}
 */
const getSize = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stats) => {
      if (err) {
        reject(err);
      }

      resolve(stats.size); // Byte
    });
  });
};

/**
 * @description Check file size and print message.
 * @param {string} filePath - The file of the target
 * @param {number} limitSize - Threshold for the file.
 */
const checkFileSize = async (filePath, limitSize) => {
  const fileSize         = await getSize(filePath);
  const readableFileSize = filesize(fileSize);

  if (Number(limitSize) < fileSize) {
    console.log(`[${clc.red('NG')}] ${filePath} ${readableFileSize}`);
    return;
  }

  console.log(`[${clc.green('OK')}] ${filePath} ${readableFileSize}`);
};

export default checkFileSize;
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')

const appPaths = require('../app-paths')
const { log, warn } = require('../helpers/logger')
const ensureConsistency = require('./ensure-consistency')
const { capVersion } = require('./cap-cli')

function getAndroidMainActivity (capVersion, appId) {
  if (capVersion === 1) {
    return `
package ${appId};
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class EnableHttpsSelfSigned {
  public static void enable(WebView webview) {
    webview.setWebViewClient(new WebViewClient() {
      @Override
      public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
        handler.proceed();
      }
    });
  }
}`
  }

  // capVersion > 1
  return `
package ${appId};
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import com.getcapacitor.Bridge;
import com.getcapacitor.BridgeWebViewClient;

public class EnableHttpsSelfSigned {
  public static void enable(Bridge bridge) {
    bridge.getWebView().setWebViewClient(new BridgeWebViewClient(bridge) {
      @Override
      public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
        handler.proceed();
      }
    });
  }
}`
}
class CapacitorConfig {
  prepare (cfg) {
    ensureConsistency()

    this.pkg = require(appPaths.resolve.app('package.json'))

    this.__updateCapPkg(cfg, this.pkg)
    log(`Updated src-capacitor/package.json`)

    this.tamperedFiles = []

    const capJsonPath = this.__getCapJsonPath(cfg)
    const capJson = require(capJsonPath)

    this.tamperedFiles.push({
      path: capJsonPath,
      name: 'capacitor.config.json',
      content: this.__updateCapJson(cfg, capJson),
      originalContent: JSON.stringify(capJson, null, 2)
    })

    this.__save()
  }

  reset () {
    this.tamperedFiles.forEach(file => {
      file.content = file.originalContent
    })

    this.__save()
    this.tamperedFiles = []
  }

  __save () {
    this.tamperedFiles.forEach(file => {
      fs.writeFileSync(file.path, file.content, 'utf8')
      log(`Updated ${file.name}`)
    })
  }

  __getCapJsonPath (cfg) {
    let jsonPath

    if (cfg.ctx.platformName === 'android') {
      jsonPath = './android/app/src/main/assets/capacitor.config.json'
    }
    else if (cfg.ctx.platformName === 'ios') {
      jsonPath = './ios/App/App/capacitor.config.json'
    }
    else {
      jsonPath = './capacitor.config.json'
    }

    return path.join(appPaths.resolve.capacitor(jsonPath))
  }

  __updateCapJson (cfg, originalCapCfg) {
    const capJson = { ...originalCapCfg }

    capJson.appName = cfg.capacitor.appName || this.pkg.productName || 'Quasar App'
    capJson.bundledWebRuntime = false

    if (cfg.ctx.dev) {
      capJson.server = capJson.server || {}
      capJson.server.url = cfg.build.APP_URL
    }
    else {
      capJson.webDir = 'www'

      // ensure we don't run from a remote server
      if (capJson.server && capJson.server.url) {
        delete capJson.server.url
      }
    }

    return JSON.stringify(capJson, null, 2)
  }

  __updateCapPkg (cfg, pkg) {
    const capPkgPath = appPaths.resolve.capacitor('package.json')
    const capPkg = require(capPkgPath)

    Object.assign(capPkg, {
      name: cfg.capacitor.appName || pkg.name,
      version: cfg.capacitor.version || pkg.version,
      description: cfg.capacitor.description || pkg.description,
      author: pkg.author
    })

    fs.writeFileSync(capPkgPath, JSON.stringify(capPkg, null, 2), 'utf-8')
  }

  prepareSSL (add, target) {
    if (target === 'ios') {
      this.__handleSSLonIOS(add)
    }
    else {
      this.__handleSSLonAndroid(add)
    }
  }

  __handleSSLonIOS (add) {
    const file = appPaths.resolve.capacitor('node_modules/@capacitor/ios/ios/Capacitor/Capacitor/CAPBridgeViewController.swift')
    const needle = 'public func getWebView() -> WKWebView {'
    const content = `
  // The following part was dynamically added by Quasar.
  // This should NOT be part of the app when building for production,
  // and it will be removed by Quasar automatically on "quasar build":
  public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let cred = URLCredential(trust: challenge.protectionSpace.serverTrust!)
    completionHandler(.useCredential, cred)
  }

  `

    if (add) {
      this.__injectIntoFile(file, needle, content)
    }
    else {
      this.__removeFromFile(file, content)
    }
  }

  __injectIntoFile (file, needle, content) {
    const shortFilename = path.basename(file)

    const sslWarn = () => {
      warn()
      warn()
      warn()
      warn()
      warn(`${shortFilename} not found or content is unrecognized.`)
      warn(`Your App will revoke the devserver's SSL certificate.`)
      warn(`Please disable HTTPS from quasar.conf.js > devServer > https`)
      warn()
      warn()
      warn()
      warn()
    }

    if (!fs.existsSync(file)) {
      sslWarn()
      return
    }

    const originalContent = fs.readFileSync(file, 'utf-8')

    if (originalContent.indexOf(content) > -1) {
      // it's already there
      return
    }

    const index = originalContent.indexOf(needle)

    if (index === -1) {
      sslWarn()
      return
    }

    const newContent = originalContent.substring(0, index) + content + originalContent.substring(index)

    fs.writeFileSync(file, newContent, 'utf-8')
  }

  __removeFromFile (file, content) {
    if (!fs.existsSync(file)) {
      return
    }

    const originalContent = fs.readFileSync(file, 'utf-8')
    const index = originalContent.indexOf(content)

    if (index > -1) {
      const newContent = originalContent.replace(content, '')
      fs.writeFileSync(file, newContent, 'utf-8')
    }
  }

  __handleSSLonAndroid (add) {
    const fglob = require('fast-glob')
    const capacitorSrcPath = appPaths.resolve.capacitor('android/app/src/main/java')
    let mainActivityPath = fglob.sync(`**/MainActivity.java`, { cwd: capacitorSrcPath, absolute: true })

    if (mainActivityPath.length > 0) {
      if (mainActivityPath.length > 1) {
        warn(`Found multiple matches for MainActivity.java file, https might not work. Using file ${mainActivityPath[0]}.`)
      }
      mainActivityPath = mainActivityPath[0]
    }
    else if (mainActivityPath.length === 0) {
      warn()
      warn('IMPORTANT! Could not find MainActivity.java file and therefore cannot enable devServer: https support.')
      warn()
      return
    }

    const enableHttpsSelfSignedPath = path.join(path.dirname(mainActivityPath), 'EnableHttpsSelfSigned.java')

    if (fs.existsSync(mainActivityPath)) {
      let mainActivity = fs.readFileSync(mainActivityPath, 'utf8')

      const sslString = `
    if (BuildConfig.DEBUG) {
      EnableHttpsSelfSigned.enable(${capVersion === 1 ? 'findViewById(R.id.webview)' : 'this.bridge'});
    }
      `

      if (add) {
        // Allow unsigned certificates in MainActivity
        if (!/EnableHttpsSelfSigned\.enable/.test(mainActivity)) {
          mainActivity = mainActivity.replace(
            /this\.init\(.*}}\);/ms,
            match => `${match}
${sslString}
              `
          )
        }

        // Add helper file
        if (!fs.existsSync(enableHttpsSelfSignedPath)) {
          const appId = mainActivity.match(/package ([\w\.]*);/)[1]

          fs.writeFileSync(
            enableHttpsSelfSignedPath,
            getAndroidMainActivity(capVersion, appId)
          )
        }
      }
      else {
        if (/EnableHttpsSelfSigned\.enable/.test(mainActivity)) {
          mainActivity = mainActivity.replace(sslString, '')
        }

        if (fs.existsSync(enableHttpsSelfSignedPath)) {
          fs.unlinkSync(enableHttpsSelfSignedPath)
        }
      }

      fs.writeFileSync(mainActivityPath, mainActivity, 'utf-8')
    }
  }
}

module.exports = CapacitorConfig
<commit_msg>fix(app/Capacitor): HTTPS server with iOS (path to bridge file within @capacitor/ios changed) #7845<commit_after>const fs = require('fs')
const path = require('path')

const appPaths = require('../app-paths')
const { log, warn } = require('../helpers/logger')
const ensureConsistency = require('./ensure-consistency')
const { capVersion } = require('./cap-cli')

function getAndroidMainActivity (capVersion, appId) {
  if (capVersion === 1) {
    return `
package ${appId};
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class EnableHttpsSelfSigned {
  public static void enable(WebView webview) {
    webview.setWebViewClient(new WebViewClient() {
      @Override
      public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
        handler.proceed();
      }
    });
  }
}`
  }

  // capVersion > 1
  return `
package ${appId};
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import com.getcapacitor.Bridge;
import com.getcapacitor.BridgeWebViewClient;

public class EnableHttpsSelfSigned {
  public static void enable(Bridge bridge) {
    bridge.getWebView().setWebViewClient(new BridgeWebViewClient(bridge) {
      @Override
      public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
        handler.proceed();
      }
    });
  }
}`
}
class CapacitorConfig {
  prepare (cfg) {
    ensureConsistency()

    this.pkg = require(appPaths.resolve.app('package.json'))

    this.__updateCapPkg(cfg, this.pkg)
    log(`Updated src-capacitor/package.json`)

    this.tamperedFiles = []

    const capJsonPath = this.__getCapJsonPath(cfg)
    const capJson = require(capJsonPath)

    this.tamperedFiles.push({
      path: capJsonPath,
      name: 'capacitor.config.json',
      content: this.__updateCapJson(cfg, capJson),
      originalContent: JSON.stringify(capJson, null, 2)
    })

    this.__save()
  }

  reset () {
    this.tamperedFiles.forEach(file => {
      file.content = file.originalContent
    })

    this.__save()
    this.tamperedFiles = []
  }

  __save () {
    this.tamperedFiles.forEach(file => {
      fs.writeFileSync(file.path, file.content, 'utf8')
      log(`Updated ${file.name}`)
    })
  }

  __getCapJsonPath (cfg) {
    let jsonPath

    if (cfg.ctx.platformName === 'android') {
      jsonPath = './android/app/src/main/assets/capacitor.config.json'
    }
    else if (cfg.ctx.platformName === 'ios') {
      jsonPath = './ios/App/App/capacitor.config.json'
    }
    else {
      jsonPath = './capacitor.config.json'
    }

    return path.join(appPaths.resolve.capacitor(jsonPath))
  }

  __updateCapJson (cfg, originalCapCfg) {
    const capJson = { ...originalCapCfg }

    capJson.appName = cfg.capacitor.appName || this.pkg.productName || 'Quasar App'
    capJson.bundledWebRuntime = false

    if (cfg.ctx.dev) {
      capJson.server = capJson.server || {}
      capJson.server.url = cfg.build.APP_URL
    }
    else {
      capJson.webDir = 'www'

      // ensure we don't run from a remote server
      if (capJson.server && capJson.server.url) {
        delete capJson.server.url
      }
    }

    return JSON.stringify(capJson, null, 2)
  }

  __updateCapPkg (cfg, pkg) {
    const capPkgPath = appPaths.resolve.capacitor('package.json')
    const capPkg = require(capPkgPath)

    Object.assign(capPkg, {
      name: cfg.capacitor.appName || pkg.name,
      version: cfg.capacitor.version || pkg.version,
      description: cfg.capacitor.description || pkg.description,
      author: pkg.author
    })

    fs.writeFileSync(capPkgPath, JSON.stringify(capPkg, null, 2), 'utf-8')
  }

  prepareSSL (add, target) {
    if (target === 'ios') {
      this.__handleSSLonIOS(add)
    }
    else {
      this.__handleSSLonAndroid(add)
    }
  }

  __getIosCapacitorBridgeFile () {
    // we need to try multiple files because
    // @capacitor/ios changed the location during its v2
    const fileList = [
      'node_modules/@capacitor/ios/ios/Capacitor/Capacitor/CAPBridgeViewController.swift',
      'node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController.swift'
    ]

    for (let i = 0; i < fileList.length; i++) {
      let file = appPaths.resolve.capacitor(fileList[i])
      if (fs.existsSync(file)) {
        return file
      }
    }
  }

  __handleSSLonIOS (add) {
    const file = this.__getIosCapacitorBridgeFile()
    const needle = 'public func getWebView() -> WKWebView {'
    const content = `
  // The following part was dynamically added by Quasar.
  // This should NOT be part of the app when building for production,
  // and it will be removed by Quasar automatically on "quasar build":
  public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let cred = URLCredential(trust: challenge.protectionSpace.serverTrust!)
    completionHandler(.useCredential, cred)
  }

  `

    if (add) {
      this.__injectIntoFile(file, needle, content)
    }
    else {
      this.__removeFromFile(file, content)
    }
  }

  __injectIntoFile (file, needle, content) {
    const sslWarn = () => {
      const shortFilename = path.basename(file)

      warn()
      warn()
      warn()
      warn()
      warn(`${shortFilename} not found or content is unrecognized.`)
      warn(`Your App will revoke the devserver's SSL certificate.`)
      warn(`Please disable HTTPS from quasar.conf.js > devServer > https`)
      warn()
      warn()
      warn()
      warn()
    }

    if (!file) {
      sslWarn()
      return
    }

    const originalContent = fs.readFileSync(file, 'utf-8')

    if (originalContent.indexOf(content) > -1) {
      // it's already there
      return
    }

    const index = originalContent.indexOf(needle)

    if (index === -1) {
      sslWarn()
      return
    }

    const newContent = originalContent.substring(0, index) + content + originalContent.substring(index)

    fs.writeFileSync(file, newContent, 'utf-8')
  }

  __removeFromFile (file, content) {
    if (!file) {
      return
    }

    const originalContent = fs.readFileSync(file, 'utf-8')
    const index = originalContent.indexOf(content)

    if (index > -1) {
      const newContent = originalContent.replace(content, '')
      fs.writeFileSync(file, newContent, 'utf-8')
    }
  }

  __handleSSLonAndroid (add) {
    const fglob = require('fast-glob')
    const capacitorSrcPath = appPaths.resolve.capacitor('android/app/src/main/java')
    let mainActivityPath = fglob.sync(`**/MainActivity.java`, { cwd: capacitorSrcPath, absolute: true })

    if (mainActivityPath.length > 0) {
      if (mainActivityPath.length > 1) {
        warn(`Found multiple matches for MainActivity.java file, https might not work. Using file ${mainActivityPath[0]}.`)
      }
      mainActivityPath = mainActivityPath[0]
    }
    else if (mainActivityPath.length === 0) {
      warn()
      warn('IMPORTANT! Could not find MainActivity.java file and therefore cannot enable devServer: https support.')
      warn()
      return
    }

    const enableHttpsSelfSignedPath = path.join(path.dirname(mainActivityPath), 'EnableHttpsSelfSigned.java')

    if (fs.existsSync(mainActivityPath)) {
      let mainActivity = fs.readFileSync(mainActivityPath, 'utf8')

      const sslString = `
    if (BuildConfig.DEBUG) {
      EnableHttpsSelfSigned.enable(${capVersion === 1 ? 'findViewById(R.id.webview)' : 'this.bridge'});
    }
      `

      if (add) {
        // Allow unsigned certificates in MainActivity
        if (!/EnableHttpsSelfSigned\.enable/.test(mainActivity)) {
          mainActivity = mainActivity.replace(
            /this\.init\(.*}}\);/ms,
            match => `${match}
${sslString}
              `
          )
        }

        // Add helper file
        if (!fs.existsSync(enableHttpsSelfSignedPath)) {
          const appId = mainActivity.match(/package ([\w\.]*);/)[1]

          fs.writeFileSync(
            enableHttpsSelfSignedPath,
            getAndroidMainActivity(capVersion, appId)
          )
        }
      }
      else {
        if (/EnableHttpsSelfSigned\.enable/.test(mainActivity)) {
          mainActivity = mainActivity.replace(sslString, '')
        }

        if (fs.existsSync(enableHttpsSelfSignedPath)) {
          fs.unlinkSync(enableHttpsSelfSignedPath)
        }
      }

      fs.writeFileSync(mainActivityPath, mainActivity, 'utf-8')
    }
  }
}

module.exports = CapacitorConfig
<|endoftext|>


<commit_before>// ==UserScript==
// @name        和谐华新助手
// @include     http://bbs.huasing.org/*
// @version     0.22
// @description Hide posts from penzi
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js
// @grant       GM_addStyle
// ==/UserScript==

// 可以自己加的 ^_^ 我这是测试数据而已 不是攻击啊，别喷我
var penzi = ['唐甬', 'materialist','西东南北风','flying2010','dnegel']

window.jQuery = window.$ = jQuery

// hide post in 华新鲜事
$('div.brow2 div[class="ccol6 brow2h"] a[class="nickname bblack"]').each(function(index, element) {
    if ($.inArray($(this).attr('title'), penzi) > -1) {
        $(this).parents().eq(2).hide();
    }
});

// hide post in 版面
$('div.brow2 div[class="bcol5 brow2h"] a[class="nickname bblack"]').each(function(index, element) {
    if ($.inArray($(this).attr('title'), penzi) > -1) {
        $(this).parents().eq(2).hide();
    }
});

// hide 在帖子里的
$('div.authordiv div:first-child>a:first-child').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(1).hide();
        $(this).parents().eq(1).next().hide();
    }
});

// hide 漂浮出来的frame里的
$('div[id^="i-"]>div a[href^="user.php"]>font>b').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(3).hide();
    }
});

// --------------------- wap ---------------------

// hide post in 华新鲜事
$('.list>ul>li>em>a:nth-child(2)').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(1).hide();
    }
});

// hide 在帖子里的
$('p>em>a:nth-child(1)').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(1).hide();
    }
});

// hide 首页
$('.con2>ul>li>a:nth-child(3)').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(0).hide();
    }
});
<commit_msg>add penzi pItt<commit_after>// ==UserScript==
// @name        和谐华新助手
// @include     http://bbs.huasing.org/*
// @version     0.22
// @description Hide posts from penzi
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js
// @grant       GM_addStyle
// ==/UserScript==

// 可以自己加的 ^_^ 我这是测试数据而已 不是攻击啊，别喷我
var penzi = ['唐甬', 'materialist', '西东南北风', 'flying2010', 'dnegel', 'pItt']

window.jQuery = window.$ = jQuery

// hide post in 华新鲜事
$('div.brow2 div[class="ccol6 brow2h"] a[class="nickname bblack"]').each(function(index, element) {
    if ($.inArray($(this).attr('title'), penzi) > -1) {
        $(this).parents().eq(2).hide();
    }
});

// hide post in 版面
$('div.brow2 div[class="bcol5 brow2h"] a[class="nickname bblack"]').each(function(index, element) {
    if ($.inArray($(this).attr('title'), penzi) > -1) {
        $(this).parents().eq(2).hide();
    }
});

// hide 在帖子里的
$('div.authordiv div:first-child>a:first-child').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(1).hide();
        $(this).parents().eq(1).next().hide();
    }
});

// hide 漂浮出来的frame里的
$('div[id^="i-"]>div a[href^="user.php"]>font>b').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(3).hide();
    }
});

// --------------------- wap ---------------------

// hide post in 华新鲜事
$('.list>ul>li>em>a:nth-child(2)').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(1).hide();
    }
});

// hide 在帖子里的
$('p>em>a:nth-child(1)').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(1).hide();
    }
});

// hide 首页
$('.con2>ul>li>a:nth-child(3)').each(function(index, element) {
    if ($.inArray($(this).text(), penzi) > -1) {
        $(this).parents().eq(0).hide();
    }
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright (c) 2017 Google Inc. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * Code distributed by Google as part of this project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
"use strict";

 // TODO(mmandlis): rewrite the tests.

const assert = require('chai').assert;
var Slot = require("../slot.js");
let util = require('./test-util.js');

describe('slot', function() {
  // it('associate and disassociate slot', function() {
  //   let slot = new Slot('slotid');
  //   assert.isFalse(slot.isAssociated());
  //
  //   // cannot disassociate not associated slot.
  //   assert.throws(() => { slot.disassociateParticle() });
  //
  //   // associate slot.
  //   let particleSpec = util.initParticleSpec('particle');
  //   slot.associateWithParticle(particleSpec);
  //   assert.isTrue(slot.isAssociated());
  //   // cannot associate slot that is already associated.
  //   assert.throws(() => { slot.associateWithParticle(particleSpec); });
  // });
  //
  // it('add and provide pending requests', function() {
  //   let slot = new Slot('slotid');
  //   assert.isFalse(slot.isAssociated());
  //
  //   let count = 0;
  //   let handler = () => { count++; };
  //
  //   slot.addPendingRequest(util.initParticleSpec('particle1'), handler, {});
  //   // Add request for the same particle, so it is ignored.
  //   slot.addPendingRequest(util.initParticleSpec('particle1'), handler, {});
  //   slot.addPendingRequest(util.initParticleSpec('particle2'), handler, {});
  //   slot.providePendingSlot();
  //   let expectedCount = 0;
  //   assert.equal(++expectedCount, count);
  //   slot.providePendingSlot();
  //   assert.equal(++expectedCount, count);
  //   // Slot has no pending requests, providing it does nothing.
  //   slot.providePendingSlot();
  //   assert.equal(expectedCount, count);
  //
  //   // Cannot provide not associated slot.
  //   slot.associateWithParticle(util.initParticleSpec('particle'));
  //   assert.throws(() => { slot.providePendingSlot(); });
  //   assert.equal(expectedCount, count);
  // });
  // it('remove pending request', function() {
  //   let slot = new Slot('slotid');
  //   let count = 0;
  //   let reject = () => { count++; };
  //   slot.addPendingRequest(util.initParticleSpec('particle1'), {}, reject);
  //   slot.removePendingRequest(util.initParticleSpec('particle1'));
  //   assert.equal(1, count);
  // });
});
<commit_msg>runtime/slot.js test<commit_after>/**
 * @license
 * Copyright (c) 2017 Google Inc. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * Code distributed by Google as part of this project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
"use strict";

const assert = require('chai').assert;
var Slot = require("../slot.js");

describe('slot', function() {
  it('setting context', function() {
    let slot = new Slot("dummy-consumeConn", "dummy-arc");
    let startRenderCount = 0;
    let stopRenderCount = 0;
    slot.startRenderCallback = () => { ++startRenderCount; };
    slot.stopRenderCallback = () => { ++stopRenderCount; };

    // context was null, set to null: nothing happens.
    slot.setContext(null);
    assert.equal(startRenderCount, 0);
    assert.equal(stopRenderCount, 0);

    // context was null, set to non-null: startRender is called.
    slot.setContext("dummy-context");
    assert.equal(startRenderCount, 1);
    assert.equal(stopRenderCount, 0);

    // context was not null, set to another non-null context: nothing happens.
    assert.isFalse(slot.isSameContext("other-context"));
    slot.setContext("other-context");
    assert.equal(startRenderCount, 1);
    assert.equal(stopRenderCount, 0);

    // context was not null, set to null: stopRender is called.
    slot.setContext(null);
    assert.equal(startRenderCount, 1);
    assert.equal(stopRenderCount, 1);
  });
});
<|endoftext|>


<commit_before>"use strict";
module.exports = function(app)
{
	var mongoose = app.openbiz.mongoose;
    var schema = new mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,
        name: String,
        address:{
            country: String,
            province: String,
            city: String,
            street: String,
            zipcode: String
        },
        phone:{
            countryCode: String,
            areaCode:   Number,
            number:     Number
        },
        administrators:[{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'cubi.user.User'
        }],
        users:[{
        	type: mongoose.Schema.Types.ObjectId,
            ref: 'cubi.user.User'
        }],
        creator:{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'cubi.user.User'
        },
        contacts:[{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'cubi.contact.Contact'
        }]
    },{
        versionKey: false,
        collection: 'cubi-account'
    });
    return mongoose.model('cubi.account.Account', schema);
}<commit_msg>update ui and app<commit_after>"use strict";
module.exports = function(app)
{
	var mongoose = app.openbiz.mongoose;
    var schema = new mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,
        name: String,
        info:{
            address:{
                country: String,
                province: String,
                city: String,
                street: String,
                zipcode: String
            },
            phone:{
                countryCode: String,
                areaCode:   Number,
                number:     Number
            }
        },
        users:[{
        	userId:{
                type: mongoose.Schema.Types.ObjectId,
                ref: 'cubi.user.User'
            },
            role:{
                type: String,
                enum: ['administrator','member'],
                default: 'member'
            }
        }],
        contacts:[{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'cubi.contact.Contact'
        }],
        creator:{
            id:{
                type: mongoose.Schema.Types.ObjectId,
                ref: 'cubi.user.User'
            },
            timestamp: {
                type: Date,
                default: Date.now
            }
        }
    },{
        versionKey: false,
        collection: 'cubi_account'
    });
    return mongoose.model('cubi.account.Account', schema);
}<|endoftext|>


<commit_before>GS.ElevatorStates = {
	Down: 0,
	Up: 1,
	GoindDown: 2,
	GoingUp: 3,
};

GS.Elevator = function(grid, sector) {
	GS.GridObject.call(this, grid);

	this.sector = sector;
	this.speed = 0.25;
	this.state = GS.ElevatorStates.Down;
	this.automatic = true;
	this.lightColor = new THREE.Color();

	this.view = {
		collisionData: {
			boundingBox: new THREE.Box3(),
			triangles: null,
			segments: null,
		},
	};

	this.maxCooldown = GS.msToFrames(0);
	this.cooldown = this.maxCooldown;

	this.velocity = new THREE.Vector3();
};

GS.Elevator.prototype = GS.inherit(GS.GridObject, {
	constructor: GS.Elevator,

	init: function() {
		this.downY = this.position.y;
		this.upY = this.downY + this.sector.elevatorMaxHeight;

		this.updateBoundingBox();
	},

	update: function() {
		this.velocity.set(0, 0, 0);
		var oldY = 0;

		switch (this.state) {
			case GS.ElevatorStates.Down:
				if (this.automatic) {
					this.cooldown--;
					if (this.cooldown <= 0) {
						this.cooldown = this.maxCooldown;
						this.state = GS.ElevatorStates.GoingUp;
					}
				}
				break;

			case GS.ElevatorStates.Up:
				if (this.automatic) {
					this.cooldown--;
					if (this.cooldown <= 0) {
						this.cooldown = this.maxCooldown;
						this.state = GS.ElevatorStates.GoingDown;
					}
				}
				break;

			case GS.ElevatorStates.GoingDown:
				oldY = this.position.y;
				this.position.y -= this.speed;
				if (this.position.y <= this.downY) {
					this.position.y = this.downY;
					this.velocity.y = this.downY - oldY;
					this.state = GS.ElevatorStates.Down;
				} else {
					this.velocity.y = -this.speed;
				}
				break;

			case GS.ElevatorStates.GoingUp:
				oldY = this.position.y;
				this.position.y += this.speed;
				if (this.position.y >= this.upY) {
					this.position.y = this.upY;
					this.velocity.y = this.upY - oldY;
					this.state = GS.ElevatorStates.Up;
				} else {
					this.velocity.y = this.speed;
				}
				break;
		}

		this.updateChange();
	},

	updateChange: function() {
		if (this.velocity.y !== 0) {
			this.updateBoundingBox();
			this.updateTriangles(this.velocity);
			this.updateSegments(this.velocity.y);
			this.updateSector(this.velocity.y);
			this.updateMesh();

			this.grid.collisionManager.elevatorMove(this, this.velocity.y);
		}

		this.getLightColorFromSector(this.lightColor, this.sector);
		for (var i = 0; i < this.view.mesh.children.length; i++) {
			var material = this.view.mesh.children[i].material;
			if (material.emissive !== undefined) {
				material.emissive.copy(this.lightColor);
			}
		}
	},

	updateSector: function(yVelocity) {
		this.sector.floorTopY += yVelocity;
		this.sector.ceilBottomY += yVelocity;
	},

	setPositionUp: function() {
		this.velocity.y = this.upY - this.position.y;
		this.position.y = this.upY;
		this.state = GS.ElevatorStates.Up;

		this.updateChange();

		return this;
	},

	setPositionDown: function() {
		this.velocity.y = this.downY - this.position.y;
		this.position.y = this.downY;
		this.state = GS.ElevatorStates.Down;

		this.updateChange();

		return this;
	},

	goDown: function() {
		this.state = GS.ElevatorStates.GoingDown;

		return this;
	},

	goUp: function() {
		this.state = GS.ElevatorStates.GoingUp;

		return this;
	},

	updateMesh: function() {
		for (var i = 0; i < this.view.mesh.children.length; i++) {
			this.view.mesh.children[i].position.copy(this.position);
		}
	},

	onUse: function() {
		if (this.state == GS.ElevatorStates.Closed) {
			this.state = GS.ElevatorStates.Opening;
		}
	},
});<commit_msg>reuse door sounds for elevator movement<commit_after>GS.ElevatorStates = {
	Down: 0,
	Up: 1,
	GoindDown: 2,
	GoingUp: 3,
};

GS.Elevator = function(grid, sector) {
	GS.GridObject.call(this, grid);

	this.sector = sector;
	this.speed = 0.25;
	this.state = GS.ElevatorStates.Down;
	this.automatic = true;
	this.lightColor = new THREE.Color();

	this.view = {
		collisionData: {
			boundingBox: new THREE.Box3(),
			triangles: null,
			segments: null,
		},
	};

	this.maxCooldown = GS.msToFrames(0);
	this.cooldown = this.maxCooldown;

	this.velocity = new THREE.Vector3();
};

GS.Elevator.prototype = GS.inherit(GS.GridObject, {
	constructor: GS.Elevator,

	init: function() {
		this.downY = this.position.y;
		this.upY = this.downY + this.sector.elevatorMaxHeight;

		this.updateBoundingBox();
	},

	update: function() {
		this.velocity.set(0, 0, 0);
		var oldY = 0;

		switch (this.state) {
			case GS.ElevatorStates.Down:
				if (this.automatic) {
					this.cooldown--;
					if (this.cooldown <= 0) {
						this.cooldown = this.maxCooldown;
						this.state = GS.ElevatorStates.GoingUp;
					}
				}
				break;

			case GS.ElevatorStates.Up:
				if (this.automatic) {
					this.cooldown--;
					if (this.cooldown <= 0) {
						this.cooldown = this.maxCooldown;
						this.state = GS.ElevatorStates.GoingDown;
					}
				}
				break;

			case GS.ElevatorStates.GoingDown:
				oldY = this.position.y;
				this.position.y -= this.speed;
				if (this.position.y <= this.downY) {
					this.position.y = this.downY;
					this.velocity.y = this.downY - oldY;
					this.state = GS.ElevatorStates.Down;
					this.grid.soundManager.playSound("door_close");
				} else {
					this.velocity.y = -this.speed;
				}
				break;

			case GS.ElevatorStates.GoingUp:
				oldY = this.position.y;
				this.position.y += this.speed;
				if (this.position.y >= this.upY) {
					this.position.y = this.upY;
					this.velocity.y = this.upY - oldY;
					this.state = GS.ElevatorStates.Up;
					this.grid.soundManager.playSound("door_close");
				} else {
					this.velocity.y = this.speed;
				}
				break;
		}

		this.updateChange();
	},

	updateChange: function() {
		if (this.velocity.y !== 0) {
			this.updateBoundingBox();
			this.updateTriangles(this.velocity);
			this.updateSegments(this.velocity.y);
			this.updateSector(this.velocity.y);
			this.updateMesh();

			this.grid.collisionManager.elevatorMove(this, this.velocity.y);
		}

		this.getLightColorFromSector(this.lightColor, this.sector);
		for (var i = 0; i < this.view.mesh.children.length; i++) {
			var material = this.view.mesh.children[i].material;
			if (material.emissive !== undefined) {
				material.emissive.copy(this.lightColor);
			}
		}
	},

	updateSector: function(yVelocity) {
		this.sector.floorTopY += yVelocity;
		this.sector.ceilBottomY += yVelocity;
	},

	setPositionUp: function() {
		this.velocity.y = this.upY - this.position.y;
		this.position.y = this.upY;
		this.state = GS.ElevatorStates.Up;

		this.updateChange();

		return this;
	},

	setPositionDown: function() {
		this.velocity.y = this.downY - this.position.y;
		this.position.y = this.downY;
		this.state = GS.ElevatorStates.Down;

		this.updateChange();

		return this;
	},

	goDown: function() {
		this.state = GS.ElevatorStates.GoingDown;
		this.grid.soundManager.playSound("door_open");

		return this;
	},

	goUp: function() {
		this.state = GS.ElevatorStates.GoingUp;
		this.grid.soundManager.playSound("door_open");

		return this;
	},

	updateMesh: function() {
		for (var i = 0; i < this.view.mesh.children.length; i++) {
			this.view.mesh.children[i].position.copy(this.position);
		}
	},

	onUse: function() {
		if (this.state == GS.ElevatorStates.Closed) {
			this.state = GS.ElevatorStates.Opening;
		}
	},
});<|endoftext|>


<commit_before>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2015 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* The Health component provides the ability for Game Objects to have a `health` property
* that can be damaged and reset through game code.
* Requires the LifeSpan component.
*
* @class
*/
Phaser.Component.Health = function () {};

Phaser.Component.Health.prototype = {

    /**
    * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object.
    *
    * It can be used in combination with the `damage` method or modified directly.
    * @property {number} health
    * @default
    */
    health: 1,

    /**
    * Damages the Game Object. This removes the given amount of health from the `health` property.
    *
    * If health is taken below or is equal to zero then the `kill` method is called.
    *
    * @member
    * @param {number} amount - The amount to subtract from the current `health` value.
    * @return {Phaser.Sprite} This instance.
    */
    damage: function(amount) {

        if (this.alive)
        {
            this.health -= amount;

            if (this.health <= 0)
            {
                this.kill();
            }
        }

        return this;

    }

};
<commit_msg>Adds Heal Method to Phaser.Components.Health<commit_after>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2015 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* The Health component provides the ability for Game Objects to have a `health` property
* that can be damaged and reset through game code.
* Requires the LifeSpan component.
*
* @class
*/
Phaser.Component.Health = function () {};

Phaser.Component.Health.prototype = {

    /**
    * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object.
    *
    * It can be used in combination with the `damage` method or modified directly.
    * @property {number} health
    * @default
    */
    health: 1,

    /**
    * Damages the Game Object. This removes the given amount of health from the `health` property.
    *
    * If health is taken below or is equal to zero then the `kill` method is called.
    *
    * @member
    * @param {number} amount - The amount to subtract from the current `health` value.
    * @return {Phaser.Sprite} This instance.
    */
    damage: function(amount) {

        if (this.alive)
        {
            this.health -= amount;

            if (this.health <= 0)
            {
                this.kill();
            }
        }

        return this;

    }

    /**
    * Heal the Game Object. This adds the given amount of health from the `health` property.
    *
    * @member
    * @param {number} amount - The amount to add from the current `health` value.
    * @return {Phaser.Sprite} This instance.
    */
    heal: function(amount) {

        if (this.alive)
        {
            this.health += amount;
        }

        return this;

    }

};
<|endoftext|>


<commit_before>var Model = require('cdb/core/model');
var WidgetView = require('../../widget');
var WidgetHistogramContent = require('./content-view.js');

/**
 * Histogram widget view
 */
module.exports = WidgetView.extend({

  _createContentView: function() {
    return new WidgetHistogramContent({
      dataModel: this.model,
      viewModel: new Model(),
      filter: this.filter
    });
  }

});
<commit_msg>Remove unnecessary file ext<commit_after>var Model = require('cdb/core/model');
var WidgetView = require('../../widget');
var WidgetHistogramContent = require('./content-view');

/**
 * Histogram widget view
 */
module.exports = WidgetView.extend({

  _createContentView: function() {
    return new WidgetHistogramContent({
      dataModel: this.model,
      viewModel: new Model(),
      filter: this.filter
    });
  }

});
<|endoftext|>