<commit_before>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

document.addEventListener('deviceready', function () {
    Firebase.goOnline();
});

$('#not-available').on('click', function() {
	alert('Faskes is not available.')
})

function getNoAntri(tipe, username, name) {
  breanna = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username),
  antri = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/antrian');
  pasien = breanna.child("pasien");

  alert('Pastikan koneksi anda stabil'); // Make sure the connection is OK

  get = 'Getting data..';
  console.log(get);

  var nama = prompt("Nama: "),
      nik = prompt("NIK: ");

  if (nama === '' || nik.length != 16) {
    alert('Input tidak valid');
  } else {
    antri.transaction(function(currentRank) {
        currentData = currentRank + 1;

        return currentData;
    }, function(error, committed, snapshot) {
        nomor = Number(snapshot.val());
        if (error) {
            alert('Koneksi anda tidak stabil' + error);
        } else {
            alert('Nomor Antrian: ' + snapshot.val());
            nomor.push().set({
              nama: nama,
              nik: nik,
              no_antri: snapshot.val()
            })
        }
    });
  }

  console.log('Data is ready');
}

function tempatTidur(tipe, username) {
  brea = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/tempat_tidur');

  wait = 'Getting data..';
  console.log(wait);
  alert(wait);

  brea.on('value', function(snapshot) {
    satu = snapshot.val().satu;
    dua = snapshot.val().dua;
    tiga = snapshot.val().tiga;

    alert('Kelas I: ' + satu + '\n' + 'Kelas II: ' + dua + '\n' + 'Kelas III: ' + tiga); // Show user the data's
  })
}

function doctorProfile(nama, lulusan, tahun) {
  giant = 'Lulusan: ' + lulusan + '\n' + 'Tahun: ' + tahun;
  name = 'dr. ' + nama;

  alert(name + '\n' + giant); // Pop-up
}
<commit_msg>Won't answer if not online<commit_after>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

document.addEventListener('deviceready', function () {
    Firebase.goOnline();
});

$('#not-available').on('click', function() {
	alert('Faskes is not available.')
})

function getNoAntri(tipe, username, name) {
  breanna = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username),
  antri = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/antrian');
  pasien = breanna.child("pasien");

  if (navigator.online) {
    alert('Anda tidak online');
  } else {
    get = 'Getting data..';
    console.log(get);

    var nama = prompt("Nama: "),
        nik = prompt("NIK: ");

    if (nama === '' || nik.length != 16) {
      alert('Input tidak valid');
    } else {
      antri.transaction(function(currentRank) {
          currentData = currentRank + 1;

          return currentData;
      }, function(error, committed, snapshot) {
          nomor = Number(snapshot.val());
          if (error) {
              alert('Koneksi anda tidak stabil' + error);
          } else {
              alert('Nomor Antrian: ' + snapshot.val());
              nomor.push().set({
                nama: nama,
                nik: nik,
                no_antri: snapshot.val()
              })
          }
      });
    }
    console.log('Data is ready');
  }
}

function tempatTidur(tipe, username) {
  brea = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/tempat_tidur');

  wait = 'Getting data..';
  console.log(wait);
  alert(wait);

  brea.on('value', function(snapshot) {
    satu = snapshot.val().satu;
    dua = snapshot.val().dua;
    tiga = snapshot.val().tiga;

    alert('Kelas I: ' + satu + '\n' + 'Kelas II: ' + dua + '\n' + 'Kelas III: ' + tiga); // Show user the data's
  })
}

function doctorProfile(nama, lulusan, tahun) {
  giant = 'Lulusan: ' + lulusan + '\n' + 'Tahun: ' + tahun;
  name = 'dr. ' + nama;

  alert(name + '\n' + giant); // Pop-up
}
<|endoftext|>


<commit_before>'use strict';

var create = Object.create, getPrototypeOf = Object.getPrototypeOf
  , x = {};

module.exports = function (/*customCreate*/) {
	var setPrototypeOf = Object.setPrototypeOf
	  , customCreate = arguments[0] || create;
	if (typeof setPrototype !== 'function') return false;
	return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x;
};
<commit_msg>Fix isImplemented for setPrototypeOf<commit_after>'use strict';

var create = Object.create, getPrototypeOf = Object.getPrototypeOf
  , x = {};

module.exports = function (/*customCreate*/) {
	var setPrototypeOf = Object.setPrototypeOf
	  , customCreate = arguments[0] || create;
	if (typeof setPrototypeOf !== 'function') return false;
	return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x;
};
<|endoftext|>


<commit_before>var PLEDGE_URL = "https://pledge.lessig2016.us";
var RECEIPT_URL = "/thank-you";

function step2(amount){
  $(".step-1-container").hide("slow");
  $("#step-1").removeClass("active");
  $("#step-2").addClass("active");
  //$("#pledgeBox").animate({height: "auto"}, 500);
  if( amount > 0 ) {
    $("#amount_input").val(amount);
    $("#amount_input").parent().hide();
  }
  $(".step-2-container").show("slow");
}

