<commit_before>var config = require('./config');
var path = require('path');
var ipc = require('ipc');
var notifier = require('node-notifier');
var shell = require('shell');
var CronJob = require('cron').CronJob;

function renderFeedback() {
  var templateSource = document.getElementById('template-feedback').innerHTML;
  var template = Handlebars.compile(templateSource);
  var resultsPlaceholder = document.getElementById('result-feedback');
  resultsPlaceholder.innerHTML = template({
    feedback: config.feedback
  });
}

function renderTemplate(type, data) {
  var templateSource = document.getElementById('template-' + type).innerHTML;
  var template = Handlebars.compile(templateSource);
  var resultsPlaceholder = document.getElementById('result-' + type);
  resultsPlaceholder.innerHTML = template(data);
}

function createNotification(events) {
  // TODO: if the upcoming event is in an hour, only then notify
  // FIX: display separate notifications without replacing each other
  events.forEach(function(event) {
    notifier.notify({
      'title': event.name,
      'message': 'by ' + event.group_name + ' on ' + event.formatted_time,
      'icon': path.join(__dirname, 'logo.png'),
      'wait': true,
      'open': event.url
    });
  })
}

function callAPI(type, willNotify){
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){
    var body = JSON.parse(this.responseText);
    var data = {};
    data[type] = body[type].slice(0, 3);
    if (type === 'events' && willNotify) {
      createNotification(data[type]);
    }
    data.website = config.website;
    data.feedback = config.feedback;
    renderTemplate(type, data);
  };
  xhr.open('GET', config.apiUrl + type, true);
  xhr.send();
}

document.body.addEventListener('click', function(e){
  var el = e.target;
  if (!el) return;
  if (el.tagName.toLowerCase() == 'a' && el.target == '_blank'){
    e.preventDefault();
    shell.openExternal(el.href);
  }
});

document.getElementById('quit').addEventListener('click', function() {
  ipc.sendSync('event', 'quit');
})

new CronJob('0 0,30 * * * *', function() {
  callAPI('events', true);
  callAPI('repos', true);
}, null, true, config.timezone);

renderFeedback();
callAPI('events', false);
callAPI('repos', false);
<commit_msg>feature: create a notification if the upcoming event starts within an hour. close #6<commit_after>var config = require('./config');
var path = require('path');
var ipc = require('ipc');
var notifier = require('node-notifier');
var shell = require('shell');
var CronJob = require('cron').CronJob;
var moment = require('moment-timezone');

function renderFeedback() {
  var templateSource = document.getElementById('template-feedback').innerHTML;
  var template = Handlebars.compile(templateSource);
  var resultsPlaceholder = document.getElementById('result-feedback');
  resultsPlaceholder.innerHTML = template({
    feedback: config.feedback
  });
}

function renderTemplate(type, data) {
  var templateSource = document.getElementById('template-' + type).innerHTML;
  var template = Handlebars.compile(templateSource);
  var resultsPlaceholder = document.getElementById('result-' + type);
  resultsPlaceholder.innerHTML = template(data);
}

function isWithinAnHour(startTime) {
  moment(startTime, 'DD MMM YYYY, ddd, hh:mm a').isBefore(moment().add(1, 'hour'))
}

function createNotification(nextEvent) {
  // if upcoming event starts within the next hour,
  // create a notification
  if (isWithinAnHour(nextEvent.formatted_time)) {
    notifier.notify({
      'title': nextEvent.name,
      'message': 'by ' + nextEvent.group_name + ' on ' + nextEvent.formatted_time,
      'icon': path.join(__dirname, 'logo.png'),
      'wait': true,
      'open': nextEvent.url
    });
  }
}

function callAPI(type, willNotify){
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){
    var body = JSON.parse(this.responseText);
    var data = {};
    data[type] = body[type].slice(0, 3);
    if (type === 'events' && willNotify) {
      createNotification(data[type][0]);
    }
    data.website = config.website;
    data.feedback = config.feedback;
    renderTemplate(type, data);
  };
  xhr.open('GET', config.apiUrl + type, true);
  xhr.send();
}

document.body.addEventListener('click', function(e){
  var el = e.target;
  if (!el) return;
  if (el.tagName.toLowerCase() == 'a' && el.target == '_blank'){
    e.preventDefault();
    shell.openExternal(el.href);
  }
});

document.getElementById('quit').addEventListener('click', function() {
  ipc.sendSync('event', 'quit');
})

new CronJob('0 0,30 * * * *', function() {
  callAPI('events', true);
  callAPI('repos', true);
}, null, true, config.timezone);

renderFeedback();
callAPI('events', false);
callAPI('repos', false);
<|endoftext|>


<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}, wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`%[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters hypotheek':
      //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Huis](postback:hypotheekkeuze_huis) %[Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'hypotheek_starter')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say('Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja - graag](postback:update_ja) %[Nee, bedankt](postback:update_nee)'))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja - graag':
            return bot.say(`Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.' `)
            .then(() => 'update_ja');
          break;
          case 'Nee, bedankt':
              receive: () => 'bye'
              break;
          default:
            return bot.say(`...`)
              .then(() => 'processing')
            break;
}
}
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?')
      receive: (bot, message) => {
  //          const emailVisitor = message.text;
  //          //return bot.setProp('emailVisitor', emailVisitor)
  //           .then(()  => bot.say('Ok - dan hou ik je via ${emailVisitor} op de hoogte.'))
  //           .then(()  =>'processing')
    }
},

hypotheekkeuze_appartement: {
receive: (bot,message)  => {
    //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
}
},
hypotheekkeuze_huis: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
  receive: () => 'askName'
},
hypotheekkeuze_vakantiewoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
},
hypotheektype_starter: {
    prompt: (bot) => bot.say('Pleasure meeting you - starter'),
    receive: () => 'processing'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say(`Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`),
    receive: () => 'processing'
},

askName: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case 'Huis':
          return bot.say(`Leuk :)`)
          .then(() => 'vervolgVragen')
          break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
    }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...'),
  receive: (bot, message) => {
      const name = message.text;
      return bot.setProp('name', name)
          .then(() => bot.say(`Hoi ${name}. Ik heb nog wat vragen voor je om verder te kunnen.`))
          .then(() => 'lastCheck');
    }
},

lastCheck: {
    // prompt: (bot) => bot.say('Is er nog iets waar ik  je bij kan helpen? %[JA](postback:nogietsanders) %[NEE](postback:bye) '),
    // .then(()  => 'processing');
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<commit_msg>script<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}, wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`%[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters hypotheek':
      //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Huis](postback:hypotheekkeuze_huis) %[Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'hypotheek_starter')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say('Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja - graag](postback:update_ja) %[Nee, bedankt](postback:update_nee)'))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja - graag':
            return bot.say(`Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.' `)
            .then(() => 'update_ja');
          break;
          case 'Nee, bedankt':
              receive: () => 'bye'
              break;
          default:
            return bot.say(`...`)
              .then(() => 'processing')
            break;
}
}
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
        return bot.say('...')
          .then(() => 'processing')
  //          const emailVisitor = message.text;
  //          //return bot.setProp('emailVisitor', emailVisitor)
  //           .then(()  => bot.say('Ok - dan hou ik je via ${emailVisitor} op de hoogte.'))
  //           .then(()  =>'processing')
    }
},

hypotheekkeuze_appartement: {
receive: (bot,message)  => {
    //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
}
},
hypotheekkeuze_huis: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
  receive: () => 'askName'
},
hypotheekkeuze_vakantiewoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
},
hypotheektype_starter: {
    prompt: (bot) => bot.say('Pleasure meeting you - starter'),
    receive: () => 'processing'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say(`Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`),
    receive: () => 'processing'
},

askName: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case 'Huis':
          return bot.say(`Leuk :)`)
          .then(() => 'vervolgVragen')
          break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
    }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...'),
  receive: (bot, message) => {
      const name = message.text;
      return bot.setProp('name', name)
          .then(() => bot.say(`Hoi ${name}. Ik heb nog wat vragen voor je om verder te kunnen.`))
          .then(() => 'lastCheck');
    }
},