function step3(){
  $("#step-2").removeClass("active");
  $("#step-3").addClass("active");
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function get_browser_info(){
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
        return {name:'IE',version:(tem[1]||'')};
        }
    if(M[1]==='Chrome'){
        tem=ua.match(/\bOPR\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
    return {
      name: M[0],
      version: M[1]
    };
}

var ALREADY_BANKED = 1000000;
var GOAL_DOLLARS = 5000000;

    $(function() {
      var date = new Date();
      date.setTime(date.getTime()+(24*60*60*1000));
      document.cookie = ("last_team_key={{team.key()}};" +
                         "expires=" + date.toGMTString() +
                         ";domain=.lessig2016.us;path=/");
      var browserInfo = get_browser_info()
      if (browserInfo.name == 'Firefox') {
        console.log("detected FF version: " + browserInfo.version);
        if (browserInfo.version < 17) {
          $('#pledgeBox .info').after('
Sorry, we are not supporting older Firefox versions at the moment. Please try another browser for now.
');
        } else {
          console.log('Firefox version was OK: ' + browserInfo.version);
        }
      }
    });
<commit_msg>testing deployment<commit_after>var PLEDGE_URL = "https://pledge.lessig2016.us"; //changed for new domain
var RECEIPT_URL = "/thank-you";

function step2(amount){
  $(".step-1-container").hide("slow");
  $("#step-1").removeClass("active");
  $("#step-2").addClass("active");
  //$("#pledgeBox").animate({height: "auto"}, 500);
  if( amount > 0 ) {
    $("#amount_input").val(amount);
    $("#amount_input").parent().hide();
  }
  $(".step-2-container").show("slow");
}

function step3(){
  $("#step-2").removeClass("active");
  $("#step-3").addClass("active");
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function get_browser_info(){
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
        return {name:'IE',version:(tem[1]||'')};
        }
    if(M[1]==='Chrome'){
        tem=ua.match(/\bOPR\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
    return {
      name: M[0],
      version: M[1]
    };
}

var ALREADY_BANKED = 1000000;
var GOAL_DOLLARS = 5000000;

    $(function() {
      var date = new Date();
      date.setTime(date.getTime()+(24*60*60*1000));
      document.cookie = ("last_team_key={{team.key()}};" +
                         "expires=" + date.toGMTString() +
                         ";domain=.lessig2016.us;path=/");
      var browserInfo = get_browser_info()
      if (browserInfo.name == 'Firefox') {
        console.log("detected FF version: " + browserInfo.version);
        if (browserInfo.version < 17) {
          $('#pledgeBox .info').after('
Sorry, we are not supporting older Firefox versions at the moment. Please try another browser for now.
');
        } else {
          console.log('Firefox version was OK: ' + browserInfo.version);
        }
      }
    });
<|endoftext|>


<commit_before>//global services go here
angular.module('omniwallet').factory('userService', ['$rootScope', '$http',
function($rootScope, $http) {
  var service = {
    data : {
      walletKey : '',
      asymKey : {},
      wallet : {},
      loggedIn : false
    },

    login : function(wallet, walletKey, asymKey) {
      service.data.walletKey = walletKey;
      service.data.asymKey = asymKey;
      service.data.wallet = wallet;
      service.data.loggedIn = true;
    },

    logout : function() {
      service.data.loggedIn = false;
      service.data.wallet = {}
    },

    addAddress : function(address, privKey) {
      for (var i in service.data.wallet.addresses ) {
        if (service.data.wallet.addresses[i].address == address) {
          service.data.wallet.addresses[i].privkey = privKey;
          service.saveSession();
          return;
        }
      };
      // update currencies
      $http.post('/v1/address/addr/', {
        'addr' : address
      }).success(function(result) {
        var currencies = [];
        result.balance.map(function(e, i, a) {
          currencies.push(e.symbol);
        });
        service.data.wallet.addresses.push({
          "address" : address,
          "privkey" : privKey,
          "currencies" : currencies
        });
        service.data.loggedIn = true;
        service.saveSession();
      }).error(function(error) {
        service.data.wallet.addresses.push({
          "address" : address,
          "privkey" : privKey,
          "currencies" : []
        });
      });
    },

    getAddress : function(address) {
      for (var i in service.data.wallet.addresses) {
        if (service.data.wallet.addresses[i].address == address) {
          return service.data.wallet.addresses[i];
        }
      }
    },

    getAllAddresses : function() {
      return service.data.wallet.addresses;
    },

    getCurrencies : function() {
      currencies = []
      service.data.wallet.addresses.forEach( function( address ) {
        for( var c=0; c < address.currencies.length; c++ ){
          if(currencies.indexOf( address.currencies[c] ) == -1) {
            currencies.push(address.currencies[c]);
          }
        }
      });
      return currencies;
    },

    getWallet : function() {
      return service.data.wallet;
    },

    getUUID : function() {
      return service.data.wallet.uuid;
    },

    removeAddress : function(address) {
      for (var i = 0; i < service.data.wallet.addresses.length; i++)
        if (service.data.wallet.addresses[i].address == address) {
          service.data.wallet.addresses.splice(i, 1);
          service.saveSession();
          return;
        }
    },

    updateWallet : function() {
      var uuid = service.getUUID();
      return $http.get('/v1/user/wallet/challenge?uuid=' + uuid).then(function(result) {
        var data = result.data;
        var encryptedWallet = CryptUtil.encryptObject(service.data.wallet, service.data.walletKey);
        var challenge = data.challenge;
        var signature = ""

        return $http({
          url : '/v1/user/wallet/update',
          method : 'POST',
          data : {
            uuid : uuid,
            wallet : encryptedWallet,
            challenge : challenge,
            signature : signature
          }
        });
      });
    },

    saveSession : function() {
      service.updateWallet().then(function() {
        console.log("Success saving")
      });
    }
  };

  return service;
}]);

angular.module('omniwallet').factory('appraiser', ['$rootScope', '$http','$q', '$injector',
function($rootScope, $http,$q, $injector) {

  function AppraiserService() {
    this.conversions = {};
    this.userService = $injector.get( 'userService' );
    var self = this;
    function UpdateLoop() {
      self.updateValues(function() {
        setTimeout(UpdateLoop, 30000);
      });
    }

    UpdateLoop();
  };
  AppraiserService.prototype.updateValues = function(callback) {
    var self = this;
    var requests =[];
    var coins = this.userService.getCurrencies();
    coins.forEach(function(symbol){
      requests.push(
        $http.get('/v1/values/'+symbol+'.json').then(function(response) {
          var currency = response.data[0];
          if (currency.symbol == 'BTC') {
            // Store these things internally as the value of a satoshi.
            self.conversions.BTC = currency.price / 100000000;
            $rootScope.$emit('APPRAISER_VALUE_CHANGED', 'BTC');
          } else {
            self.conversions[currency.symbol] = currency.price;
            $rootScope.$emit('APPRAISER_VALUE_CHANGED', currency.symbol);
          }
        }, function(error) {
          console.log(error);
        })
      );
    });
    $q.all( requests ).then(function(responses){
      callback();
    });
  };
  AppraiserService.prototype.getValue = function(amount, symbol) {
    if (symbol == 'BTC') {
      if (this.conversions.BTC)
        return this.conversions.BTC * amount;
      else
        return 'BTC Value Unavailable';
    } else {
      if (this.conversions.hasOwnProperty(symbol)) {
        return this.getValue(this.conversions[symbol] * amount, 'BTC');
      } else
        return symbol + ' Value Unavailable';
    }
  };

  return new AppraiserService();
}]);

angular.module( 'omniwallet' ).factory( 'hashExplorer', function ( ) {
  var tx = '', loc = '', setHash = function(){};
  return {
    tx : tx,
    loc: loc,
    setHash: function(tx) {
      this.tx = JSON.stringify(tx);
      this.loc = window.location.href.split('/').slice(-2).join('/');
    }
  }
});
<commit_msg>Add signing to user service in client<commit_after>//global services go here
angular.module('omniwallet').factory('userService', ['$rootScope', '$http',
function($rootScope, $http) {
  var service = {
    data : {
      walletKey : '',
      asymKey : {},
      wallet : {},
      loggedIn : false
    },

    login : function(wallet, walletKey, asymKey) {
      service.data.walletKey = walletKey;
      service.data.asymKey = asymKey;
      service.data.wallet = wallet;
      service.data.loggedIn = true;
    },

    logout : function() {
      service.data.loggedIn = false;
      service.data.wallet = {}
    },

    addAddress : function(address, privKey) {
      for (var i in service.data.wallet.addresses ) {
        if (service.data.wallet.addresses[i].address == address) {
          service.data.wallet.addresses[i].privkey = privKey;
          service.saveSession();
          return;
        }
      };
      // update currencies
      $http.post('/v1/address/addr/', {
        'addr' : address
      }).success(function(result) {
        var currencies = [];
        result.balance.map(function(e, i, a) {
          currencies.push(e.symbol);
        });
        service.data.wallet.addresses.push({
          "address" : address,
          "privkey" : privKey,
          "currencies" : currencies
        });
        service.data.loggedIn = true;
        service.saveSession();
      }).error(function(error) {
        service.data.wallet.addresses.push({
          "address" : address,
          "privkey" : privKey,
          "currencies" : []
        });
      });
    },

    getAddress : function(address) {
      for (var i in service.data.wallet.addresses) {
        if (service.data.wallet.addresses[i].address == address) {
          return service.data.wallet.addresses[i];
        }
      }
    },

    getAllAddresses : function() {
      return service.data.wallet.addresses;
    },

    getCurrencies : function() {
      currencies = []
      service.data.wallet.addresses.forEach( function( address ) {
        for( var c=0; c < address.currencies.length; c++ ){
          if(currencies.indexOf( address.currencies[c] ) == -1) {
            currencies.push(address.currencies[c]);
          }
        }
      });
      return currencies;
    },

    getWallet : function() {
      return service.data.wallet;
    },

    getUUID : function() {
      return service.data.wallet.uuid;
    },

    getAsymKey: function() {
      return service.data.asymKey;
    },

    removeAddress: function( address ) {
      for( var i=0; i<service.data.wallet.addresses.length; i++ )
        if( service.data.wallet.addresses[i].address == address )
        {
          service.data.wallet.addresses.splice( i, 1 );
          service.saveSession();
          return;
        }
    },

    updateWallet : function() {
      var uuid = service.getUUID();
      return $http.get('/v1/user/wallet/challenge?uuid='+uuid)
        .then(function(result) {
          var data = result.data;
          var encryptedWallet = CryptUtil.encryptObject(service.data.wallet, service.data.walletKey);
          var challenge = data.challenge;
          var signature = CryptUtil.createSignedObject(challenge, service.getAsymKey().privKey);

          return $http({
            url: '/v1/user/wallet/update',
            method: 'POST',
            data: { uuid: uuid, wallet: encryptedWallet, signature: signature }
          });
        })
    },

    saveSession : function() {
      service.updateWallet().then(function() {
        console.log("Success saving")
      });
    }
  };

  return service;
}]);

angular.module('omniwallet').factory('appraiser', ['$rootScope', '$http','$q', '$injector',
function($rootScope, $http,$q, $injector) {

  function AppraiserService() {
    this.conversions = {};
    this.userService = $injector.get( 'userService' );
    var self = this;
    function UpdateLoop() {
      self.updateValues(function() {
        setTimeout(UpdateLoop, 30000);
      });
    }

    UpdateLoop();
  };
  AppraiserService.prototype.updateValues = function(callback) {
    var self = this;
    var requests =[];
    var coins = this.userService.getCurrencies();
    coins.forEach(function(symbol){
      requests.push(
        $http.get('/v1/values/'+symbol+'.json').then(function(response) {
          var currency = response.data[0];
          if (currency.symbol == 'BTC') {
            // Store these things internally as the value of a satoshi.
            self.conversions.BTC = currency.price / 100000000;
            $rootScope.$emit('APPRAISER_VALUE_CHANGED', 'BTC');
          } else {
            self.conversions[currency.symbol] = currency.price;
            $rootScope.$emit('APPRAISER_VALUE_CHANGED', currency.symbol);
          }
        }, function(error) {
          console.log(error);
        })
      );
    });
    $q.all( requests ).then(function(responses){
      callback();
    });
  };
  AppraiserService.prototype.getValue = function(amount, symbol) {
    if (symbol == 'BTC') {
      if (this.conversions.BTC)
        return this.conversions.BTC * amount;
      else
        return 'BTC Value Unavailable';
    } else {
      if (this.conversions.hasOwnProperty(symbol)) {
        return this.getValue(this.conversions[symbol] * amount, 'BTC');
      } else
        return symbol + ' Value Unavailable';
    }
  };

  return new AppraiserService();
}]);

angular.module( 'omniwallet' ).factory( 'hashExplorer', function ( ) {
  var tx = '', loc = '', setHash = function(){};
  return {
    tx : tx,
    loc: loc,
    setHash: function(tx) {
      this.tx = JSON.stringify(tx);
      this.loc = window.location.href.split('/').slice(-2).join('/');
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

const { pSetTimeout } = require('../../../utilities');

const { processResponse } = require('./process_response');
const commands = require('./commands');

const fireCommand = async function (commandInput) {
  const { command, opts } = commandInput;
  const { data, metadata } = commands[command](commandInput);

  // Simulate asynchronousity
  // TODO: remove when there is a real ORM
  await pSetTimeout(0);

  const dataA = processResponse({ data, opts });

  return { response: { data: dataA, metadata } };
};

module.exports = {
  fireCommand,
};
<commit_msg>Better database simulation<commit_after>'use strict';

const { pSetTimeout } = require('../../../utilities');

const { processResponse } = require('./process_response');
const commands = require('./commands');

const fireCommand = async function (commandInput) {
  // Simulate asynchronousity
  // TODO: remove when there is a real ORM
  await pSetTimeout(0);

  const { command, opts } = commandInput;
  const { data, metadata } = commands[command](commandInput);

  const dataA = processResponse({ data, opts });

  return { response: { data: dataA, metadata } };
};

module.exports = {
  fireCommand,
};
<|endoftext|>


<commit_before>(function ($) {
  $(document).ready(function() {

    var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;

    // Main
    initHeader();
    initAnimation();
    addListeners();

    function initHeader() {
        width = window.innerWidth;
        height = window.innerHeight;
        target = {x: width/2, y: height/2};

        largeHeader = document.getElementById('large-header');
        largeHeader.style.height = height+'px';

        canvas = document.getElementById('demo-canvas');
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');

        // create points
        points = [];
        for(var x = 0; x < width; x = x + width/20) {
            for(var y = 0; y < height; y = y + height/20) {
                var px = x + Math.random()*width/20;
                var py = y + Math.random()*height/20;
                var p = {x: px, originX: px, y: py, originY: py };
                points.push(p);
            }
        }

        // for each point find the 5 closest points
        for(var i = 0; i < points.length; i++) {
            var closest = [];
            var p1 = points[i];
            for(var j = 0; j < points.length; j++) {
                var p2 = points[j]
                if(!(p1 == p2)) {
                    var placed = false;
                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(closest[k] == undefined) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }

                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(getDistance(p1, p2) < getDistance(p1, closest[k])) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }
                }
            }
            p1.closest = closest;
        }

        // assign a circle to each point
        for(var i in points) {
            var c = new Circle(points[i], 2+Math.random()*2, 'rgba(255,255,255,0.3)');
            points[i].circle = c;
        }
    }

    // Event handling
    function addListeners() {
        if(!('ontouchstart' in window)) {
            window.addEventListener('mousemove', mouseMove);
        }
        window.addEventListener('scroll', scrollCheck);
        window.addEventListener('resize', resize);
    }

    function mouseMove(e) {
        var posx = posy = 0;
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)    {
            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        target.x = posx;
        target.y = posy;
    }

    function scrollCheck() {
        if(document.body.scrollTop > height) animateHeader = false;
        else animateHeader = true;
    }

    function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        largeHeader.style.height = height+'px';
        canvas.width = width;
        canvas.height = height;
    }

    // animation
    function initAnimation() {
        animate();
        for(var i in points) {
            shiftPoint(points[i]);
        }
    }

    function animate() {
        if(animateHeader) {
            ctx.clearRect(0,0,width,height);
            for(var i in points) {
                // detect points in range
                if(Math.abs(getDistance(target, points[i])) < 4000) {
                    points[i].active = 0.3;
                    points[i].circle.active = 0.6;
                } else if(Math.abs(getDistance(target, points[i])) < 20000) {
                    points[i].active = 0.1;
                    points[i].circle.active = 0.3;
                } else if(Math.abs(getDistance(target, points[i])) < 40000) {
                    points[i].active = 0.02;
                    points[i].circle.active = 0.1;
                } else {
                    points[i].active = 0;
                    points[i].circle.active = 0;
                }

                drawLines(points[i]);
                points[i].circle.draw();
            }
        }
        requestAnimationFrame(animate);
    }

    function shiftPoint(p) {
        TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
            y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
            onComplete: function() {
                shiftPoint(p);
            }});
    }

    // Canvas manipulation
    function drawLines(p) {
        if(!p.active) return;
        for(var i in p.closest) {
            ctx.beginPath();
            ctx.moveTo(p.x, p.y);
            ctx.lineTo(p.closest[i].x, p.closest[i].y);
            ctx.strokeStyle = 'rgba(156,217,249,'+ p.active+')';
            ctx.stroke();
        }
    }

    function Circle(pos,rad,color) {
        var _this = this;

        // constructor
        (function() {
            _this.pos = pos || null;
            _this.radius = rad || null;
            _this.color = color || null;
        })();

        this.draw = function() {
            if(!_this.active) return;
            ctx.beginPath();
            ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
            ctx.fillStyle = 'rgba(156,217,249,'+ _this.active+')';
            ctx.fill();
        };
    }

    // Util
    function getDistance(p1, p2) {
        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
    }

    function addLink() {
    //Get the selected text and append the extra info
    var selection = window.getSelection(),
        pagelink = '

 This content is part of Article on:  ' + document.location.href,
        copytext = selection + pagelink,
        newdiv = document.createElement('div');

    //hide the newly created container
    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';

    //insert the container, fill it with the extended text, and define the new selection
    document.body.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);

    window.setTimeout(function () {
        document.body.removeChild(newdiv);
      }, 100);
    }

    document.addEventListener('copy', addLink);

    //Smooth scroll

    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1500);
          return false;
        }
      }
    });

  });

})(jQuery);
<commit_msg>Update driver.js<commit_after>
<|endoftext|>