lastCheck: {
    // prompt: (bot) => bot.say('Is er nog iets waar ik  je bij kan helpen? %[JA](postback:nogietsanders) %[NEE](postback:bye) '),
    // .then(()  => 'processing');
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<|endoftext|>


<commit_before>var renderer, stage, container, graphics, zoom,
            world, boxShape, boxBody, planeBody, planeShape,chassisBody,player, cars=[];

        var carTexture;

        var PLAYER=Math.pow(2,1),
            CAR=Math.pow(2,2);

        init();

        function Car(x,y,w,h,angle,velX,velY,mass,world,container,collisionGroup,stage){
            this.chassisBody = new p2.Body({
                position: [x,y],
                mass: mass,
                angle: angle,
                velocity: [velX, velY],
            });

            this.boxShape = new p2.Box({ width: w, height: h });
            this.boxShape.collisionGroup = collisionGroup;
            this.boxShape.collisionMask = PLAYER | CAR
            this.chassisBody.addShape(this.boxShape);
            world.addBody(this.chassisBody);
            // Create the vehicle
            this.vehicle = new p2.TopDownVehicle(this.chassisBody);
            // Add one front wheel and one back wheel - we don't actually need four :)

            this.chassisBody.frontWheel = this.vehicle.addWheel({
                localPosition: [0, 0.5] // front
            });

            this.chassisBody.frontWheel.setSideFriction(200);
            // Back wheel
            this.chassisBody.backWheel = this.vehicle.addWheel({
                localPosition: [0, -0.5] // back
            });
            this.chassisBody.backWheel.setSideFriction(200); // Less side friction on back wheel makes it easier to drift
            this.vehicle.addToWorld(world);

            this.graphics = new PIXI.Graphics();
            this.graphics.beginFill(0xff0000);
            this.texture = carTexture;
            this.sprite = new PIXI.Sprite(this.texture);
            this.graphics.addChild(this.sprite);
            this.graphics.drawRect(-this.boxShape.width/2, -this.boxShape.height/2, this.boxShape.width, this.boxShape.height);
            this.sprite.width = -this.boxShape.width;
            this.sprite.height = -this.boxShape.height;
            this.sprite.position={x:-this.boxShape.width/2, y:this.boxShape.height/2}
            this.sprite.scale.x = -this.sprite.scale.x
            // Add the box to our container
            container.addChild(this.graphics);

            this.update = function(){
                this.graphics.position.x = this.chassisBody.position[0];
                this.graphics.position.y = this.chassisBody.position[1];
                this.graphics.rotation =   this.chassisBody.angle;
            }
        }

        function init(){

            // Init p2.js
            // Create a dynamic body for the chassis
            world = new p2.World({
                gravity : [0,0]
            });

            zoom = 50;

            // Initialize the stage
            renderer =  PIXI.autoDetectRenderer(800, 600),
            stage = new PIXI.Stage(0xFFFFFF);
            container = new PIXI.Container(),
            PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
            PIXI.loader
                        .add('car', 'assets/car.png')
                        .load(function (loader, resources) {
                            carTexture = resources.car.texture;
                            player = new Car(0,0,0.5,1,-1.5,15,0,2,world,container,PLAYER,stage);
                            animate();
            });
            stage.addChild(container);
            document.body.appendChild(renderer.view);
            // Add transform to the container
            container.position.x =  renderer.width/10; // center at origin
            container.position.y =  renderer.height/10;
            container.scale.x =  zoom;  // zoom in
            container.scale.y = -zoom; // Note: we flip the y axis to make "up" the physics "up"

            world.on("impact",function(evt){
                console.log(evt)
                var bodyA = evt.bodyA,
                bodyB = evt.bodyB;
                bodyA.frontWheel.setSideFriction(2);
                bodyB.frontWheel.setSideFriction(2);

                bodyA.backWheel.setSideFriction(2);
                bodyB.backWheel.setSideFriction(2);
            });0

            // Draw the box.

            var keys = {
                '37': 0, // left
                '39': 0, // right
                '38': 0, // up
                '40': 0 // down
            };
            var maxSteer = 20000;
            window.addEventListener("keydown",function (evt){
                keys[evt.keyCode] = 1;
                onInputChange();
            });
            window.addEventListener("keyup",function (evt){
                keys[evt.keyCode] = 0;
                onInputChange();
            });
            function onInputChange(){
                // Steer value zero means straight forward. Positive is left and negative right.
                player.chassisBody.frontWheel.steerValue = maxSteer * (keys[37] - keys[39]);
                player.chassisBody.backWheel.setBrakeForce(0);
                if(keys[40]){
                    if(player.chassisBody.backWheel.getSpeed() > 0.1){
                        // Moving forward - add some brake force to slow down
                        player.chassisBody.backWheel.setBrakeForce(2);
                    } else {
                        // Moving backwards - reverse the engine force
                        player.chassisBody.backWheel.setBrakeForce(2);
                    }
                }
            }
        }

        // Animation loop
        function animate(t){
            t = t || 0;
            requestAnimationFrame(animate);

            // Move physics bodies forward in time
            world.step(1/60);

            // Transfer positions of the physics objects to Pixi.js

            player.update();
            for (var i = cars.length - 1; i >= 0; i--) {
                cars[i].update()
            };
            // console.log(p2.vec2.length(player.chassisBody.velocity))
            if(p2.vec2.length(player.chassisBody.velocity) <= 0.05){
                player.chassisBody.backWheel.setBrakeForce(2);
                player.boxShape.collisionGroup = CAR;
                cars.push(player);
                player = new Car(0,0,0.5,1,-1.5,15,0,2,world,container,PLAYER,stage);

            }
            // Render scene
            renderer.render(stage);
        }<commit_msg>added walls<commit_after>var renderer, stage, container, graphics, zoom,
            world, boxShape, boxBody, planeBody, planeShape,chassisBody,player, cars=[],wall=[];

        var carTexture;

        var PLAYER=Math.pow(2,1),
            CAR=Math.pow(2,2),
            WALL=Math.pow(2,3);

        init();

        function Car(x,y,w,h,angle,velX,velY,mass,world,container,collisionGroup,stage){
            this.chassisBody = new p2.Body({
                position: [x,y],
                mass: mass,
                angle: angle,
                velocity: [velX, velY],
            });

            this.boxShape = new p2.Box({ width: w, height: h });
            this.boxShape.collisionGroup = collisionGroup;
            this.boxShape.collisionMask = PLAYER | CAR | WALL
            this.chassisBody.addShape(this.boxShape);
            world.addBody(this.chassisBody);
            // Create the vehicle
            this.vehicle = new p2.TopDownVehicle(this.chassisBody);
            // Add one front wheel and one back wheel - we don't actually need four :)

            this.chassisBody.frontWheel = this.vehicle.addWheel({
                localPosition: [0, 0.5] // front
            });

            this.chassisBody.frontWheel.setSideFriction(200);
            // Back wheel
            this.chassisBody.backWheel = this.vehicle.addWheel({
                localPosition: [0, -0.5] // back
            });
            this.chassisBody.backWheel.setSideFriction(200); // Less side friction on back wheel makes it easier to drift
            this.vehicle.addToWorld(world);

            this.graphics = new PIXI.Graphics();
            this.graphics.beginFill(0xff0000);
            this.texture = carTexture;
            this.sprite = new PIXI.Sprite(this.texture);
            this.graphics.addChild(this.sprite);
            this.graphics.drawRect(-this.boxShape.width/2, -this.boxShape.height/2, this.boxShape.width, this.boxShape.height);
            this.sprite.width = -this.boxShape.width;
            this.sprite.height = -this.boxShape.height;
            this.sprite.position={x:-this.boxShape.width/2, y:this.boxShape.height/2}
            this.sprite.scale.x = -this.sprite.scale.x
            // Add the box to our container
            container.addChild(this.graphics);

            this.update = function(){
                this.graphics.position.x = this.chassisBody.position[0];
                this.graphics.position.y = this.chassisBody.position[1];
                this.graphics.rotation =   this.chassisBody.angle;
            }
        }

        function Wall(x,y,w,h,angle,container,world){
            this.wallBody = new p2.Body({
                position: [x,y],
                mass: 0,
                angle: angle,
            });

            this.boxShape = new p2.Box({ width: w, height: h });
            this.boxShape.collisionGroup = WALL;
            this.boxShape.collisionMask = PLAYER | CAR ;
            this.wallBody.addShape(this.boxShape);
            world.addBody(this.wallBody);
            this.graphics = new PIXI.Graphics();
            this.graphics.beginFill(0xff0000);

            this.graphics.drawRect(-this.boxShape.width/2, -this.boxShape.height/2, this.boxShape.width, this.boxShape.height);

            this.graphics.position.x = this.wallBody.position[0];
            this.graphics.position.y = this.wallBody.position[1];

            container.addChild(this.graphics);

        }

        function init(){

            // Init p2.js
            // Create a dynamic body for the chassis
            world = new p2.World({
                gravity : [0,0]
            });

            zoom = 50;

            // Initialize the stage
            renderer =  PIXI.autoDetectRenderer(800, 600),
            stage = new PIXI.Stage(0xFFFFFF);
            container = new PIXI.Container(),
            PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
            PIXI.loader
                        .add('car', 'assets/car.png')
                        .load(function (loader, resources) {
                            carTexture = resources.car.texture;
                            wall[0] = new Wall(720/zoom,-240/zoom,20/zoom,600/zoom,0,container,world)
                            wall[1] = new Wall(320/zoom,60/zoom,800/zoom,20/zoom,0,container,world)
                            wall[2] = new Wall(320/zoom,-540/zoom,800/zoom,20/zoom,0,container,world)
                            wall[4] = new Wall(-80/zoom,-240/zoom,20/zoom,600/zoom,0,container,world)

                            player = new Car(0,0,0.5,1,-1.5,15,0,2,world,container,PLAYER,stage);
                            animate();
            });
            stage.addChild(container);
            document.body.appendChild(renderer.view);
            // Add transform to the container
            container.position.x =  renderer.width/10; // center at origin
            container.position.y =  renderer.height/10;
            container.scale.x =  zoom;  // zoom in
            container.scale.y = -zoom; // Note: we flip the y axis to make "up" the physics "up"

            world.on("impact",function(evt){
                var bodyA = evt.bodyA,
                bodyB = evt.bodyB;

                if(bodyA.shapes[0].collisionGroup == CAR || bodyA.shapes[0].collisionGroup == PLAYER) {
                    bodyA.frontWheel.setSideFriction(2);
                    bodyA.backWheel.setSideFriction(2);
                }
                if(bodyB.shapes[0].collisionGroup == CAR || bodyB.shapes[0].collisionGroup == PLAYER) {
                    bodyB.frontWheel.setSideFriction(2);
                    bodyB.backWheel.setSideFriction(2);
                }

            });0

            // Draw the box.

            var keys = {
                '37': 0, // left
                '39': 0, // right
                '38': 0, // up
                '40': 0 // down
            };
            var maxSteer = 20000;
            window.addEventListener("keydown",function (evt){
                keys[evt.keyCode] = 1;
                onInputChange();
            });
            window.addEventListener("keyup",function (evt){
                keys[evt.keyCode] = 0;
                onInputChange();
            });
            function onInputChange(){
                // Steer value zero means straight forward. Positive is left and negative right.
                player.chassisBody.frontWheel.steerValue = maxSteer * (keys[37] - keys[39]);
                player.chassisBody.backWheel.setBrakeForce(0);
                if(keys[40]){
                    if(player.chassisBody.backWheel.getSpeed() > 0.1){
                        // Moving forward - add some brake force to slow down
                        player.chassisBody.backWheel.setBrakeForce(2);
                    } else {
                        // Moving backwards - reverse the engine force
                        player.chassisBody.backWheel.setBrakeForce(2);
                    }
                }
            }
        }

        // Animation loop
        function animate(t){
            t = t || 0;
            requestAnimationFrame(animate);

            // Move physics bodies forward in time
            world.step(1/60);

            // Transfer positions of the physics objects to Pixi.js

            player.update();
            for (var i = cars.length - 1; i >= 0; i--) {
                cars[i].update()
            };
            // console.log(p2.vec2.length(player.chassisBody.velocity))
            if(p2.vec2.length(player.chassisBody.velocity) <= 0.05){
                player.chassisBody.backWheel.setBrakeForce(2);
                player.boxShape.collisionGroup = CAR;
                cars.push(player);
                player = new Car(0,0,0.5,1,-1.5,15,0,2,world,container,PLAYER,stage);

            }
            // Render scene
            renderer.render(stage);
        }<|endoftext|>


<commit_before>/*
  html2canvas @VERSION@ <http://html2canvas.hertzen.com>
  Copyright (c) 2011 Niklas von Hertzen. All rights reserved.
  http://www.twitter.com/niklasvh

  Released under MIT License
*/

html2canvas.Generate = {};

html2canvas.Generate.Gradient = function(src, bounds) {
    var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    tmp,
    p0 = 0,
    p1 = 0,
    p2 = 0,
    p3 = 0,
    steps = [],
    position,
    i,
    len,
    lingrad,
    increment,
    p,
    img;

    canvas.width = bounds.width;
    canvas.height = bounds.height;

    function getColors(input) {
        var j = -1,
        color = '',
        chr;

        while( j++ < input.length ) {
            chr = input.charAt( j );
            if (chr === ')') {
                color += chr;
                steps.push( color );
                color = '';
                j+=2;
            } else {
                color += chr;
            }
        }
    }

    if ( tmp = src.match(/-webkit-linear-gradient\((.*)\)/) ) {

        position = tmp[1].split( ",", 1 )[0];
        getColors( tmp[1].substr( position.length + 2 ) );
        position = position.split(' ');

        for (p = 0; p < position.length; p+=1) {

            switch(position[p]) {
                case 'top':
                    p3 = bounds.height;
                    break;

                case 'right':
                    p0 = bounds.width;
                    break;

                case 'bottom':
                    p1 = bounds.height;
                    break;

                case 'left':
                    p2 = bounds.width;
                    break;
            }

        }

    } else if (tmp = src.match(/-webkit-gradient\(linear, (\d+)[%]{0,1} (\d+)[%]{0,1}, (\d+)[%]{0,1} (\d+)[%]{0,1}, from\((.*)\), to\((.*)\)\)/)) {

        p0 = (tmp[1] * bounds.width) / 100;
        p1 = (tmp[2] * bounds.height) / 100;
        p2 = (tmp[3] * bounds.width) / 100;
        p3 = (tmp[4] * bounds.height) / 100;

        steps.push(tmp[5]);
        steps.push(tmp[6]);

    } else if (tmp = src.match(/-moz-linear-gradient\((\d+)[%]{0,1} (\d+)[%]{0,1}, (.*)\)/)) {

        p0 = (tmp[1] * bounds.width) / 100;
        p1 = (tmp[2] * bounds.width) / 100;
        p2 = bounds.width - p0;
        p3 = bounds.height - p1;
        getColors( tmp[3] );

    } else {
        return;
    }

    lingrad = ctx.createLinearGradient( p0, p1, p2, p3 );
    increment = 1 / (steps.length - 1);

    for (i = 0, len = steps.length; i < len; i+=1) {
        lingrad.addColorStop(increment * i, steps[i]);
    }

    ctx.fillStyle = lingrad;

    // draw shapes
    ctx.fillRect(0, 0, bounds.width,bounds.height);

    img = new Image();
    img.src = canvas.toDataURL();

    return img;

}

html2canvas.Generate.ListAlpha = function(number) {
    var tmp = "",
    modulus;

    do {
        modulus = number % 26;
        tmp = String.fromCharCode((modulus) + 64) + tmp;
        number = number / 26;
    }while((number*26) > 26);

    return tmp;
}

html2canvas.Generate.ListRoman = function(number) {
    var romanArray = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"],
    decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
    roman = "",
    v,
    len = romanArray.length;

    if (number <= 0 || number >= 4000) {
        return number;
    }

    for (v=0; v < len; v+=1) {
        while (number >= decimal[v]) {
            number -= decimal[v];
            roman += romanArray[v];
        }
    }

    return roman;

}
<commit_msg>This fixes an exception when trying to parse gradient like: 'rgb(254, 254, 254) 0%, rgb(236, 236, 236) 100%'<commit_after>/*
  html2canvas @VERSION@ <http://html2canvas.hertzen.com>
  Copyright (c) 2011 Niklas von Hertzen. All rights reserved.
  http://www.twitter.com/niklasvh

  Released under MIT License
*/

html2canvas.Generate = {};

html2canvas.Generate.Gradient = function(src, bounds) {
    var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    tmp,
    p0 = 0,
    p1 = 0,
    p2 = 0,
    p3 = 0,
    steps = [],
    position,
    i,
    len,
    lingrad,
    increment,
    p,
    img;

    canvas.width = bounds.width;
    canvas.height = bounds.height;

    function getColors(input) {
        var j = -1,
        color = '',
        chr;

        while( j++ < input.length ) {
            chr = input.charAt( j );
            if (chr === ')') {
                color += chr;
                steps.push( color );
                color = '';
                j+=2;
            } else if (color || isValidColorStartChar(chr)) {
                color += chr;
            }
        }
    }

    function isValidColorStartChar(c) {
    	return c && /[^0-9%,]/.test(c);
    }

    if ( tmp = src.match(/-webkit-linear-gradient\((.*)\)/) ) {

        position = tmp[1].split( ",", 1 )[0];
        getColors( tmp[1].substr( position.length + 2 ) );
        position = position.split(' ');

        for (p = 0; p < position.length; p+=1) {

            switch(position[p]) {
                case 'top':
                    p3 = bounds.height;
                    break;

                case 'right':
                    p0 = bounds.width;
                    break;

                case 'bottom':
                    p1 = bounds.height;
                    break;

                case 'left':
                    p2 = bounds.width;
                    break;
            }

        }

    } else if (tmp = src.match(/-webkit-gradient\(linear, (\d+)[%]{0,1} (\d+)[%]{0,1}, (\d+)[%]{0,1} (\d+)[%]{0,1}, from\((.*)\), to\((.*)\)\)/)) {

        p0 = (tmp[1] * bounds.width) / 100;
        p1 = (tmp[2] * bounds.height) / 100;
        p2 = (tmp[3] * bounds.width) / 100;
        p3 = (tmp[4] * bounds.height) / 100;

        steps.push(tmp[5]);
        steps.push(tmp[6]);

    } else if (tmp = src.match(/-moz-linear-gradient\((\d+)[%]{0,1} (\d+)[%]{0,1}, (.*)\)/)) {

        p0 = (tmp[1] * bounds.width) / 100;
        p1 = (tmp[2] * bounds.width) / 100;
        p2 = bounds.width - p0;
        p3 = bounds.height - p1;
        getColors( tmp[3] );

    } else {
        return;
    }

    lingrad = ctx.createLinearGradient( p0, p1, p2, p3 );
    increment = 1 / (steps.length - 1);

    for (i = 0, len = steps.length; i < len; i+=1) {
        lingrad.addColorStop(increment * i, steps[i]);
    }

    ctx.fillStyle = lingrad;

    // draw shapes
    ctx.fillRect(0, 0, bounds.width,bounds.height);

    img = new Image();
    img.src = canvas.toDataURL();

    return img;

}

html2canvas.Generate.ListAlpha = function(number) {
    var tmp = "",
    modulus;

    do {
        modulus = number % 26;
        tmp = String.fromCharCode((modulus) + 64) + tmp;
        number = number / 26;
    }while((number*26) > 26);

    return tmp;
}

html2canvas.Generate.ListRoman = function(number) {
    var romanArray = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"],
    decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
    roman = "",
    v,
    len = romanArray.length;

    if (number <= 0 || number >= 4000) {
        return number;
    }

    for (v=0; v < len; v+=1) {
        while (number >= decimal[v]) {
            number -= decimal[v];
            roman += romanArray[v];
        }
    }

    return roman;

}
<|endoftext|>


<commit_before>// TODO: fix a bug that the first component is put before the Input component

function clone_array(array){
  return array.map(function(a){return a;});
}

$(function() {
  function refresh(){
    setTimeout(function(){
      var blocks = [];
      var shape = [];
      var global_shape = [1, 1, 1, 1];  // kx, ky, sx, sy at input image
      var model_memory_footprint = 0;
      var variable_memory_footprint = 0;

      $("#header").removeClass("inconsistent");

      $("#network").children().each(function(i, elem){
        var type = $(elem).find(".component-header").text();
        var params = $(elem).find("input").map(function(j, number){
          return parseInt(number.value);
        });
        $(elem).find(".out").remove();
        $(elem).find(".global-shape").remove();
        $(elem).removeClass("inconsistent");

        var valid = true;

        if(type == "Input"){
          var batch = params[0], ch = params[1], h = params[2], w = params[3];
          input_shape = [batch, ch, h, w];
          shape = [batch, ch, h, w];
          variable_memory_footprint += batch * ch * h * w;
        }
        else if(type == "Linear"){
          var batch = shape[0];
          var feature = shape.slice(1).reduce(function(x, y){return x * y;});
          var dim_in = params[0], dim_out = params[1];
          var b = 1;  // bias
          if( feature != dim_in){
            valid = false;
          }
          shape = [batch, dim_out];
          model_memory_footprint += (dim_in + b) * dim_out;
          variable_memory_footprint += batch * dim_out;
        }
        else if(type == "Convolution2D"){
          var batch = shape[0], ch = shape[1], h = shape[2], w = shape[3];
          var ch_in = params[0], ch_out = params[1], kx = params[2];
          var ky = params[3], sx = params[4], sy = params[5];
          var b = 1;  // bias
          if( (w - kx) % sx == 0 && (h - ky) % sy == 0){
            w_new = ((w - kx) / sx) + 1;
            h_new = ((h - ky) / sy) + 1;
          }else{
            valid = false;
          }
          shape = [batch, ch_out, h_new, w_new];
          var gkx = global_shape[0], gky = global_shape[1];
          var gsx = global_shape[2], gsy = global_shape[3];
          gkx += gsx * (kx - 1);
          gky += gsy * (ky - 1);
          gsx *= sx;
          gsy *= sy;
          global_shape = [gkx, gky, gsx, gsy];
          model_memory_footprint += (ch_in * kx * ky + b) * ch_out;
          variable_memory_footprint += batch * ch_out * h_new * w_new;
        }
        else if(type == "Pooling"){
          var batch = shape[0], ch = shape[1], h = shape[2], w = shape[3];
          var px = params[0], py = params[1], sx = params[2], sy = params[3];
          if( (w - px) % sx != 0 || (h - py) % sy != 0){
            valid = false;
          }else{
            w_new = ((w - px) / sx) + 1;
            h_new = ((h - py) / sy) + 1;
          }

          var gkx = global_shape[0], gky = global_shape[1];
          var gsx = global_shape[2], gsy = global_shape[3];
          gkx += gsx * (px - 1);
          gky += gsy * (py - 1);
          gsx *= sx;
          gsy *= sy;
          global_shape = [gkx, gky, gsx, gsy];

          shape = [batch, ch, h_new, w_new];
          variable_memory_footprint += batch * ch * h_new * w_new;
        }
        else if(type == "Element-wise"){
          var batch = shape[0], ch = shape[1], h = shape[2], w = shape[3];
          variable_memory_footprint += batch * ch * h * w;
        }

        elem.shape = clone_array(shape);
        elem.global_shape = clone_array(global_shape);

        // display global shape and output shape
        var out = $("

global shape: " + global_shape +
          "

out: " + shape + "

");
        $(elem).find(".component-content").append(out);

        // display graphical global shape
        if(type != "Linear"){
          var input_h = input_shape[2], input_w = input_shape[3];
          var input_shape_image = $("

",
            {class: "global-shape", height: input_h, width: input_w, css: {
              "background-color":"gray", margin: "2px", border: "1px solid black",
              float:"right", position: "relative"
            }
          });

          var gkx = global_shape[0], gky = global_shape[1];
          var gsx = global_shape[2], gsy = global_shape[3];
          var h = shape[2], w = shape[3];
          var tiles = h < w ? h : w;
          tiles = tiles < 10 ? tiles : 10;
          for(var i=0; i<tiles; ++i){
            var color = i % 2 == 0 ? "black" : "white";
            var top = i * gsy - 1 + "px", left = i * gsx - 1 + "px";
            var global_shape_image = $("

",
              {height: gky, width: gkx, css: {
                border: "1px solid " + color,
                position: "absolute", top: top, left: left
              }
            });
            $(input_shape_image).append(global_shape_image);
          }
          $(elem).append(input_shape_image);
        }

        if(!valid){
          $(elem).addClass("inconsistent");
          $("#header").addClass("inconsistent");
        }
      });

      memory_footprint = variable_memory_footprint + model_memory_footprint;
      memory_footprint *= 4 // bytes of float32
      $("#footprint").val(memory_footprint.toLocaleString());
    }, 1);
  }

  $( "#network" ).sortable({
    handle: ".component-header",
    cancel: ".component-close",
    placeholder: "component-placeholder ui-corner-all",
    tolerance: "pointer",
    items: "div.sortable",
    //cursor: "move",
    stop: function(event, ui){
      refresh();
    }
  });

  $( "#catalog .component" ).draggable({
    handle: ".component-header",
    connectToSortable: "#network",
    helper: "clone",
    stop : function(event, ui) {
      if(!$(ui.helper[0].parentElement).is("#network")){return;}

      // some preparation
      ui.helper.removeAttr("style")
      .removeClass("ui-draggable")
      .find( ".component-header" )
      .prepend( "")
      .find(".component-close" ).click(function() {
        var icon = $( this );
        icon.parent().parent().remove();
        refresh();
      });
      ui.helper.find("input[type=number]").bind("keyup input", function(){
        refresh();
      });

      // set the input size by the output size of the upstream element
      if(ui.helper.hasClass("parametric")){
        var upstream_shape = ui.helper[0].previousElementSibling.shape;
        var type = ui.helper.find(".component-header").text();
        if(type == "Linear"){
          var size = upstream_shape.slice(1).reduce(function(x, y){return x * y;});
          ui.helper.find("input[name=dim-in]").val(size).change();
        }else if(type == "Convolution2D"){
          var size = upstream_shape[1];
          ui.helper.find("input[name=ch-in]").val(size);
          ui.helper.find("input[name=ch-out]").val(size).change();
        }
      }
    }
  });

  $( ".component" )
  .addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
  .find( ".component-header" )
  .addClass( "ui-widget-header ui-corner-all" );

  $("#network input[type=number]").bind("keyup input", function(){
    refresh();
  });

  refresh();
});
<commit_msg>Use appropreate term<commit_after>// TODO: fix a bug that the first component is put before the Input component

function clone_array(array){
  return array.map(function(a){return a;});
}

$(function() {
  function refresh(){
    setTimeout(function(){
      var blocks = [];
      var shape = [];
      var receptive_field = [1, 1, 1, 1];  // kx, ky, sx, sy at input image
      var model_memory_footprint = 0;
      var variable_memory_footprint = 0;

      $("#header").removeClass("inconsistent");

      $("#network").children().each(function(i, elem){
        var type = $(elem).find(".component-header").text();
        var params = $(elem).find("input").map(function(j, number){
          return parseInt(number.value);
        });
        $(elem).find(".out").remove();
        $(elem).find(".receptive-field").remove();
        $(elem).removeClass("inconsistent");

        var valid = true;

        if(type == "Input"){
          var batch = params[0], ch = params[1], h = params[2], w = params[3];
          input_shape = [batch, ch, h, w];
          shape = [batch, ch, h, w];
          variable_memory_footprint += batch * ch * h * w;
        }
        else if(type == "Linear"){
          var batch = shape[0];
          var feature = shape.slice(1).reduce(function(x, y){return x * y;});
          var dim_in = params[0], dim_out = params[1];
          var b = 1;  // bias
          if( feature != dim_in){
            valid = false;
          }
          shape = [batch, dim_out];
          model_memory_footprint += (dim_in + b) * dim_out;
          variable_memory_footprint += batch * dim_out;
        }
        else if(type == "Convolution2D"){
          var batch = shape[0], ch = shape[1], h = shape[2], w = shape[3];
          var ch_in = params[0], ch_out = params[1], kx = params[2];
          var ky = params[3], sx = params[4], sy = params[5];
          var b = 1;  // bias
          if( (w - kx) % sx == 0 && (h - ky) % sy == 0){
            w_new = ((w - kx) / sx) + 1;
            h_new = ((h - ky) / sy) + 1;
          }else{
            valid = false;
          }
          shape = [batch, ch_out, h_new, w_new];
          var gkx = receptive_field[0], gky = receptive_field[1];
          var gsx = receptive_field[2], gsy = receptive_field[3];
          gkx += gsx * (kx - 1);
          gky += gsy * (ky - 1);
          gsx *= sx;
          gsy *= sy;
          receptive_field = [gkx, gky, gsx, gsy];
          model_memory_footprint += (ch_in * kx * ky + b) * ch_out;
          variable_memory_footprint += batch * ch_out * h_new * w_new;
        }
        else if(type == "Pooling"){
          var batch = shape[0], ch = shape[1], h = shape[2], w = shape[3];
          var px = params[0], py = params[1], sx = params[2], sy = params[3];
          if( (w - px) % sx != 0 || (h - py) % sy != 0){
            valid = false;
          }else{
            w_new = ((w - px) / sx) + 1;
            h_new = ((h - py) / sy) + 1;
          }

          var gkx = receptive_field[0], gky = receptive_field[1];
          var gsx = receptive_field[2], gsy = receptive_field[3];
          gkx += gsx * (px - 1);
          gky += gsy * (py - 1);
          gsx *= sx;
          gsy *= sy;
          receptive_field = [gkx, gky, gsx, gsy];

          shape = [batch, ch, h_new, w_new];
          variable_memory_footprint += batch * ch * h_new * w_new;
        }
        else if(type == "Element-wise"){
          var batch = shape[0], ch = shape[1], h = shape[2], w = shape[3];
          variable_memory_footprint += batch * ch * h * w;
        }

        elem.shape = clone_array(shape);
        elem.receptive_field = clone_array(receptive_field);

        // display receptive field and output shape
        var out = $("

receptive field: " +
          receptive_field + "

out: " + shape + "

");
        $(elem).find(".component-content").append(out);

        // display graphical receptive field
        if(type != "Linear"){
          var input_h = input_shape[2], input_w = input_shape[3];
          var input_shape_image = $("

",
            {class: "receptive-field", height: input_h, width: input_w, css: {
              "background-color":"gray", margin: "2px", border: "1px solid black",
              float:"right", position: "relative"
            }
          });

          var gkx = receptive_field[0], gky = receptive_field[1];
          var gsx = receptive_field[2], gsy = receptive_field[3];
          var h = shape[2], w = shape[3];
          var tiles = h < w ? h : w;
          tiles = tiles < 10 ? tiles : 10;
          for(var i=0; i<tiles; ++i){
            var color = i % 2 == 0 ? "black" : "white";
            var top = i * gsy - 1 + "px", left = i * gsx - 1 + "px";
            var receptive_field_image = $("

",
              {height: gky, width: gkx, css: {
                border: "1px solid " + color,
                position: "absolute", top: top, left: left
              }
            });
            $(input_shape_image).append(receptive_field_image);
          }
          $(elem).append(input_shape_image);
        }

        if(!valid){
          $(elem).addClass("inconsistent");
          $("#header").addClass("inconsistent");
        }
      });

      memory_footprint = variable_memory_footprint + model_memory_footprint;
      memory_footprint *= 4 // bytes of float32
      $("#footprint").val(memory_footprint.toLocaleString());
    }, 1);
  }

  $( "#network" ).sortable({
    handle: ".component-header",
    cancel: ".component-close",
    placeholder: "component-placeholder ui-corner-all",
    tolerance: "pointer",
    items: "div.sortable",
    //cursor: "move",
    stop: function(event, ui){
      refresh();
    }
  });

  $( "#catalog .component" ).draggable({
    handle: ".component-header",
    connectToSortable: "#network",
    helper: "clone",
    stop : function(event, ui) {
      if(!$(ui.helper[0].parentElement).is("#network")){return;}

      // some preparation
      ui.helper.removeAttr("style")
      .removeClass("ui-draggable")
      .find( ".component-header" )
      .prepend( "")
      .find(".component-close" ).click(function() {
        var icon = $( this );
        icon.parent().parent().remove();
        refresh();
      });
      ui.helper.find("input[type=number]").bind("keyup input", function(){
        refresh();
      });

      // set the input size by the output size of the upstream element
      if(ui.helper.hasClass("parametric")){
        var upstream_shape = ui.helper[0].previousElementSibling.shape;
        var type = ui.helper.find(".component-header").text();
        if(type == "Linear"){
          var size = upstream_shape.slice(1).reduce(function(x, y){return x * y;});
          ui.helper.find("input[name=dim-in]").val(size).change();
        }else if(type == "Convolution2D"){
          var size = upstream_shape[1];
          ui.helper.find("input[name=ch-in]").val(size);
          ui.helper.find("input[name=ch-out]").val(size).change();
        }
      }
    }
  });

  $( ".component" )
  .addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
  .find( ".component-header" )
  .addClass( "ui-widget-header ui-corner-all" );

  $("#network input[type=number]").bind("keyup input", function(){
    refresh();
  });

  refresh();
});
<|endoftext|>


<commit_before>/* This script imports and utilizes lightbeamData.json to make a prototype Lightbeam visualization application | see: https://github.com/mozilla/lightbeam/issues/710 for more information.*/

function lightbeamVis() {

	let visitedSites = {
		'google.com': {},
		'amazon.com': {},
		'facebook.com': {},
		'youtube.com': {},
	};

	let thirdPartySpan = document.getElementById("third-party-site");
	let thirdPartyAboutSpan = document.getElementById("third-party-site-about");
	let visitedSiteSpan = document.getElementById("visited-site");
	let dataSentSpan = document.getElementById('data-sent');
	let prevPathElement;
	let sidePanel = document.getElementById('side-panel');

		// get <path> element from DOM based on title attribute
	let pathElements = [];
	let pathSVGElements = document.getElementsByClassName('site');
	for (let k = 0; k < pathSVGElements.length; k++) {
		pathElements.push(pathSVGElements[k].getElementsByTagName('path'));
	}
	//convert array of HTML collection objects into a single array of path elements
	pathElements = pathElements.reduce(function(a, b) {return [...a, ...b];
		}, []);

	// add click event to each third party pie section (pathElement)
	for (let l = 0; l < pathElements.length; l++) {
		pathElements[l].addEventListener('click', function() {
				updateSideBar(pathElements[l]);
			}
		);
	}

	/* Back to top link resets scroll position */
	const backToTop = document.getElementById('back-to-top');
	backToTop.onclick = scrollToTop;

	function scrollToTop() {
		window.scrollTo(0,0);
	}

/* --- Deselect third party pie slice on clicking away ---*/
	document.body.addEventListener('click', deselectSlice, true);

	function deselectSlice(e) {
		if (e.target.id.indexOf('chart') === -1) {
			for (let m = 0; m < pathElements.length; m++) {
				pathElements[m].classList.remove('active');
			}
		}
	}

	let closeButton = document.getElementById('close');
	closeButton.onclick = closeSideBar;

	function closeSideBar() {
		sidePanel.classList.add('hidden');
	}

	/* -------- LOAD DATA ---------- */

	loadJSON();

	function loadJSON() {
		var xobj = new XMLHttpRequest();
	  xobj.overrideMimeType("application/json");
	  xobj.open('GET', 'lightbeamData.json', true);
	  xobj.onreadystatechange = function () {
	        if (xobj.readyState == 4 && xobj.status == "200") {
	          init(xobj.responseText);
	        }
	  };
	  xobj.send(null);
	}

	function init(response) {

		// Parse JSON string into object
		var data = JSON.parse(response);

		// populate visitedSites from JSON data
		// each element in each array is a unique third-party site linked to by the visited site key.
		for (let currentSite in visitedSites) {
			let dataSent = 0;
			for (let j = 0; j < data.length; j++) {
				// source website is index 0 for each ith array in data
				let source = data[j][0];
				// target website is index 1 for each ith array in data
				let target = data[j][1];
				// check if target has a subdomain and remove it e.g. remove x in 'x.cloudfront.net'.
				let arrayOfStrings = target.split('.');
				if (arrayOfStrings.length > 2) {
					arrayOfStrings.splice(0, 1);
					target = arrayOfStrings.join('.');
				}
				// if there's a third-party source
				if (source === currentSite && target !== currentSite) {
					// if third-party site is not yet captured
					if (!visitedSites[currentSite].hasOwnProperty(target)) {
						dataSent += 3;
						visitedSites[currentSite][target] = dataSent;
					}
				}
			}
		}

		console.log('Third party sites by visited site: ', visitedSites);
	}

	function updateSideBar(pathElement) {
		if (sidePanel.classList.contains('hidden')) {
			sidePanel.classList.remove('hidden');
		}
		if (!prevPathElement) {
			prevPathElement = pathElement;
		} else if (prevPathElement !== pathElement) {
			prevPathElement.classList.remove('active');
			prevPathElement = pathElement;
		}
		// update third party value in side panel
		let thirdPartySite = pathElement.textContent;
			thirdPartySpan.innerText = thirdPartySite;
		thirdPartyAboutSpan.innerText = thirdPartySite;
		// get parentElement to pathElement (<svg>)
		let parentSVG = pathElement.nearestViewportElement;
		// then get siblingElement to parentElement (<a>)
		let siblingElement = parentSVG.nextElementSibling;
		// then get the value of the title attribute, which corresponds to the visited site name string
		let visitedSite = siblingElement.getAttribute('title');
		visitedSiteSpan.innerText = visitedSite;
		// update data sent value in side panel
		dataSentSpan.innerText = visitedSites[visitedSite][thirdPartySite];
		pathElement.classList.add('active');
		// on larger screen widths, this has no effect
		// for smaller screen widths, this scrolls to the bottom of the page where the side panel is located
		window.scrollTo(0, 10000);
	}
}

window.onload = lightbeamVis;<commit_msg>Add scroll to top on sidebar close<commit_after>/* This script imports and utilizes lightbeamData.json to make a prototype Lightbeam visualization application | see: https://github.com/mozilla/lightbeam/issues/710 for more information.*/

function lightbeamVis() {

	let visitedSites = {
		'google.com': {},
		'amazon.com': {},
		'facebook.com': {},
		'youtube.com': {},
	};

	let thirdPartySpan = document.getElementById("third-party-site");
	let thirdPartyAboutSpan = document.getElementById("third-party-site-about");
	let visitedSiteSpan = document.getElementById("visited-site");
	let dataSentSpan = document.getElementById('data-sent');
	let prevPathElement;
	let sidePanel = document.getElementById('side-panel');

		// get <path> element from DOM based on title attribute
	let pathElements = [];
	let pathSVGElements = document.getElementsByClassName('site');
	for (let k = 0; k < pathSVGElements.length; k++) {
		pathElements.push(pathSVGElements[k].getElementsByTagName('path'));
	}
	//convert array of HTML collection objects into a single array of path elements
	pathElements = pathElements.reduce(function(a, b) {return [...a, ...b];
		}, []);

	// add click event to each third party pie section (pathElement)
	for (let l = 0; l < pathElements.length; l++) {
		pathElements[l].addEventListener('click', function() {
				updateSideBar(pathElements[l]);
			}
		);
	}

	/* Back to top link resets scroll position */
	const backToTop = document.getElementById('back-to-top');
	backToTop.onclick = scrollToTop;

	function scrollToTop() {
		window.scrollTo(0,0);
	}

/* --- Deselect third party pie slice on clicking away ---*/
	document.body.addEventListener('click', deselectSlice, true);

	function deselectSlice(e) {
		if (e.target.id.indexOf('chart') === -1) {
			for (let m = 0; m < pathElements.length; m++) {
				pathElements[m].classList.remove('active');
			}
		}
	}

	let closeButton = document.getElementById('close');
	closeButton.onclick = closeSideBar;

	function closeSideBar() {
		sidePanel.classList.add('hidden');
		scrollToTop();
	}

	/* -------- LOAD DATA ---------- */

	loadJSON();

	function loadJSON() {
		var xobj = new XMLHttpRequest();
	  xobj.overrideMimeType("application/json");
	  xobj.open('GET', 'lightbeamData.json', true);
	  xobj.onreadystatechange = function () {
	        if (xobj.readyState == 4 && xobj.status == "200") {
	          init(xobj.responseText);
	        }
	  };
	  xobj.send(null);
	}

	function init(response) {

		// Parse JSON string into object
		var data = JSON.parse(response);

		// populate visitedSites from JSON data
		// each element in each array is a unique third-party site linked to by the visited site key.
		for (let currentSite in visitedSites) {
			let dataSent = 0;
			for (let j = 0; j < data.length; j++) {
				// source website is index 0 for each ith array in data
				let source = data[j][0];
				// target website is index 1 for each ith array in data
				let target = data[j][1];
				// check if target has a subdomain and remove it e.g. remove x in 'x.cloudfront.net'.
				let arrayOfStrings = target.split('.');
				if (arrayOfStrings.length > 2) {
					arrayOfStrings.splice(0, 1);
					target = arrayOfStrings.join('.');
				}
				// if there's a third-party source
				if (source === currentSite && target !== currentSite) {
					// if third-party site is not yet captured
					if (!visitedSites[currentSite].hasOwnProperty(target)) {
						dataSent += 3;
						visitedSites[currentSite][target] = dataSent;
					}
				}
			}
		}

		console.log('Third party sites by visited site: ', visitedSites);
	}

	function updateSideBar(pathElement) {
		if (sidePanel.classList.contains('hidden')) {
			sidePanel.classList.remove('hidden');
		}
		if (!prevPathElement) {
			prevPathElement = pathElement;
		} else if (prevPathElement !== pathElement) {
			prevPathElement.classList.remove('active');
			prevPathElement = pathElement;
		}
		// update third party value in side panel
		let thirdPartySite = pathElement.textContent;
			thirdPartySpan.innerText = thirdPartySite;
		thirdPartyAboutSpan.innerText = thirdPartySite;
		// get parentElement to pathElement (<svg>)
		let parentSVG = pathElement.nearestViewportElement;
		// then get siblingElement to parentElement (<a>)
		let siblingElement = parentSVG.nextElementSibling;
		// then get the value of the title attribute, which corresponds to the visited site name string
		let visitedSite = siblingElement.getAttribute('title');
		visitedSiteSpan.innerText = visitedSite;
		// update data sent value in side panel
		dataSentSpan.innerText = visitedSites[visitedSite][thirdPartySite];
		pathElement.classList.add('active');
		// on larger screen widths, this has no effect
		// for smaller screen widths, this scrolls to the bottom of the page where the side panel is located
		window.scrollTo(0, 10000);
	}
}

window.onload = lightbeamVis;<|endoftext|>


<commit_before>function fun1() {
    var rtl = document.getElementById('rtl').value;
    var rtr = document.getElementById('rtr').value;
    var rbl = document.getElementById('rbl').value;
    var rbr = document.getElementById('rbr').value;
    var ttl = document.getElementById('ttl');
    var ttr = document.getElementById('ttr');
    var tbr = document.getElementById('tbr');
    var tbl = document.getElementById('tbl');

    var block = document.getElementById('block');

    ttl.value = rtl;
    ttr.value = rtr;
    tbr.value = rbr;
    tbl.value = rbl;
    block.style.borderRadius = rtl + 'px ' + rtr + 'px ' + rbr + 'px ' + rbl + 'px ';
}

function move() {
    var elem = document.getElementById("myBar");
    var width = 10;
    var id = setInterval(frame, 10);

    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("label").innerHTML = width * 1 + '%';
        }
    }
}

function myMove() {
    var elem = document.getElementById("myAnimation");
    var pos = 0;
    var id = setInterval(frame, 10);

    function frame() {
        if (pos == 150) {
            clearInterval(id);
        } else {
            pos++;
            elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
        }
    }
}

function moneyConverter(valNum) {
    document.getElementById("outputrub").innerHTML = valNum * 60;
}

function plus() {
    var num1,num2,resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 + num2;
    document.getElementById('out').innerHTML=result;
}

function minus() {
    var num1,num2,result;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 - num2;
    document.getElementById('out').innerHTML=result;
}
<commit_msg>функция умножения<commit_after>function fun1() {
    var rtl = document.getElementById('rtl').value;
    var rtr = document.getElementById('rtr').value;
    var rbl = document.getElementById('rbl').value;
    var rbr = document.getElementById('rbr').value;
    var ttl = document.getElementById('ttl');
    var ttr = document.getElementById('ttr');
    var tbr = document.getElementById('tbr');
    var tbl = document.getElementById('tbl');

    var block = document.getElementById('block');

    ttl.value = rtl;
    ttr.value = rtr;
    tbr.value = rbr;
    tbl.value = rbl;
    block.style.borderRadius = rtl + 'px ' + rtr + 'px ' + rbr + 'px ' + rbl + 'px ';
}

function move() {
    var elem = document.getElementById("myBar");
    var width = 10;
    var id = setInterval(frame, 10);

    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("label").innerHTML = width * 1 + '%';
        }
    }
}

function myMove() {
    var elem = document.getElementById("myAnimation");
    var pos = 0;
    var id = setInterval(frame, 10);

    function frame() {
        if (pos == 150) {
            clearInterval(id);
        } else {
            pos++;
            elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
        }
    }
}

function moneyConverter(valNum) {
    document.getElementById("outputrub").innerHTML = valNum * 60;
}

function plus() {
    var num1,num2,resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 + num2;
    document.getElementById('out').innerHTML=result;
}

function minus() {
    var num1,num2,result;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 - num2;
    document.getElementById('out').innerHTML=result;
}
function um() {
    var num1,num2,result;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 * num2;
    document.getElementById('out').innerHTML=result;
}
<|endoftext|>


<commit_before>var map;
var insert_div = function(){
  var div = $('
')[0];
  $('#chart_view').append(div);
  return div;
};

var build_health_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'Hospitals & Level II, III, IV Health Centers'],
    ['2007',  numberify(region["health_2007"])],
    ['2009',  numberify(region["health_2009"])],
    ['2010',  numberify(region["health_2010"])]
  ]);
};

var build_population_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'Population Number (absolute)'],
    ['1991',  numberify(region["population_1991"])],
    ['2002',  numberify(region["population_2002"])],
    ['2011',  numberify(region["population_projected_2011"])],
    ['2011',  numberify(region["population_2012"])]
  ]);
};