<commit_before>'use strict';

const buildRequestKeyHash = (authorizeRequestId, applicationId, keyCode) => {
	const sha256 = crypto.createHash('sha256');
	sha256.update(`${config.api.secret_token.authorize_request}/${applicationId}/${authorizeRequestId}/${keyCode}`);

	return sha256.digest('hex');
};
exports.buildRequestKeyHash = buildRequestKeyHash;

exports.buildRequestKey = (authorizeRequestId, applicationId, keyCode) => {
	return `${authorizeRequestId}-${buildRequestKeyHash(authorizeRequestId, applicationId, keyCode)}.${keyCode}`;
};

exports.keyToElements = (key) => {
	const reg = /([^-]+)-([^-]{64}).([^-]+)/.exec(key);

	return {authorizeRequestId: reg[1], hash: reg[2], keyCode: reg[3]};
};

exports.verifyRequestKey = (key) => {
	// TODO

	return true;
};
<commit_msg>add require<commit_after>'use strict';

const crypto = require('crypto');
const config = require('./load-config')();

const buildRequestKeyHash = (authorizeRequestId, applicationId, keyCode) => {
	const sha256 = crypto.createHash('sha256');
	sha256.update(`${config.api.secret_token.authorize_request}/${applicationId}/${authorizeRequestId}/${keyCode}`);

	return sha256.digest('hex');
};
exports.buildRequestKeyHash = buildRequestKeyHash;

exports.buildRequestKey = (authorizeRequestId, applicationId, keyCode) => {
	return `${authorizeRequestId}-${buildRequestKeyHash(authorizeRequestId, applicationId, keyCode)}.${keyCode}`;
};

exports.keyToElements = (key) => {
	const reg = /([^-]+)-([^-]{64}).([^-]+)/.exec(key);

	return {authorizeRequestId: reg[1], hash: reg[2], keyCode: reg[3]};
};

exports.verifyRequestKey = (key) => {
	// TODO

	return true;
};
<|endoftext|>


<commit_before>var clicked = false;
var eggCount = 0;
var chosenNums = [];
var easterImgClass = "text-center";
var easterImgStyle = "width: 100%; height: auto;";
var easterImgSrcBase = "../img/easter-eggs/";
var easterImg = "some HTML string -> use setImg()";

function setImg(newSrc) {
    easterImg = "" +
                    "You found an Easter Egg!";
}

// GISD - Sharingan
$("#gisd-image").click(function () {

    if (clicked) return;
    else clicked = true;

    rasengan();
});

function rasengan() {
    console.log("rasengan!");

    var narutoEggs = [
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png"
    ];
    var otherEggs = [
        "../img/easter-eggs/dragonball.png",
        "../img/easter-eggs/fairytail.png",
        "../img/easter-eggs/geass.png",
        "../img/easter-eggs/steins-gate.png",
        "../img/easter-eggs/white-beard.png",
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png"
    ];

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.alt = "Easter Egg " + randNum + " Special";
    img.onclick = rasengan;

    function setEgg(eggs) {

        // find a new picture
        var randNum = Math.floor(Math.random() * eggs.length);
        while ($.inArray(randNum, chosenNums) != -1)
            randNum = Math.floor(Math.random() * eggs.length);
        chosenNums.push(randNum);

        img.src = eggs[randNum];
    }

    function geassEgg() {
        console.log("You were chosen");
    }

    // egg picking
    if (eggCount++ < narutoEggs.length) setEgg(narutoEggs);
    else if (eggCount === 10)           geassEgg();
    else                                setEgg(otherEggs);

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);
}