var build_primary_education_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'gross intake', 'net intake', 'gross enrollment', 'net enrolment'],
    ['2009',  numberify(region["primary_education_gross_intake_2009"]), numberify(region["primary_education_net_intake_2009"]),numberify(region["primary_education_gross_enrolment_2009"]), numberify(region["primary_education_net_enrolment_2009"]) ],
    ['2010',  numberify(region["primary_education_gross_intake_2010"]), numberify(region["primary_education_net_intake_2010"]),numberify(region["primary_education_gross_enrolment_2010"]), numberify(region["primary_education_net_enrolment_2010"]) ]
  ]);
};

var build_secondary_education_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'gross intake', 'net intake', 'gross enrollment', 'net enrolment'],
    ['2009',  numberify(region["secondary_education_gross_intake_2009"]), numberify(region["secondary_education_net_intake_2009"]),numberify(region["secondary_education_gross_enrolment_2009"]), numberify(region["secondary_education_net_enrolment_2009"]) ],
    ['2010',  numberify(region["secondary_education_gross_intake_2010"]), numberify(region["secondary_education_net_intake_2010"]),numberify(region["secondary_education_gross_enrolment_2010"]), numberify(region["secondary_education_net_enrolment_2010"]) ]
  ]);
};

var build_land_usage_data = function(region){
  return google.visualization.arrayToDataTable([
    ["Name", "Km"],
    ["Urbanised Areas" , numberify(region["urbanised_areas"])],
    ["Bushlands" , numberify(region["bushlands"])],
    ["Commercial Farmlands (cattle)" , numberify(region["commercial_farmlands"])],
    ["Cultivated Lands (farming)" , numberify(region["cultivated_lands"])],
    ["GrassLands" , numberify(region["grasslands"])],
    ["Impediments (collapsed terrain, landslides etc)" , numberify(region["impediments"])],
    ["Plantations" , numberify(region["plantations"])],
    ["Plantations Softwoods" , numberify(region["plantations_softwoods"])],
    ["Depleted Tropical Forest" , numberify(region["depleted_tropical_forest"])],
    ["Tropical Forest" , numberify(region["tropical_forest"])],
    ["Water Bodies" , numberify(region["water_bodies"])],
    ["Wetlands" , numberify(region["wetlands"])],
    ["Woodlands" , numberify(region["woodlands"])]
  ]);
};

var build_health_options = function(region){
  return {
    title: "Amount of Health Centers and Hospitals for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Amount of Health Centers and Hospitals', minValue: 0}
  };
};

var build_population_options = function(region){
  return {
    title: "Census Population for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Population', minValue: 0}
  };
};

var build_primary_education_options = function(region){
  return {
    title: "Primary Education for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Number of people', minValue: 0}
  };
};

var build_secondary_education_options = function(region){
  return {
    title: "Secondary Education for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Number of people', minValue: 0}
  };
};

var build_land_usage_options = function(region){
  return {
    title: "Land Usage for ugandan region " + region["region_district"]
  };
};

var add_health = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_health_data(region), build_health_options(region));
};

var add_population = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_population_data(region), build_population_options(region));
};

var add_primary_education = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_primary_education_data(region), build_primary_education_options(region));
};
var add_secondary_education = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_secondary_education_data(region), build_secondary_education_options(region));
};
var add_land_usage = function(region){
  new google.visualization.Table(insert_div()).draw(build_land_usage_data(region), build_land_usage_options(region));
};

var build_chart = function(region){
  $('#chart_view').html("");
  add_health(region);
  add_population(region);
  add_primary_education(region);
  add_secondary_education(region);
  add_land_usage(region);
};

var setup_map = function(){
  var myLatLng = new google.maps.LatLng( 0.398056, 33.478056 );
  var myOptions = {
      zoom: 6,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map( document.getElementById( 'map' ), myOptions );
};

var start = function() {
  setup_map();
  $.getJSON('/health.json', function(regions){
    regions.forEach(build_marker);
  });
  $.getJSON('/iati.json', function(projects){
    projects.forEach(build_iati_marker);
  });
};

var build_link = function(region){
  var link  = $('' + region["region_district"] + '');
  $('#links').append(link);
  link.click(function(event){
    event.preventDefault();
    build_chart(region);
  });
};

var build_iati_link = function(project){
  var link  = $('' + project["title"] + '');
  $('#links').append(link);
  link.click(function(event){
    event.preventDefault();
    build_iati_chart(project);
  });
};

var decide_colour = function(start_year_id, end_year_id, region){
  if(parseInt(region[start_year_id]) >= parseInt(region[end_year_id])){
    return '#ff0000';
  }else{
    return '#00ff00';
  }
};

var build_iati_chart = function(project){
  console.log('project', project);
};

var numberify = function(string){
  return parseInt(string.split(",").join(""));
};

var decide_radius = function(region){
  var ratio = numberify(region["population_1991"]) / numberify(region["population_2012"]);
  return ratio * 40000;
};

var get_url_vars = function()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    if (vars.length == 1){
      return {};
    }else{
      return vars;
    }
};