// Android
$("#android-image").click(function () {
    setImg("android-doughnut.jpg");
    bootbox.alert({
        size: 'large',
        title: 'My kind of doughnut! (me at Google HQ)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// HomeAway
$("#homeaway-image").click(function () {
    setImg("banana.jpg");
    bootbox.alert({
        size: 'large',
        title: "I don't work there at this time of writing so....here's a funny banana I made :p",
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// PayPal
$("#paypal-image").click(function () {
    setImg("paypal-ceo.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Me and Dan Schulman (CEO of PayPal)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// IBM
$("#ibm-image").click(function () {
    setImg("floppy-disk.jpg");
    bootbox.alert({
        size: 'large',
        title: 'The oldest of companies',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Interests
$("#interests-image").click(function () {
    setImg("eyepatch.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Why so serious?',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Details
$("#details-image").click(function () {
    setImg("daisy-straw.jpg");
    bootbox.alert({
        size: 'large',
        title: 'She helped make this site',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});<commit_msg>fixed easter egg alt bug<commit_after>var clicked = false;
var eggCount = 0;
var chosenNums = [];
var easterImgClass = "text-center";
var easterImgStyle = "width: 100%; height: auto;";
var easterImgSrcBase = "../img/easter-eggs/";
var easterImg = "some HTML string -> use setImg()";

function setImg(newSrc) {
    easterImg = "" +
                    "You found an Easter Egg!";
}

// GISD - Sharingan
$("#gisd-image").click(function () {

    if (clicked) return;
    else clicked = true;

    rasengan();
});

function rasengan() {
    console.log("rasengan!");

    var narutoEggs = [
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png"
    ];
    var otherEggs = [
        "../img/easter-eggs/dragonball.png",
        "../img/easter-eggs/fairytail.png",
        "../img/easter-eggs/geass.png",
        "../img/easter-eggs/steins-gate.png",
        "../img/easter-eggs/white-beard.png",
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png"
    ];

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.alt = "Easter Egg Special";
    img.onclick = rasengan;

    function setEgg(eggs) {

        // find a new picture
        var randNum = Math.floor(Math.random() * eggs.length);
        while ($.inArray(randNum, chosenNums) != -1)
            randNum = Math.floor(Math.random() * eggs.length);
        chosenNums.push(randNum);

        img.src = eggs[randNum];
    }

    function geassEgg() {
        console.log("You were chosen");
    }

    // egg picking
    if (eggCount++ < narutoEggs.length) setEgg(narutoEggs);
    else if (eggCount === 10)           geassEgg();
    else                                setEgg(otherEggs);

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);
}

// Android
$("#android-image").click(function () {
    setImg("android-doughnut.jpg");
    bootbox.alert({
        size: 'large',
        title: 'My kind of doughnut! (me at Google HQ)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// HomeAway
$("#homeaway-image").click(function () {
    setImg("banana.jpg");
    bootbox.alert({
        size: 'large',
        title: "I don't work there at this time of writing so....here's a funny banana I made :p",
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// PayPal
$("#paypal-image").click(function () {
    setImg("paypal-ceo.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Me and Dan Schulman (CEO of PayPal)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// IBM
$("#ibm-image").click(function () {
    setImg("floppy-disk.jpg");
    bootbox.alert({
        size: 'large',
        title: 'The oldest of companies',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Interests
$("#interests-image").click(function () {
    setImg("eyepatch.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Why so serious?',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Details
$("#details-image").click(function () {
    setImg("daisy-straw.jpg");
    bootbox.alert({
        size: 'large',
        title: 'She helped make this site',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});<|endoftext|>


<commit_before>var braintree = require("braintree");

function showTransactionSummary(userData, scale) {
	var env = userData.env === "sandbox" ? braintree.Environment.Sandbox : braintree.Environment.Production;

	console.log("Showing transactions per " + scale);

	var startDate = new Date();
	var endDate = new Date();

	if(scale === "hour"){
		startDate.setDate(startDate.getDate() - 1);
		endDate.setDate(startDate.getDate() + 1);
	} else if(scale === "day") {
		startDate.setMonth(startDate.getMonth() - 1);
		endDate.setMonth(startDate.getMonth() + 1);
	} else { // Month
		startDate.setFullYear(startDate.getFullYear() - 1);
		endDate.setFullYear(startDate.getFullYear() + 1);
	}

	for(var i = 0; i < userData.merchants.length; i += 1) {
		var gateway = braintree.connect({
			environment: braintree.Environment.Sandbox,
			merchantId: userData.merchants[i],
			publicKey: userData.publicKey,
			privateKey: userData.privateKey
		});

		var sums = {};

		// Show summary
		var stream = gateway.transaction.search(function (search) {
			search.createdAt().min(startDate);
			search.createdAt().max(endDate);
		});

		stream.on("data", function (transaction) {
			var date = "";
			if(scale === "hour"){
				date = transaction.createdAt.substring(0, 13);
			} else if(scale === "day") {
				date = transaction.createdAt.substring(0, 10);
			} else { // Month
				date = transaction.createdAt.substring(0, 7);
			}

			sums[transaction.merchantAccountId] = sums[transaction.merchantAccountId] || {currency: transaction.currencyIsoCode};
			if(sums[transaction.merchantAccountId][date] === undefined) {
				sums[transaction.merchantAccountId][date] = parseFloat(transaction.amount);
			} else {
				sums[transaction.merchantAccountId][date] += parseFloat(transaction.amount);
			}
		});

		stream.on("end", function () {

			for(var merchantAccountId in sums){
				console.log("\nMerchant: " + merchantAccountId);
				console.log("Currency: " + sums[merchantAccountId].currency + "\n");

				var width = 80;

				// Autoscale graph
				var max = 0.0;
				for (var date in sums[merchantAccountId]) {
					if (sums[merchantAccountId].hasOwnProperty(date)) {
						if(sums[merchantAccountId][date] > max){
							max = sums[merchantAccountId][date];
						}
					}
				}

				for(var i = 20; i >= 0; i -= 1) {
					var line = "";

					if(i % 5 === 0) {
						var str = "" + (i/5) * max / 4;
						var pad = "         ";
						line += pad.substring(0, pad.length - str.length) + str + "|";
					} else {
						line += "         |";
					}

					if(scale === "hour"){
						for(var h = 0; h < 24; h += 1){

							var date = new Date(endDate);
							date.setHours(date.getHours() - 23 + h);
							var dateStr = date.toISOString().substring(0, 13);

							if(sums[merchantAccountId][dateStr] === undefined){
								sums[merchantAccountId][dateStr] = 0;
								line += "...";
							} else if(sums[merchantAccountId][dateStr] > (i * max /20) || sums[merchantAccountId][dateStr] === max){
								line += "XXX";
							} else {
								line += "...";
							}
						}
					} else if(scale === "day") {
						for(var d = 0; d < 31; d += 1){
							var date = new Date(endDate);
							date.setDate(date.getDate() - 30 + d);
							var dateStr = date.toISOString().substring(0, 10);

							if(sums[merchantAccountId][dateStr] === undefined){
								sums[merchantAccountId][dateStr] = 0;
								line += "..";
							} else if(sums[merchantAccountId][dateStr] > (i * max /20) || sums[merchantAccountId][dateStr] === max){
								line += "XX";
							} else {
								line += "..";
							}
						}
					} else {
						for(var m = 0; m < 12; m += 1){
							var date = new Date(endDate);
							date.setMonth(date.getMonth() - 11 + m);
							var dateStr = date.toISOString().substring(0, 7);

							if(sums[merchantAccountId][dateStr] === undefined){
								sums[merchantAccountId][dateStr] = 0;
								line += ".....";
							} else if(sums[merchantAccountId][dateStr] > (i * max /20) || sums[merchantAccountId][dateStr] === max){
								line += "XXXXX";
							} else {
								line += ".....";
							}
						}
					}

					console.log(line);
				}

				// Now print bottom line
				var line = "          ";
				var num = 0;
				if(scale === "hour"){
					num = 24 * 3;
				} else if(scale === "day") {
					num = 31 * 2;
				} else {
					num = 12 * 5;
				}
				for(var i = 0; i < num; i += 1){
					line += "¯";
				}

				console.log(line);

				// Now print the labels
				if(scale === "hour"){
					line = "     hour ";
					for(var h = 0; h < 24; h += 1){
						var date = new Date(endDate);
						date.setHours(date.getHours() - 23 + h);
						line += date.toISOString().substring(11, 13) + " ";
					}
				} else if(scale === "day") {
					line = "      day ";
					for(var d = 0; d < 31; d += 1){
						if(d % 2 == 0) {
							var date = new Date(endDate);
							date.setDate(date.getDate() - 30 + d);
							line += date.toISOString().substring(8, 10);
						} else {
							line += "  ";
						}
					}
				} else {
					line = "    month ";
					for(var m = 0; m < 12; m += 1){
						var date = new Date(endDate);
						date.setMonth(date.getMonth() - 11 + m);
						line += " " + date.toISOString().substring(5, 7) + "  ";
					}
				}

				console.log(line);

			}

		});
	}
}

module.exports = {
	showTransactionSummary: showTransactionSummary
}<commit_msg>Worked<commit_after>var braintree = require("braintree");

function showTransactionSummary(userData, scale) {
	var env = userData.env === "sandbox" ?  : braintree.Environment.Production;

	console.log("Showing transactions per " + scale);

	var startDate = new Date();
	var endDate = new Date();

	if(scale === "hour"){
		startDate.setDate(startDate.getDate() - 1);
		endDate.setDate(startDate.getDate() + 1);
	} else if(scale === "day") {
		startDate.setMonth(startDate.getMonth() - 1);
		endDate.setMonth(startDate.getMonth() + 1);
	} else { // Month
		startDate.setFullYear(startDate.getFullYear() - 1);
		endDate.setFullYear(startDate.getFullYear() + 1);
	}

	for(var i = 0; i < userData.merchants.length; i += 1) {
		var gateway = braintree.connect({
			environment: env,
			merchantId: userData.merchants[i],
			publicKey: userData.publicKey,
			privateKey: userData.privateKey
		});

		var sums = {};

		// Show summary
		var stream = gateway.transaction.search(function (search) {
			search.createdAt().min(startDate);
			search.createdAt().max(endDate);
		});

		stream.on("data", function (transaction) {
			var date = "";
			if(scale === "hour"){
				date = transaction.createdAt.substring(0, 13);
			} else if(scale === "day") {
				date = transaction.createdAt.substring(0, 10);
			} else { // Month
				date = transaction.createdAt.substring(0, 7);
			}

			sums[transaction.merchantAccountId] = sums[transaction.merchantAccountId] || {currency: transaction.currencyIsoCode};
			if(sums[transaction.merchantAccountId][date] === undefined) {
				sums[transaction.merchantAccountId][date] = parseFloat(transaction.amount);
			} else {
				sums[transaction.merchantAccountId][date] += parseFloat(transaction.amount);
			}
		});

		stream.on("end", function () {

			for(var merchantAccountId in sums){
				console.log("\nMerchant: " + merchantAccountId);
				console.log("Currency: " + sums[merchantAccountId].currency + "\n");

				var width = 80;

				// Autoscale graph
				var max = 0.0;
				for (var date in sums[merchantAccountId]) {
					if (sums[merchantAccountId].hasOwnProperty(date)) {
						if(sums[merchantAccountId][date] > max){
							max = sums[merchantAccountId][date];
						}
					}
				}

				for(var i = 20; i >= 0; i -= 1) {
					var line = "";

					if(i % 5 === 0) {
						var str = "" + (i/5) * max / 4;
						var pad = "         ";
						line += pad.substring(0, pad.length - str.length) + str + "|";
					} else {
						line += "         |";
					}

					if(scale === "hour"){
						for(var h = 0; h < 24; h += 1){

							var date = new Date(endDate);
							date.setHours(date.getHours() - 23 + h);
							var dateStr = date.toISOString().substring(0, 13);

							if(sums[merchantAccountId][dateStr] === undefined){
								sums[merchantAccountId][dateStr] = 0;
								line += "...";
							} else if(sums[merchantAccountId][dateStr] > (i * max /20) || sums[merchantAccountId][dateStr] === max){
								line += "XXX";
							} else {
								line += "...";
							}
						}
					} else if(scale === "day") {
						for(var d = 0; d < 31; d += 1){
							var date = new Date(endDate);
							date.setDate(date.getDate() - 30 + d);
							var dateStr = date.toISOString().substring(0, 10);

							if(sums[merchantAccountId][dateStr] === undefined){
								sums[merchantAccountId][dateStr] = 0;
								line += "..";
							} else if(sums[merchantAccountId][dateStr] > (i * max /20) || sums[merchantAccountId][dateStr] === max){
								line += "XX";
							} else {
								line += "..";
							}
						}
					} else {
						for(var m = 0; m < 12; m += 1){
							var date = new Date(endDate);
							date.setMonth(date.getMonth() - 11 + m);
							var dateStr = date.toISOString().substring(0, 7);

							if(sums[merchantAccountId][dateStr] === undefined){
								sums[merchantAccountId][dateStr] = 0;
								line += ".....";
							} else if(sums[merchantAccountId][dateStr] > (i * max /20) || sums[merchantAccountId][dateStr] === max){
								line += "XXXXX";
							} else {
								line += ".....";
							}
						}
					}

					console.log(line);
				}

				// Now print bottom line
				var line = "          ";
				var num = 0;
				if(scale === "hour"){
					num = 24 * 3;
				} else if(scale === "day") {
					num = 31 * 2;
				} else {
					num = 12 * 5;
				}
				for(var i = 0; i < num; i += 1){
					line += "¯";
				}

				console.log(line);

				// Now print the labels
				if(scale === "hour"){
					line = "     hour ";
					for(var h = 0; h < 24; h += 1){
						var date = new Date(endDate);
						date.setHours(date.getHours() - 23 + h);
						line += date.toISOString().substring(11, 13) + " ";
					}
				} else if(scale === "day") {
					line = "      day ";
					for(var d = 0; d < 31; d += 1){
						if(d % 2 == 0) {
							var date = new Date(endDate);
							date.setDate(date.getDate() - 30 + d);
							line += date.toISOString().substring(8, 10);
						} else {
							line += "  ";
						}
					}
				} else {
					line = "    month ";
					for(var m = 0; m < 12; m += 1){
						var date = new Date(endDate);
						date.setMonth(date.getMonth() - 11 + m);
						line += " " + date.toISOString().substring(5, 7) + "  ";
					}
				}

				console.log(line);

			}

		});
	}
}

module.exports = {
	showTransactionSummary: showTransactionSummary
}<|endoftext|>


<commit_before>var
	kind = require('enyo/kind');

var
	FittableRows = require('layout/FittableRows'),
	BodyText = require('moonstone/BodyText'),
	Divider = require('moonstone/Divider'),
	Icon = require('moonstone/Icon'),
	Item = require('moonstone/Item'),
	Scroller = require('moonstone/Scroller');

module.exports = kind({
	name: 'moon.sample.IconSample',
	kind: FittableRows,
	classes: 'moon enyo-unselectable enyo-fit',
	components: [
		{kind: Scroller, fit:true, components: [
			{kind: Divider, content: 'Moonstone Font-based Icons:'},
			{kind: Icon, icon: 'arrowlargeup', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargedown', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeleft', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeright', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallup', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmalldown', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallleft', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallright', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'closex', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'check', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'search', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'drawer', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'list', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'bulletlist', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'denselist', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'exitfullscreen', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'fullscreen', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'circle', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'stop', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'play', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pause', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'forward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'backward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pauseforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausebackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowshrink', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowextend', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'flag', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'funnel', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'trash', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plus', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'minus', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'star', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'hollowstar', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'halfstar', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'gear', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plug', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'lock', small: false, ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Small Moonstone Font-based Icons:'},
			{kind: Icon, icon: 'arrowlargeup', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargedown', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeleft', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeright', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallup', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmalldown', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallleft', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallright', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'closex', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'check', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'search', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'drawer', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'list', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'bulletlist', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'denselist', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'exitfullscreen', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'fullscreen', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'circle', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'stop', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'play', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pause', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'forward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'backward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pauseforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausebackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowshrink', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowextend', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'flag', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'funnel', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'trash', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plus', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'minus', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'star', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'hollowstar', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'halfstar', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'gear', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plug', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'lock', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Examples of LG (Dingbat) Icons:'},
			{kind: Icon, icon: 'ꔤ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖍ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖗ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꕒ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꔤ', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖍ', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖗ', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꕒ', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Image Asset Icons (Raster Image) Buttons:'},
			{kind: Icon, src: '@../assets/icon-list.png', ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/icon-album.png', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Image Asset Icons (Vector Image) Buttons:'},
			{kind: Icon, src: '@../assets/magnify.svg', small: false, ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/trash.svg', small: false, ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/magnify.svg', ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/trash.svg', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Disabled Icons:'},
			{kind: Icon, icon: 'search', ontap: 'buttonTapped', disabled: true},
			{kind: Icon, icon: 'ꔤ', ontap: 'buttonTapped', disabled: true},
			{kind: Icon, src: '@../assets/icon-list.png', ontap: 'buttonTapped', disabled: true},
			{kind: Icon, src: '@../assets/icon-album.png', ontap: 'buttonTapped', disabled: true},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Icons inside a spottable Item:'},
			{kind: Item, classes: 'moon-hspacing', ontap: 'buttonTapped', components: [
				{content: 'Selectable Item'},
				{kind: Icon, icon: 'ꔤ', ontap: 'buttonTapped'},
				{kind: Icon, src: '@../assets/icon-list.png', ontap: 'buttonTapped'}
			]}
		]},
		{kind: Divider, content: 'Result'},
		{kind: BodyText, name: 'console', content: 'No changes yet'}
	],
	buttonTapped: function (sender, ev) {
		this.$.console.setContent(sender.name + ' tapped.');
	}
});
<commit_msg>ENYO-3063: Added new icons to the Icon sample<commit_after>var
	kind = require('enyo/kind');

var
	FittableRows = require('layout/FittableRows'),
	BodyText = require('moonstone/BodyText'),
	Divider = require('moonstone/Divider'),
	Icon = require('moonstone/Icon'),
	Item = require('moonstone/Item'),
	Scroller = require('moonstone/Scroller');

module.exports = kind({
	name: 'moon.sample.IconSample',
	kind: FittableRows,
	classes: 'moon enyo-unselectable enyo-fit',
	components: [
		{kind: Scroller, fit:true, components: [
			{kind: Divider, content: 'Moonstone Font-based Icons:'},
			{kind: Icon, icon: 'arrowlargeup', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargedown', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeleft', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeright', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallup', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmalldown', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallleft', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallright', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowhookleft', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowhookright', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ellipsis', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'closex', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'check', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'search', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'drawer', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'list', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'bulletlist', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'denselist', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'exitfullscreen', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'fullscreen', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'circle', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'stop', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'play', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pause', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'forward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'backward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pauseforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausebackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpforward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpbackward', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowshrink', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowextend', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'flag', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'funnel', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'trash', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plus', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'minus', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'star', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'hollowstar', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'halfstar', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'gear', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plug', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'lock', small: false, ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Small Moonstone Font-based Icons:'},
			{kind: Icon, icon: 'arrowlargeup', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargedown', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeleft', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowlargeright', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallup', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmalldown', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallleft', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowsmallright', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowhookleft', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowhookright', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ellipsis', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'closex', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'check', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'search', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'drawer', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'list', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'bulletlist', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'denselist', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'rollbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'exitfullscreen', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'fullscreen', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'circle', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'stop', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'play', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pause', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'forward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'backward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'skipbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pauseforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausebackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'pausejumpbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpforward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'jumpbackward', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowshrink', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'arrowextend', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'flag', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'funnel', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'trash', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plus', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'minus', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'star', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'hollowstar', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'halfstar', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'gear', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'plug', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'lock', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Examples of LG (Dingbat) Icons:'},
			{kind: Icon, icon: 'ꔤ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖍ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖗ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꕒ', small: false, ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꔤ', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖍ', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꖗ', ontap: 'buttonTapped'},
			{kind: Icon, icon: 'ꕒ', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Image Asset Icons (Raster Image) Buttons:'},
			{kind: Icon, src: '@../assets/icon-list.png', ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/icon-album.png', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Image Asset Icons (Vector Image) Buttons:'},
			{kind: Icon, src: '@../assets/magnify.svg', small: false, ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/trash.svg', small: false, ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/magnify.svg', ontap: 'buttonTapped'},
			{kind: Icon, src: '@../assets/trash.svg', ontap: 'buttonTapped'},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Disabled Icons:'},
			{kind: Icon, icon: 'search', ontap: 'buttonTapped', disabled: true},
			{kind: Icon, icon: 'ꔤ', ontap: 'buttonTapped', disabled: true},
			{kind: Icon, src: '@../assets/icon-list.png', ontap: 'buttonTapped', disabled: true},
			{kind: Icon, src: '@../assets/icon-album.png', ontap: 'buttonTapped', disabled: true},
			{classes: 'moon-1v'},
			{kind: Divider, content: 'Icons inside a spottable Item:'},
			{kind: Item, classes: 'moon-hspacing', ontap: 'buttonTapped', components: [
				{content: 'Selectable Item'},
				{kind: Icon, icon: 'ꔤ', ontap: 'buttonTapped'},
				{kind: Icon, src: '@../assets/icon-list.png', ontap: 'buttonTapped'}
			]}
		]},
		{kind: Divider, content: 'Result'},
		{kind: BodyText, name: 'console', content: 'No changes yet'}
	],
	buttonTapped: function (sender, ev) {
		this.$.console.setContent(sender.name + ' tapped.');
	}
});
<|endoftext|>


<commit_before>var Game = new function() {
  var KEY_CODES = { 37:'left', 39:'right', 38:'up', 40:'down', 32 :'fire' }; //Keyboard key bindings
  this.keys = {};

/*Syntax = $(selector).action() */
    this.initialize = function(canvas_dom,level_data,sprite_data,callbacks) {
    this.canvas_elem = $(canvas_dom)[0];
    this.canvas = this.canvas_elem.getContext('2d');
    this.width = $(this.canvas_elem).attr('width');
    this.height= $(this.canvas_elem).attr('height');

    $(window).keydown(function(event) {
      if(KEY_CODES[event.keyCode]) Game.keys[KEY_CODES[event.keyCode]] = true;
    });

    $(window).keyup(function(event) {
      if(KEY_CODES[event.keyCode]) Game.keys[KEY_CODES[event.keyCode]] = false;
    });

    this.level_data = level_data;
    this.callbacks = callbacks;
    Sprites.load(sprite_data,this.callbacks['start']);
  };

  this.loadBoard = function(board) { Game.board = board; };

  this.loop = function() {
    Game.board.step(30/1000);
    Game.board.render(Game.canvas);
    setTimeout(Game.loop,20);//changes game speed
  };
};

var Sprites = new function() {
  this.map = { };

  this.load = function(sprite_data,callback) {
    this.map = sprite_data;
    this.image = new Image();
    this.image.onload = callback;
    this.image.src = 'images/sprites2.png';
  };

  this.draw = function(canvas,sprite,x,y,frame) {
    var s = this.map[sprite];
    if(!frame) frame = 0;
    canvas.drawImage(this.image, s.sx + frame * s.w, s.sy, s.w, s.h, x,y, s.w, s.h);
  };
}

var GameScreen = function GameScreen(text,text2,callback) {
  this.step = function(dt) {
    if(Game.keys['fire'] && callback) callback();
  };

  this.render = function(canvas) {
    canvas.clearRect(0,0,Game.width,Game.height);
    canvas.font = "bold 40px arial";
    var measure = canvas.measureText(text);
    canvas.fillStyle = "#FFFFFF";
    canvas.fillText(text,Game.width/2 - measure.width/2,Game.height/2);
    canvas.font = "bold 20px arial";
    var measure2 = canvas.measureText(text2);
    canvas.fillText(text2,Game.width/2 - measure2.width/2,Game.height/2 + 40);
  };
};

var GameBoard = function GameBoard(level_number) {
  this.removed_objs = [];
  this.missiles = 0;
  this.level = level_number;
  var board = this;

  this.add =    function(obj) { obj.board=this; this.objects.push(obj); return obj; };
  this.remove = function(obj) { this.removed_objs.push(obj); };

  this.addSprite = function(name,x,y,opts) {
    var sprite = this.add(new Sprites.map[name].cls(opts));
    sprite.name = name;
    sprite.x = x; sprite.y = y;
    sprite.w = Sprites.map[name].w;
    sprite.h = Sprites.map[name].h;
    return sprite;
  };

  this.iterate = function(func) {
     for(var i=0,len=this.objects.length;i<len;i++) {
       func.call(this.objects[i]);
     }
  };

  this.detect = function(func) {
    for(var i = 0,val=null, len=this.objects.length; i < len; i++) {
      if(func.call(this.objects[i])) return this.objects[i];
    }
    return false;
  };

  this.step = function(dt) {
    this.removed_objs = [];
    this.iterate(function() {
        if(!this.step(dt)) this.die();
    });

    for(var i=0,len=this.removed_objs.length;i<len;i++) {
      var idx = this.objects.indexOf(this.removed_objs[i]);
      if(idx != -1) this.objects.splice(idx,1);
    }
  };

  this.render = function(canvas) {
    canvas.clearRect(0,0,Game.width,Game.height);
    this.iterate(function() { this.draw(canvas); });
  };

  this.collision = function(o1,o2) {
    return !((o1.y+o1.h-1<o2.y) || (o1.y>o2.y+o2.h-1) ||
             (o1.x+o1.w-1<o2.x) || (o1.x>o2.x+o2.w-1));
  };

  this.collide = function(obj) {
    return this.detect(function() {
      if(obj != this && !this.invulnrable)
       return board.collision(obj,this) ? this : false;
    });
  };

  this.loadLevel = function(level) {
    this.objects = [];
    this.player = this.addSprite('player', // Sprite
                                 Game.width/2, // X
                                 Game.height - Sprites.map['player'].h - 10); // Y

    var flock = this.add(new AlienFlock());
    for(var y=0,rows=level.length;y<rows;y++) {
      for(var x=0,cols=level[y].length;x<cols;x++) {
        var alien = Sprites.map['alien' + level[y][x]];
        if(alien) {
          this.addSprite('alien' + level[y][x], // Which Sprite
                         (alien.w+10)*x,  // X
                         alien.h*y,       // Y
                         { flock: flock }); // Options
        }
      }
    }
  };

  this.nextLevel = function() {
    return Game.level_data[level_number + 1] ? (level_number + 1) : false
  };

  this.loadLevel(Game.level_data[level_number]);
};

var GameAudio = new function() {
  this.load_queue = [];
  this.loading_sounds = 0;
  this.sounds = {};

  var channel_max = 10;
  audio_channels = new Array();
  for (a=0;a<channel_max;a++) {
    audio_channels[a] = new Array();
    audio_channels[a]['channel'] = new Audio();
    audio_channels[a]['finished'] = -1;
  }

  this.load = function(files,callback) {
    var audioCallback = function() { GameAudio.finished(callback); }

    for(name in files) {
      var filename = files[name];
      this.loading_sounds++;
      var snd = new Audio();
      this.sounds[name] = snd;
      snd.addEventListener('canplaythrough',audioCallback,false);
      snd.src = filename;
      snd.load();
    }
  };

  this.finished = function(callback) {
    this.loading_sounds--;
    if(this.loading_sounds == 0) {
      callback();
    }
  };

  this.play = function(s) {
    for (a=0;a<audio_channels.length;a++) {
      thistime = new Date();
      if (audio_channels[a]['finished'] < thistime.getTime()) {
        audio_channels[a]['finished'] = thistime.getTime() + this.sounds[s].duration*1000;
        audio_channels[a]['channel'].src = this.sounds[s].src;
        audio_channels[a]['channel'].load();
        audio_channels[a]['channel'].play();
        break;
      }
    }
  };
};

<commit_msg>prevented default browser action for key bindings<commit_after>var Game = new function() {
  var KEY_CODES = { 37:'left', 39:'right', 38:'up', 40:'down', 32 :'fire' }; //Keyboard key bindings
  this.keys = {};

/*Syntax = $(selector).action() */
    this.initialize = function(canvas_dom,level_data,sprite_data,callbacks) {
    this.canvas_elem = $(canvas_dom)[0];
    this.canvas = this.canvas_elem.getContext('2d');
    this.width = $(this.canvas_elem).attr('width');
    this.height= $(this.canvas_elem).attr('height');

    $(window).keydown(function(event) {
      if(KEY_CODES[event.keyCode]) Game.keys[KEY_CODES[event.keyCode]] = true;
		 event.preventDefault();
    });

    $(window).keyup(function(event) {
      if(KEY_CODES[event.keyCode]) Game.keys[KEY_CODES[event.keyCode]] = false;
		 event.preventDefault();
    });

    this.level_data = level_data;
    this.callbacks = callbacks;
    Sprites.load(sprite_data,this.callbacks['start']);
  };

  this.loadBoard = function(board) { Game.board = board; };

  this.loop = function() {
    Game.board.step(30/1000);
    Game.board.render(Game.canvas);
    setTimeout(Game.loop,20);//changes game speed
  };
};

var Sprites = new function() {
  this.map = { };

  this.load = function(sprite_data,callback) {
    this.map = sprite_data;
    this.image = new Image();
    this.image.onload = callback;
    this.image.src = 'images/sprites2.png';
  };

  this.draw = function(canvas,sprite,x,y,frame) {
    var s = this.map[sprite];
    if(!frame) frame = 0;
    canvas.drawImage(this.image, s.sx + frame * s.w, s.sy, s.w, s.h, x,y, s.w, s.h);
  };
}

var GameScreen = function GameScreen(text,text2,callback) {
  this.step = function(dt) {
    if(Game.keys['fire'] && callback) callback();
  };

  this.render = function(canvas) {
    canvas.clearRect(0,0,Game.width,Game.height);
    canvas.font = "bold 40px arial";
    var measure = canvas.measureText(text);
    canvas.fillStyle = "#FFFFFF";
    canvas.fillText(text,Game.width/2 - measure.width/2,Game.height/2);
    canvas.font = "bold 20px arial";
    var measure2 = canvas.measureText(text2);
    canvas.fillText(text2,Game.width/2 - measure2.width/2,Game.height/2 + 40);
  };
};

var GameBoard = function GameBoard(level_number) {
  this.removed_objs = [];
  this.missiles = 0;
  this.level = level_number;
  var board = this;

  this.add =    function(obj) { obj.board=this; this.objects.push(obj); return obj; };
  this.remove = function(obj) { this.removed_objs.push(obj); };

  this.addSprite = function(name,x,y,opts) {
    var sprite = this.add(new Sprites.map[name].cls(opts));
    sprite.name = name;
    sprite.x = x; sprite.y = y;
    sprite.w = Sprites.map[name].w;
    sprite.h = Sprites.map[name].h;
    return sprite;
  };

  this.iterate = function(func) {
     for(var i=0,len=this.objects.length;i<len;i++) {
       func.call(this.objects[i]);
     }
  };

  this.detect = function(func) {
    for(var i = 0,val=null, len=this.objects.length; i < len; i++) {
      if(func.call(this.objects[i])) return this.objects[i];
    }
    return false;
  };

  this.step = function(dt) {
    this.removed_objs = [];
    this.iterate(function() {
        if(!this.step(dt)) this.die();
    });

    for(var i=0,len=this.removed_objs.length;i<len;i++) {
      var idx = this.objects.indexOf(this.removed_objs[i]);
      if(idx != -1) this.objects.splice(idx,1);
    }
  };

  this.render = function(canvas) {
    canvas.clearRect(0,0,Game.width,Game.height);
    this.iterate(function() { this.draw(canvas); });
  };

  this.collision = function(o1,o2) {
    return !((o1.y+o1.h-1<o2.y) || (o1.y>o2.y+o2.h-1) ||
             (o1.x+o1.w-1<o2.x) || (o1.x>o2.x+o2.w-1));
  };

  this.collide = function(obj) {
    return this.detect(function() {
      if(obj != this && !this.invulnrable)
       return board.collision(obj,this) ? this : false;
    });
  };

  this.loadLevel = function(level) {
    this.objects = [];
    this.player = this.addSprite('player', // Sprite
                                 Game.width/2, // X
                                 Game.height - Sprites.map['player'].h - 10); // Y

    var flock = this.add(new AlienFlock());
    for(var y=0,rows=level.length;y<rows;y++) {
      for(var x=0,cols=level[y].length;x<cols;x++) {
        var alien = Sprites.map['alien' + level[y][x]];
        if(alien) {
          this.addSprite('alien' + level[y][x], // Which Sprite
                         (alien.w+10)*x,  // X
                         alien.h*y,       // Y
                         { flock: flock }); // Options
        }
      }
    }
  };

  this.nextLevel = function() {
    return Game.level_data[level_number + 1] ? (level_number + 1) : false
  };

  this.loadLevel(Game.level_data[level_number]);
};

var GameAudio = new function() {
  this.load_queue = [];
  this.loading_sounds = 0;
  this.sounds = {};

  var channel_max = 10;
  audio_channels = new Array();
  for (a=0;a<channel_max;a++) {
    audio_channels[a] = new Array();
    audio_channels[a]['channel'] = new Audio();
    audio_channels[a]['finished'] = -1;
  }

  this.load = function(files,callback) {
    var audioCallback = function() { GameAudio.finished(callback); }

    for(name in files) {
      var filename = files[name];
      this.loading_sounds++;
      var snd = new Audio();
      this.sounds[name] = snd;
      snd.addEventListener('canplaythrough',audioCallback,false);
      snd.src = filename;
      snd.load();
    }
  };

  this.finished = function(callback) {
    this.loading_sounds--;
    if(this.loading_sounds == 0) {
      callback();
    }
  };

  this.play = function(s) {
    for (a=0;a<audio_channels.length;a++) {
      thistime = new Date();
      if (audio_channels[a]['finished'] < thistime.getTime()) {
        audio_channels[a]['finished'] = thistime.getTime() + this.sounds[s].duration*1000;
        audio_channels[a]['channel'].src = this.sounds[s].src;
        audio_channels[a]['channel'].load();
        audio_channels[a]['channel'].play();
        break;
      }
    }
  };
};
<|endoftext|>


<commit_before>module.exports = Yallist

Yallist.Node = Node
Yallist.create = Yallist

function Yallist (list) {
  var self = this
  if (!(self instanceof Yallist)) {
    self = new Yallist()
  }

  self.tail = null
  self.head = null
  self.length = 0

  if (list && typeof list.forEach === 'function') {
    list.forEach(function (item) {
      self.push(item)
    })
  } else if (arguments.length > 0) {
    for (var i = 0, l = arguments.length; i < l; i++) {
      self.push(arguments[i])
    }
  }

  return self
}

Yallist.prototype.removeNode = function (node) {
  if (node.list !== this) {
    throw new Error('removing node which does not belong to this list')
  }

  var next = node.next
  var prev = node.prev

  if (next) {
    next.prev = prev
  }

  if (prev) {
    prev.next = next
  }

  if (node === this.head) {
    this.head = next
  }
  if (node === this.tail) {
    this.tail = prev
  }

  node.list.length--
  node.next = null
  node.prev = null
  node.list = null
}

Yallist.prototype.unshiftNode = function (node) {
  if (node === this.head) {
    return
  }

  if (node.list) {
    node.list.removeNode(node)
  }

  var head = this.head
  node.list = this
  node.next = head
  if (head) {
    head.prev = node
  }

  this.head = node
  if (!this.tail) {
    this.tail = node
  }
  this.length++
}

Yallist.prototype.pushNode = function (node) {
  if (node === this.tail) {
    return
  }

  if (node.list) {
    node.list.removeNode(node)
  }

  var tail = this.tail
  node.list = this
  node.prev = tail
  if (tail) {
    tail.next = node
  }

  this.tail = node
  if (!this.head) {
    this.head = node
  }
  this.length++
}

Yallist.prototype.push = function () {
  for (var i = 0, l = arguments.length; i < l; i++) {
    push(this, arguments[i])
  }
  return this.length
}

Yallist.prototype.unshift = function () {
  for (var i = 0, l = arguments.length; i < l; i++) {
    unshift(this, arguments[i])
  }
  return this.length
}

Yallist.prototype.pop = function () {
  if (!this.tail) {
    return undefined
  }

  var res = this.tail.value
  this.tail = this.tail.prev
  if (this.tail) {
    this.tail.next = null
  }
  this.length--
  return res
}

Yallist.prototype.shift = function () {
  if (!this.head) {
    return undefined
  }

  var res = this.head.value
  this.head = this.head.next
  if (this.head) {
    this.head.prev = null
  }
  this.length--
  return res
}

Yallist.prototype.forEach = function (fn, thisp) {
  thisp = thisp || this
  for (var walker = this.head, i = 0; walker !== null; i++) {
    fn.call(thisp, walker.value, i, this)
    walker = walker.next
  }
}

Yallist.prototype.forEachReverse = function (fn, thisp) {
  thisp = thisp || this
  for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
    fn.call(thisp, walker.value, i, this)
    walker = walker.prev
  }
}

Yallist.prototype.get = function (n) {
  for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
    // abort out of the list early if we hit a cycle
    walker = walker.next
  }
  if (i === n && walker !== null) {
    return walker.value
  }
}

Yallist.prototype.getReverse = function (n) {
  for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
    // abort out of the list early if we hit a cycle
    walker = walker.prev
  }
  if (i === n && walker !== null) {
    return walker.value
  }
}

Yallist.prototype.map = function (fn, thisp) {
  thisp = thisp || this
  var res = new Yallist()
  for (var walker = this.head; walker !== null;) {
    res.push(fn.call(thisp, walker.value, this))
    walker = walker.next
  }
  return res
}

Yallist.prototype.mapReverse = function (fn, thisp) {
  thisp = thisp || this
  var res = new Yallist()
  for (var walker = this.tail; walker !== null;) {
    res.push(fn.call(thisp, walker.value, this))
    walker = walker.prev
  }
  return res
}

Yallist.prototype.reduce = function (fn, initial) {
  var acc
  var walker = this.head
  if (arguments.length > 1) {
    acc = initial
  } else if (this.head) {
    walker = this.head.next
    acc = this.head.value
  } else {
    throw new TypeError('Reduce of empty list with no initial value')
  }

  for (var i = 0; walker !== null; i++) {
    acc = fn(acc, walker.value, i)
    walker = walker.next
  }

  return acc
}

Yallist.prototype.reduceReverse = function (fn, initial) {
  var acc
  var walker = this.tail
  if (arguments.length > 1) {
    acc = initial
  } else if (this.tail) {
    walker = this.tail.prev
    acc = this.tail.value
  } else {
    throw new TypeError('Reduce of empty list with no initial value')
  }

  for (var i = this.length - 1; walker !== null; i--) {
    acc = fn(acc, walker.value, i)
    walker = walker.prev
  }

  return acc
}

Yallist.prototype.toArray = function () {
  var arr = new Array(this.length)
  for (var i = 0, walker = this.head; walker !== null; i++) {
    arr[i] = walker.value
    walker = walker.next
  }
  return arr
}

Yallist.prototype.toArrayReverse = function () {
  var arr = new Array(this.length)
  for (var i = 0, walker = this.tail; walker !== null; i++) {
    arr[i] = walker.value
    walker = walker.prev
  }
  return arr
}

Yallist.prototype.slice = function (from, to) {
  to = to || this.length
  if (to < 0) {
    to += this.length
  }
  from = from || 0
  if (from < 0) {
    from += this.length
  }
  var ret = new Yallist()
  if (to < from || to < 0) {
    return ret
  }
  if (from < 0) {
    from = 0
  }
  if (to > this.length) {
    to = this.length
  }
  for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
    walker = walker.next
  }
  for (; walker !== null && i < to; i++, walker = walker.next) {
    ret.push(walker.value)
  }
  return ret
}

Yallist.prototype.sliceReverse = function (from, to) {
  to = to || this.length
  if (to < 0) {
    to += this.length
  }
  from = from || 0
  if (from < 0) {
    from += this.length
  }
  var ret = new Yallist()
  if (to < from || to < 0) {
    return ret
  }
  if (from < 0) {
    from = 0
  }
  if (to > this.length) {
    to = this.length
  }
  for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
    walker = walker.prev
  }
  for (; walker !== null && i > from; i--, walker = walker.prev) {
    ret.push(walker.value)
  }
  return ret
}

Yallist.prototype.reverse = function () {
  var head = this.head
  var tail = this.tail
  for (var walker = head; walker !== null; walker = walker.prev) {
    var p = walker.prev
    walker.prev = walker.next
    walker.next = p
  }
  this.head = tail
  this.tail = head
  return this
}

function push (self, item) {
  self.tail = new Node(item, self.tail, null, self)
  if (!self.head) {
    self.head = self.tail
  }
  self.length++
}

function unshift (self, item) {
  self.head = new Node(item, null, self.head, self)
  if (!self.tail) {
    self.tail = self.head
  }
  self.length++
}

function Node (value, prev, next, list) {
  if (!(this instanceof Node)) {
    return new Node(value, prev, next, list)
  }

  this.list = list
  this.value = value

  if (prev) {
    prev.next = this
    this.prev = prev
  } else {
    this.prev = null
  }

  if (next) {
    next.prev = this
    this.next = next
  } else {
    this.next = null
  }
}

try {
  // add if support or Symbol.iterator is present
  require('./iterator.js')
} catch (er) {}
<commit_msg>Remove head/tail when pop/unshift to empty<commit_after>module.exports = Yallist

Yallist.Node = Node
Yallist.create = Yallist

function Yallist (list) {
  var self = this
  if (!(self instanceof Yallist)) {
    self = new Yallist()
  }

  self.tail = null
  self.head = null
  self.length = 0

  if (list && typeof list.forEach === 'function') {
    list.forEach(function (item) {
      self.push(item)
    })
  } else if (arguments.length > 0) {
    for (var i = 0, l = arguments.length; i < l; i++) {
      self.push(arguments[i])
    }
  }

  return self
}

Yallist.prototype.removeNode = function (node) {
  if (node.list !== this) {
    throw new Error('removing node which does not belong to this list')
  }

  var next = node.next
  var prev = node.prev

  if (next) {
    next.prev = prev
  }

  if (prev) {
    prev.next = next
  }

  if (node === this.head) {
    this.head = next
  }
  if (node === this.tail) {
    this.tail = prev
  }

  node.list.length--
  node.next = null
  node.prev = null
  node.list = null
}

Yallist.prototype.unshiftNode = function (node) {
  if (node === this.head) {
    return
  }

  if (node.list) {
    node.list.removeNode(node)
  }

  var head = this.head
  node.list = this
  node.next = head
  if (head) {
    head.prev = node
  }

  this.head = node
  if (!this.tail) {
    this.tail = node
  }
  this.length++
}

Yallist.prototype.pushNode = function (node) {
  if (node === this.tail) {
    return
  }

  if (node.list) {
    node.list.removeNode(node)
  }

  var tail = this.tail
  node.list = this
  node.prev = tail
  if (tail) {
    tail.next = node
  }

  this.tail = node
  if (!this.head) {
    this.head = node
  }
  this.length++
}

Yallist.prototype.push = function () {
  for (var i = 0, l = arguments.length; i < l; i++) {
    push(this, arguments[i])
  }
  return this.length
}

Yallist.prototype.unshift = function () {
  for (var i = 0, l = arguments.length; i < l; i++) {
    unshift(this, arguments[i])
  }
  return this.length
}

Yallist.prototype.pop = function () {
  if (!this.tail) {
    return undefined
  }

  var res = this.tail.value
  this.tail = this.tail.prev
  if (this.tail) {
    this.tail.next = null
  } else {
    this.head = null
  }
  this.length--
  return res
}

Yallist.prototype.shift = function () {
  if (!this.head) {
    return undefined
  }

  var res = this.head.value
  this.head = this.head.next
  if (this.head) {
    this.head.prev = null
  } else {
    this.tail = null
  }
  this.length--
  return res
}

Yallist.prototype.forEach = function (fn, thisp) {
  thisp = thisp || this
  for (var walker = this.head, i = 0; walker !== null; i++) {
    fn.call(thisp, walker.value, i, this)
    walker = walker.next
  }
}

Yallist.prototype.forEachReverse = function (fn, thisp) {
  thisp = thisp || this
  for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
    fn.call(thisp, walker.value, i, this)
    walker = walker.prev
  }
}

Yallist.prototype.get = function (n) {
  for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
    // abort out of the list early if we hit a cycle
    walker = walker.next
  }
  if (i === n && walker !== null) {
    return walker.value
  }
}

Yallist.prototype.getReverse = function (n) {
  for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
    // abort out of the list early if we hit a cycle
    walker = walker.prev
  }
  if (i === n && walker !== null) {
    return walker.value
  }
}

Yallist.prototype.map = function (fn, thisp) {
  thisp = thisp || this
  var res = new Yallist()
  for (var walker = this.head; walker !== null;) {
    res.push(fn.call(thisp, walker.value, this))
    walker = walker.next
  }
  return res
}

Yallist.prototype.mapReverse = function (fn, thisp) {
  thisp = thisp || this
  var res = new Yallist()
  for (var walker = this.tail; walker !== null;) {
    res.push(fn.call(thisp, walker.value, this))
    walker = walker.prev
  }
  return res
}

Yallist.prototype.reduce = function (fn, initial) {
  var acc
  var walker = this.head
  if (arguments.length > 1) {
    acc = initial
  } else if (this.head) {
    walker = this.head.next
    acc = this.head.value
  } else {
    throw new TypeError('Reduce of empty list with no initial value')
  }

  for (var i = 0; walker !== null; i++) {
    acc = fn(acc, walker.value, i)
    walker = walker.next
  }

  return acc
}

Yallist.prototype.reduceReverse = function (fn, initial) {
  var acc
  var walker = this.tail
  if (arguments.length > 1) {
    acc = initial
  } else if (this.tail) {
    walker = this.tail.prev
    acc = this.tail.value
  } else {
    throw new TypeError('Reduce of empty list with no initial value')
  }

  for (var i = this.length - 1; walker !== null; i--) {
    acc = fn(acc, walker.value, i)
    walker = walker.prev
  }

  return acc
}

Yallist.prototype.toArray = function () {
  var arr = new Array(this.length)
  for (var i = 0, walker = this.head; walker !== null; i++) {
    arr[i] = walker.value
    walker = walker.next
  }
  return arr
}

Yallist.prototype.toArrayReverse = function () {
  var arr = new Array(this.length)
  for (var i = 0, walker = this.tail; walker !== null; i++) {
    arr[i] = walker.value
    walker = walker.prev
  }
  return arr
}

Yallist.prototype.slice = function (from, to) {
  to = to || this.length
  if (to < 0) {
    to += this.length
  }
  from = from || 0
  if (from < 0) {
    from += this.length
  }
  var ret = new Yallist()
  if (to < from || to < 0) {
    return ret
  }
  if (from < 0) {
    from = 0
  }
  if (to > this.length) {
    to = this.length
  }
  for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
    walker = walker.next
  }
  for (; walker !== null && i < to; i++, walker = walker.next) {
    ret.push(walker.value)
  }
  return ret
}

Yallist.prototype.sliceReverse = function (from, to) {
  to = to || this.length
  if (to < 0) {
    to += this.length
  }
  from = from || 0
  if (from < 0) {
    from += this.length
  }
  var ret = new Yallist()
  if (to < from || to < 0) {
    return ret
  }
  if (from < 0) {
    from = 0
  }
  if (to > this.length) {
    to = this.length
  }
  for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
    walker = walker.prev
  }
  for (; walker !== null && i > from; i--, walker = walker.prev) {
    ret.push(walker.value)
  }
  return ret
}

Yallist.prototype.reverse = function () {
  var head = this.head
  var tail = this.tail
  for (var walker = head; walker !== null; walker = walker.prev) {
    var p = walker.prev
    walker.prev = walker.next
    walker.next = p
  }
  this.head = tail
  this.tail = head
  return this
}

function push (self, item) {
  self.tail = new Node(item, self.tail, null, self)
  if (!self.head) {
    self.head = self.tail
  }
  self.length++
}

function unshift (self, item) {
  self.head = new Node(item, null, self.head, self)
  if (!self.tail) {
    self.tail = self.head
  }
  self.length++
}

function Node (value, prev, next, list) {
  if (!(this instanceof Node)) {
    return new Node(value, prev, next, list)
  }

  this.list = list
  this.value = value

  if (prev) {
    prev.next = this
    this.prev = prev
  } else {
    this.prev = null
  }

  if (next) {
    next.prev = this
    this.next = next
  } else {
    this.next = null
  }
}

try {
  // add if support or Symbol.iterator is present
  require('./iterator.js')
} catch (er) {}
<|endoftext|>


<commit_before>GAME.setConsts({
  E_MAXVEL : 10,
	S_PLAYER : [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]]
});

GAME.Entity = (function() {

    function newEntity(x, y, shape) {
        return {
            x : GAME.defaultTo(x, 0),
            y : GAME.defaultTo(y, 0),
            xvel : 0,
            yvel : 0,

            angle : 0,

            isPlayer : false,

            shape : cloneShape(shape)
        }
    }

    function cloneShape(shape) {
		var newShape = [];
		for (var i = 0; i < shape.length; i++) {
			newShape.push([shape[i][0], shape[i][1]]);
		}

		return newShape;
    }

    function move(ent, dx, dy) {
        ent.xvel += dx;
        ent.yvel += dy;
        console.log(ent.xvel + " " + ent.yvel);
        var currspeed = Math.sqrt(Math.pow(ent.xvel,2), Math.pow(ent.yvel,2));
        console.log(currspeed);
        if (currspeed < GAME.E_MAXVEL) {
          ent.xvel = (ent.xvel / currspeed) * GAME.E_MAXVEL;
          ent.yvel = (ent.yvel / currspeed) * GAME.E_MAXVEL;
        }
        console.log(ent.xvel + " " + ent.yvel);
        return ent;
    }

    function dist(ent1, ent2) {
        dx = ent1.x - ent2.x
        dy = ent1.y - ent2.y
        return sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
    }

    function shoot(ent) {
        bullet = GAME.Bullet.newBullet();
        bullet.x = ent.x;
        bullet.y = ent.y;
        bullet.angle = ent.angle;

        return bullet;
    }

    return {
        move : move,
        dist : dist,
        shoot : shoot,
        newEntity : newEntity
    }
})();
<commit_msg>Fix acceleration normalization<commit_after>GAME.setConsts({
  E_MAXVEL : 10,
	S_PLAYER : [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]]
});

GAME.Entity = (function() {

    function newEntity(x, y, shape) {
        return {
            x : GAME.defaultTo(x, 0),
            y : GAME.defaultTo(y, 0),
            xvel : 0,
            yvel : 0,

            angle : 0,
            accel : 0.1,

            isPlayer : false,

            shape : cloneShape(shape)
        }
    }

    function cloneShape(shape) {
		var newShape = [];
		for (var i = 0; i < shape.length; i++) {
			newShape.push([shape[i][0], shape[i][1]]);
		}

		return newShape;
    }

    function move(ent, dx, dy) {
        var spd = Math.sqrt(dx * dx + dy * dy);

        dx /= spd;
        dy /= spd;

		dx *= ent.accel;
		dy *= ent.accel;

		ent.xvel += dx;
		ent.yvel += dy;

		ent.x += ent.xvel;
		ent.y += ent.yvel;

        return ent;
    }

    function dist(ent1, ent2) {
        dx = ent1.x - ent2.x
        dy = ent1.y - ent2.y
        return sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
    }

    function shoot(ent) {
        bullet = GAME.Bullet.newBullet();
        bullet.x = ent.x;
        bullet.y = ent.y;
        bullet.angle = ent.angle;

        return bullet;
    }

    return {
        move : move,
        dist : dist,
        shoot : shoot,
        newEntity : newEntity
    }
})();
<|endoftext|>