var build_marker = function(region){
  var args = get_url_vars();
  var start_year_id = args["start_year_id"] || "health_2007";
  var end_year_id   = args["end_year_id"]   || "health_2010";
  var latlng = new google.maps.LatLng( region["lat"], region["lng"] );
  var params = {
      strokeColor: '#FF0000',
      strokeOpacity: 0,
      strokeWeight: 2,
      fillColor: decide_colour(start_year_id, end_year_id, region),
      fillOpacity: 0.01,
      map: map,
      center: latlng,
      radius: decide_radius(region)
  };
  var circle = new google.maps.Circle(params);
  google.maps.event.addListener(circle, 'click', function() {
    build_chart(region);
  });
};

var build_iati_marker = function(project){
  if(project.position){
    var lat = project.position.split(" ")[0];
    var lng = project.position.split(" ")[1];
    var latlng = new google.maps.LatLng( lat, lng );
    var params = {
      strokeColor: '#FFFF00',
      strokeOpacity: 0,
      strokeWeight: 2,
      fillColor: '#FFFF00',
      fillOpacity: 0.35,
      map: map,
      center: latlng,
      radius: 10000
    };
    var circle = new google.maps.Circle(params);
  }
};

google.load("visualization", "1", {packages:["corechart", "geochart", "table"]});
google.setOnLoadCallback(start);<commit_msg>idiot<commit_after>var map;
var insert_div = function(){
  var div = $('
')[0];
  $('#chart_view').append(div);
  return div;
};

var build_health_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'Hospitals & Level II, III, IV Health Centers'],
    ['2007',  numberify(region["health_2007"])],
    ['2009',  numberify(region["health_2009"])],
    ['2010',  numberify(region["health_2010"])]
  ]);
};

var build_population_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'Population Number (absolute)'],
    ['1991',  numberify(region["population_1991"])],
    ['2002',  numberify(region["population_2002"])],
    ['2011',  numberify(region["population_projected_2011"])],
    ['2011',  numberify(region["population_2012"])]
  ]);
};

var build_primary_education_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'gross intake', 'net intake', 'gross enrollment', 'net enrolment'],
    ['2009',  numberify(region["primary_education_gross_intake_2009"]), numberify(region["primary_education_net_intake_2009"]),numberify(region["primary_education_gross_enrolment_2009"]), numberify(region["primary_education_net_enrolment_2009"]) ],
    ['2010',  numberify(region["primary_education_gross_intake_2010"]), numberify(region["primary_education_net_intake_2010"]),numberify(region["primary_education_gross_enrolment_2010"]), numberify(region["primary_education_net_enrolment_2010"]) ]
  ]);
};

var build_secondary_education_data = function(region){
  return google.visualization.arrayToDataTable([
    ['Year', 'gross intake', 'net intake', 'gross enrollment', 'net enrolment'],
    ['2009',  numberify(region["secondary_education_gross_intake_2009"]), numberify(region["secondary_education_net_intake_2009"]),numberify(region["secondary_education_gross_enrolment_2009"]), numberify(region["secondary_education_net_enrolment_2009"]) ],
    ['2010',  numberify(region["secondary_education_gross_intake_2010"]), numberify(region["secondary_education_net_intake_2010"]),numberify(region["secondary_education_gross_enrolment_2010"]), numberify(region["secondary_education_net_enrolment_2010"]) ]
  ]);
};

var build_land_usage_data = function(region){
  return google.visualization.arrayToDataTable([
    ["Name", "Km"],
    ["Urbanised Areas" , numberify(region["urbanised_areas"])],
    ["Bushlands" , numberify(region["bushlands"])],
    ["Commercial Farmlands (cattle)" , numberify(region["commercial_farmlands"])],
    ["Cultivated Lands (farming)" , numberify(region["cultivated_lands"])],
    ["GrassLands" , numberify(region["grasslands"])],
    ["Impediments (collapsed terrain, landslides etc)" , numberify(region["impediments"])],
    ["Plantations" , numberify(region["plantations"])],
    ["Plantations Softwoods" , numberify(region["plantations_softwoods"])],
    ["Depleted Tropical Forest" , numberify(region["depleted_tropical_forest"])],
    ["Tropical Forest" , numberify(region["tropical_forest"])],
    ["Water Bodies" , numberify(region["water_bodies"])],
    ["Wetlands" , numberify(region["wetlands"])],
    ["Woodlands" , numberify(region["woodlands"])]
  ]);
};

var build_health_options = function(region){
  return {
    title: "Amount of Health Centers and Hospitals for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Amount of Health Centers and Hospitals', minValue: 0}
  };
};

var build_population_options = function(region){
  return {
    title: "Census Population for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Population', minValue: 0}
  };
};

var build_primary_education_options = function(region){
  return {
    title: "Primary Education for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Number of people', minValue: 0}
  };
};

var build_secondary_education_options = function(region){
  return {
    title: "Secondary Education for ugandan region " + region["region_district"],
    hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    vAxis: {title: 'Number of people', minValue: 0}
  };
};

var build_land_usage_options = function(region){
  return {
    title: "Land Usage for ugandan region " + region["region_district"]
  };
};

var add_health = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_health_data(region), build_health_options(region));
};

var add_population = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_population_data(region), build_population_options(region));
};

var add_primary_education = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_primary_education_data(region), build_primary_education_options(region));
};
var add_secondary_education = function(region){
  new google.visualization.LineChart(insert_div()).draw(build_secondary_education_data(region), build_secondary_education_options(region));
};
var add_land_usage = function(region){
  new google.visualization.Table(insert_div()).draw(build_land_usage_data(region), build_land_usage_options(region));
};

var build_chart = function(region){
  $('#chart_view').html("");
  add_health(region);
  add_population(region);
  add_primary_education(region);
  add_secondary_education(region);
  add_land_usage(region);
};

var setup_map = function(){
  var myLatLng = new google.maps.LatLng( 0.398056, 33.478056 );
  var myOptions = {
      zoom: 6,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map( document.getElementById( 'map' ), myOptions );
};

var start = function() {
  setup_map();
  $.getJSON('/health.json', function(regions){
    regions.forEach(build_marker);
  });
  $.getJSON('/iati.json', function(projects){
    projects.forEach(build_iati_marker);
  });
};

var build_link = function(region){
  var link  = $('' + region["region_district"] + '');
  $('#links').append(link);
  link.click(function(event){
    event.preventDefault();
    build_chart(region);
  });
};

var build_iati_link = function(project){
  var link  = $('' + project["title"] + '');
  $('#links').append(link);
  link.click(function(event){
    event.preventDefault();
    build_iati_chart(project);
  });
};

var decide_colour = function(start_year_id, end_year_id, region){
  if(parseInt(region[start_year_id]) >= parseInt(region[end_year_id])){
    return '#ff0000';
  }else{
    return '#00ff00';
  }
};

var build_iati_chart = function(project){
  console.log('project', project);
};

var numberify = function(string){
  return parseInt(string.split(",").join(""));
};

var decide_radius = function(region){
  var ratio = numberify(region["population_1991"]) / numberify(region["population_2012"]);
  return ratio * 40000;
};

var get_url_vars = function()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    if (vars.length == 1){
      return {};
    }else{
      return vars;
    }
};

var build_marker = function(region){
  var args = get_url_vars();
  var start_year_id = args["start_year_id"] || "health_2007";
  var end_year_id   = args["end_year_id"]   || "health_2010";
  var latlng = new google.maps.LatLng( region["lat"], region["lng"] );
  var params = {
      strokeColor: '#FF0000',
      strokeOpacity: 0,
      strokeWeight: 2,
      fillColor: decide_colour(start_year_id, end_year_id, region),
      fillOpacity: 0.35,
      map: map,
      center: latlng,
      radius: decide_radius(region)
  };
  var circle = new google.maps.Circle(params);

  google.maps.event.addListener(circle, 'click', function() {
    build_chart(region);
  });
};

var build_iati_marker = function(project){
  if(project.position){
    var lat = project.position.split(" ")[0];
    var lng = project.position.split(" ")[1];
    var latlng = new google.maps.LatLng( lat, lng );
    var params = {
      strokeColor: '#FFFF00',
      strokeOpacity: 0,
      strokeWeight: 2,
      fillColor: '#FFFF00',
      fillOpacity: 0.10,
      map: map,
      center: latlng,
      radius: 10000
    };
    var circle = new google.maps.Circle(params);
  }
};

google.load("visualization", "1", {packages:["corechart", "geochart", "table"]});
google.setOnLoadCallback(start);<|endoftext|>


<commit_before>function hide(id){
	id.style.display = "none";
}
<commit_msg>Update script.js<commit_after>function makeBox(id){
	var x = Math.random();
	x = x * 5000;
	setTimeout(function(){ document.getElementById("box").style.display = "block";}, x);
}

document.getElementById("box").onclick=function(){
	this.style.display="none";
	makeBox();
}

makeBox();
<|endoftext|>


<commit_before>'use strict';
/* global SharedUtils, evt */

window.SmartBanner = (function(win) {

  // Extend from the HTMLElement prototype
  var proto = evt(Object.create(HTMLElement.prototype));

  proto.createdCallback = function() {
    this.style.width = '0';
    this.classList.add('closed');
    this.addEventListener('transitionend', this);
  };

  proto.calculateChildWidth = function() {
    var child = this.firstElementChild;
    var childWidth = 0;
    var style;
    while(child) {
      style = window.getComputedStyle(child);
      childWidth += child.offsetWidth + parseInt(style.marginLeft, 10)
                                      + parseInt(style.marginRight, 10);
      child = child.nextElementSibling;
    }
    return childWidth;
  };

  proto.fireEvent = function(event, detail) {
    var evtObject = new CustomEvent(event, {
                                      bubbles: false,
                                      detail: detail || this
                                    });
    this.dispatchEvent(evtObject);
    this.fire(event, detail);
  };

  proto.handleEvent = function(evt) {
    var self = this;
    switch(evt.type) {
      // Like System app, the transition is our state machine.
      case 'transitionend':
        // We only process 'background-color' because all states have this
        // change.
        if ((evt.propertyName !== 'background-color' &&
             evt.propertyName !== 'width') ||
            evt.target !== this) {
          break;
        }

        if (this.classList.contains('opening')) {
          this.classList.remove('opening');
          // final state: opened
          this.fireEvent('opened');
        } else if (this.classList.contains('closing')) {
          this.classList.remove('closing');
          this.classList.add('closed');
          // final state: closed
          this.fireEvent('closed');
        }
        break;
    }
  };

  proto.focus = proto.open = function() {
    this.fireEvent('will-open');
    // If we get focus when we closing the group, we need to cancel the closing
    // state.
    this.classList.remove('closed');
    this.classList.remove('closing');
    this.classList.add('opening');
    // change to opening
    this.style.width = this.calculateChildWidth() + 'px';
  };

  proto.blur = proto.close = function() {
    this.fireEvent('will-close');
    // We may call close at mid state, we need to reset all of them and go to
    // closing state
    this.classList.remove('opening');
    this.classList.add('closing');
    this.style.width = '0';
  };

  // Register and return the constructor
  return document.registerElement('smart-banner', { prototype: proto });
})(window);
<commit_msg>Bug 1123192 - Fix jshint failures in tv shared<commit_after>'use strict';
/* global evt */

window.SmartBanner = (function(win) {

  // Extend from the HTMLElement prototype
  var proto = evt(Object.create(HTMLElement.prototype));

  proto.createdCallback = function() {
    this.style.width = '0';
    this.classList.add('closed');
    this.addEventListener('transitionend', this);
  };

  proto.calculateChildWidth = function() {
    var child = this.firstElementChild;
    var childWidth = 0;
    var style;
    while(child) {
      style = window.getComputedStyle(child);
      childWidth += child.offsetWidth + parseInt(style.marginLeft, 10) +
                                      parseInt(style.marginRight, 10);
      child = child.nextElementSibling;
    }
    return childWidth;
  };

  proto.fireEvent = function(event, detail) {
    var evtObject = new CustomEvent(event, {
                                      bubbles: false,
                                      detail: detail || this
                                    });
    this.dispatchEvent(evtObject);
    this.fire(event, detail);
  };

  proto.handleEvent = function(evt) {
    switch(evt.type) {
      // Like System app, the transition is our state machine.
      case 'transitionend':
        // We only process 'background-color' because all states have this
        // change.
        if ((evt.propertyName !== 'background-color' &&
             evt.propertyName !== 'width') ||
            evt.target !== this) {
          break;
        }

        if (this.classList.contains('opening')) {
          this.classList.remove('opening');
          // final state: opened
          this.fireEvent('opened');
        } else if (this.classList.contains('closing')) {
          this.classList.remove('closing');
          this.classList.add('closed');
          // final state: closed
          this.fireEvent('closed');
        }
        break;
    }
  };

  proto.focus = proto.open = function() {
    this.fireEvent('will-open');
    // If we get focus when we closing the group, we need to cancel the closing
    // state.
    this.classList.remove('closed');
    this.classList.remove('closing');
    this.classList.add('opening');
    // change to opening
    this.style.width = this.calculateChildWidth() + 'px';
  };

  proto.blur = proto.close = function() {
    this.fireEvent('will-close');
    // We may call close at mid state, we need to reset all of them and go to
    // closing state
    this.classList.remove('opening');
    this.classList.add('closing');
    this.style.width = '0';
  };

  // Register and return the constructor
  return document.registerElement('smart-banner', { prototype: proto });
})(window);
<|endoftext|>