<commit_before>~ function() {
  var requestAnimationFrame = window.requestAnimationFrame;
  var updateButton = document.querySelector('#updateButton');
  var updateText = document.querySelector('#updateText');
  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext('2d');
  //var TEXT = 'HELLO WORLD';
  var TEXT = 'Happy National Day';
  var WIDTH, HEIGHT;
  var mouseX = 1000,
    mouseY = 1000;
  window.onresize = main;
  window.addEventListener("mousemove", mouseMove, false);
  window.addEventListener("touchmove", touchMove, false);

  updateButton.onclick = function(){
    TEXT = updateText.value || TEXT;
    main();
  }

  main();
  function main() {

    setWidthHeight(); // setWidthHeight

    var particles = [];
    //ctx.globalAlpha = 1;
    //ctx.globalCompositeOperation = "lighter";
    // 新建粒子
    createParticles();
    // 动画循环
    function run() {
      requestAnimationFrame(run);
      // 清除画布
      ctx.clearRect(0, 0, WIDTH, HEIGHT);
      ctx.beginPath();

      particles.forEach(function(particle, index) {
        particle.tick(mouseX, mouseY, ctx);
      });
    }
    run();

    // createParticles
    function createParticles() {
      if(WIDTH < 480) {
        ctx.font = "30px '微软雅黑'";
      }else {
        ctx.font = "80px '微软雅黑'";
      }
      // createLinearGradient
      var gradient = ctx.createLinearGradient(0, 0, WIDTH, 0);
      gradient.addColorStop("0", "white");
      gradient.addColorStop("0.2", "gold");
      gradient.addColorStop("0.5", "pink");
      gradient.addColorStop("0.7", "white");
      gradient.addColorStop("1.0", "red");
      // lineGradient
      ctx.strokeStyle = gradient;
      var textWidth = ctx.measureText(TEXT).width;
      ctx.strokeText(TEXT, WIDTH/2 - textWidth/2, HEIGHT/2);
      // get particle from canvas
      var imgData = ctx.getImageData(0, 0, WIDTH, HEIGHT);
      for (var i = 0, len = imgData.data.length; i < len; i = i + 4) {
        var r = imgData.data[i];
        var g = imgData.data[i + 1];
        var b = imgData.data[i + 2];
        var a = imgData.data[i + 3];
        var x = Math.floor((i % (WIDTH * 4)) / 4);
        var y = Math.floor(i / (WIDTH * 4));
        var color = 'rgba(' + r + ',' + g + ',' + b + ','+ a +')';
        if (a) {
          particles.push(new Particle({
            x: x,
            y: y,
            color: color
          }));
        }
      }
    }
  };

  // set canvas to full screen
  function setWidthHeight() {
    WIDTH = canvas.width = parseInt(window.getComputedStyle(document.querySelector('body')).width);
    HEIGHT = canvas.height = parseInt(window.getComputedStyle(document.querySelector('body')).height);
  }
  // mouse move event
  function mouseMove(event) {
    event = event || window.event;
    mouseX = event.pageX;
    mouseY = event.pageY;
  }
  // touch move event
  function touchMove(event) {
    event = event || window.event;
    var touch = event.touches[0];
    mouseX = touch.pageX;
    mouseY = touch.pageY;
  }
}();
<commit_msg>从 url 中传入文字<commit_after>~ function() {
  var requestAnimationFrame = window.requestAnimationFrame;
  var updateButton = document.querySelector('#updateButton');
  var updateText = document.querySelector('#updateText');
  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext('2d');
  //var TEXT = 'HELLO WORLD';
  var TEXT = getQueryParams().text || 'Happy National Day';
  var WIDTH, HEIGHT;
  var mouseX = 1000,
    mouseY = 1000;
  window.onresize = main;
  window.addEventListener("mousemove", mouseMove, false);
  window.addEventListener("touchmove", touchMove, false);

  updateButton.onclick = function(){
    TEXT = updateText.value || TEXT;
    main();
  }

  function getQueryParams() {
    var result = {}
    var searchString = location.search.split('?')[1];
    if (searchString) {
      var searchArr = searchString.split('&');
      searchArr.forEach(function (str) {
        strArr = str.split('=');
        result[strArr[0]] = decodeURI(strArr[1])
      })
    }
    return result
  }

  main();
  function main() {

    setWidthHeight(); // setWidthHeight

    var particles = [];
    //ctx.globalAlpha = 1;
    //ctx.globalCompositeOperation = "lighter";
    // 新建粒子
    createParticles();
    // 动画循环
    function run() {
      requestAnimationFrame(run);
      // 清除画布
      ctx.clearRect(0, 0, WIDTH, HEIGHT);
      ctx.beginPath();

      particles.forEach(function(particle, index) {
        particle.tick(mouseX, mouseY, ctx);
      });
    }
    run();

    // createParticles
    function createParticles() {
      if(WIDTH < 480) {
        ctx.font = "30px '微软雅黑'";
      }else {
        ctx.font = "80px '微软雅黑'";
      }
      // createLinearGradient
      var gradient = ctx.createLinearGradient(0, 0, WIDTH, 0);
      gradient.addColorStop("0", "white");
      gradient.addColorStop("0.2", "gold");
      gradient.addColorStop("0.5", "pink");
      gradient.addColorStop("0.7", "white");
      gradient.addColorStop("1.0", "red");
      // lineGradient
      ctx.strokeStyle = gradient;
      var textWidth = ctx.measureText(TEXT).width;
      ctx.strokeText(TEXT, WIDTH/2 - textWidth/2, HEIGHT/2);
      // get particle from canvas
      var imgData = ctx.getImageData(0, 0, WIDTH, HEIGHT);
      for (var i = 0, len = imgData.data.length; i < len; i = i + 4) {
        var r = imgData.data[i];
        var g = imgData.data[i + 1];
        var b = imgData.data[i + 2];
        var a = imgData.data[i + 3];
        var x = Math.floor((i % (WIDTH * 4)) / 4);
        var y = Math.floor(i / (WIDTH * 4));
        var color = 'rgba(' + r + ',' + g + ',' + b + ','+ a +')';
        if (a) {
          particles.push(new Particle({
            x: x,
            y: y,
            color: color
          }));
        }
      }
    }
  };

  // set canvas to full screen
  function setWidthHeight() {
    WIDTH = canvas.width = parseInt(window.getComputedStyle(document.querySelector('body')).width);
    HEIGHT = canvas.height = parseInt(window.getComputedStyle(document.querySelector('body')).height);
  }
  // mouse move event
  function mouseMove(event) {
    event = event || window.event;
    mouseX = event.pageX;
    mouseY = event.pageY;
  }
  // touch move event
  function touchMove(event) {
    event = event || window.event;
    var touch = event.touches[0];
    mouseX = touch.pageX;
    mouseY = touch.pageY;
  }
}();
<|endoftext|>


<commit_before>---
layout: null
---
$(document).ready(function () {
  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

  if (window.location.hash && window.location.hash == '#blog') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }

  if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

})
<commit_msg>another try removing some js lines<commit_after>---
layout: null
---
$(document).ready(function () {
  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

  // if (window.location.hash && window.location.hash == 'blog/index.html') {
    // $('.panel-cover').addClass('panel-cover--collapsed')
  // }

  if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

})
<|endoftext|>


<commit_before>var WIDTH;
var HEIGHT;
var HWIDTH;
var HHEIGHT;
var g;
var rightDown = false;
var leftDown = false;
var upDown = false;
var downDown = false;
var carray = new Array();
var c = 1; //Do not change, not fully implemented

//TODO: Decide if we're using increments of ct or t.
var timestep=1; //Not wholly implemented yet, need some scale calls. Do not change from 1.
var t = 0;
// Main Function To Start
function start()
{
	g = $('#canvas')[0].getContext("2d");
	WIDTH = $("#canvas").width();
	HEIGHT = $("#canvas").height();
	HWIDTH=WIDTH/2;
	HHEIGHT=HEIGHT/2;
	var numstars = 5000;
	var angle;
	for (i=0; i<numstars; i++)
	{
	angle=Math.random()*2*Math.PI;
	rad=Math.pow(Math.random()*10000000,0.5);
	xjit=Math.random()*0.2*c;
	yjit=Math.random()*0.2*c;
	carray[i] = new inertialObject(Math.cos(angle)*rad,Math.sin(angle)*rad,5,0.1*Math.cos(angle)+xjit,0.1*Math.sin(angle)+yjit);
	}
	carray[numstars]=new inertialObject(0,0,20,0,0);
	boostVel=vec3.create([0,0.05,0]);
	boostRight=cBoostMat(boostVel,c);
	boostVel=vec3.create([0,-0.05,0]);
	boostLeft=cBoostMat(boostVel,c);
	boostVel=vec3.create([0,0,-0.05]);
	boostUp=cBoostMat(boostVel,c);
	boostVel=vec3.create([0,0,0.05]);
	boostDown=cBoostMat(boostVel,c);
	return setInterval(draw, 10);
}

// Draw Function
function draw()
{
//	console.profile();
	clear();
	var i;
	for (i=0; i<carray.length; i++)
	{
		carray[i].updateX0();
		carray[i].draw();
	}
	t+=timestep;
//	console.profileEnd();
}
function clear()
{
	g.fillStyle = "#fff";
	g.fillRect(0, 0, WIDTH, HEIGHT);
	g.fillStyle = "#000";
}

// Use JQuery to wait for document load
$(document).ready(function()
{
	start();
});

$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
<commit_msg>Change to white on black background<commit_after>var WIDTH;
var HEIGHT;
var HWIDTH;
var HHEIGHT;
var g;
var rightDown = false;
var leftDown = false;
var upDown = false;
var downDown = false;
var carray = new Array();
var c = 1; //Do not change, not fully implemented

//TODO: Decide if we're using increments of ct or t.
var timestep=1; //Not wholly implemented yet, need some scale calls. Do not change from 1.
var t = 0;
// Main Function To Start
function start()
{
	g = $('#canvas')[0].getContext("2d");
	WIDTH = $("#canvas").width();
	HEIGHT = $("#canvas").height();
	HWIDTH=WIDTH/2;
	HHEIGHT=HEIGHT/2;
	var numstars = 5000;
	var angle;
	for (i=0; i<numstars; i++)
	{
	    angle=Math.random()*2*Math.PI;
	    rad=Math.pow(Math.random()*10000000,0.5);
	    xjit=Math.random()*0.2*c;
	    yjit=Math.random()*0.2*c;
	    carray[i] = new inertialObject(Math.cos(angle) * rad, Math.sin(angle) * rad,
	                                   5, 0.1 * Math.cos(angle) + xjit,
	                                   0.1 * Math.sin(angle) + yjit);
	}
	carray[numstars]=new inertialObject(0,0,20,0,0);
	boostVel=vec3.create([0,0.05,0]);
	boostRight=cBoostMat(boostVel,c);
	boostVel=vec3.create([0,-0.05,0]);
	boostLeft=cBoostMat(boostVel,c);
	boostVel=vec3.create([0,0,-0.05]);
	boostUp=cBoostMat(boostVel,c);
	boostVel=vec3.create([0,0,0.05]);
	boostDown=cBoostMat(boostVel,c);
	return setInterval(draw, 10);
}

// Draw Function
function draw()
{
//	console.profile();
	clear();
	var i;
	for (i=0; i<carray.length; i++)
	{
		carray[i].updateX0();
		carray[i].draw();
	}
	t+=timestep;
//	console.profileEnd();
}
function clear()
{
	g.fillStyle = "#000";
	g.fillRect(0, 0, WIDTH, HEIGHT);
	g.fillStyle = "#fff";
}

// Use JQuery to wait for document load
$(document).ready(function()
{
	start();
});

$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
<|endoftext|>


<commit_before>(function (factory) {
  var jsyaml = require('js-yaml');
  var marked = require("marked");

  require('angular');

  factory(window.angular, jsyaml, marked);
}(function factory (angular, jsyaml, marked) {
  document.querySelector('body').classList.remove("loading");

  angular.module('sop-doc', [])
    .provider('marked', function () {
      return {
        $get: function () {
          return marked;
        }
      };
    })
    .config(function ($sceProvider) {
      $sceProvider.enabled(false);
    })
    .directive('content', function ($http, marked) {
      return {
        restrict: 'E',
        templateUrl: 'content/index.html',
        controller: function () {
          var _this = this;

          $http.get('config.yaml')
            .success(function (configYaml) {
              var config = jsyaml.safeLoad(configYaml);

              _this.title = config.title;
            });

          $http.get("content.md")
            .success(function (contentMd) {
              _this.content = marked(contentMd);
            });
        },
        controllerAs: "content"
      };
    });
}));

<commit_msg>Adding error handling for missing config or content<commit_after>(function (factory) {
  var jsyaml = require('js-yaml');
  var marked = require("marked");

  require('angular');

  factory(window.angular, jsyaml, marked);
}(function factory (angular, jsyaml, marked) {
  document.querySelector('body').classList.remove("loading");

  angular.module('sop-doc', [])
    .provider('marked', function () {
      return {
        $get: function () {
          return marked;
        }
      };
    })
    .config(function ($sceProvider) {
      $sceProvider.enabled(false);
    })
    .directive('content', function ($http, marked) {
      return {
        restrict: 'E',
        templateUrl: 'content/index.html',
        controller: function () {
          var _this = this;

          $http.get('config.yaml')
            .success(function (configYaml) {
              var config = jsyaml.safeLoad(configYaml);

              _this.title = config.title;
            })
            .error(function () {
              _this.title = '';
            });

          $http.get("content.md")
            .success(function (contentMd) {
              _this.content = marked(contentMd);
            })
            .error(function () {
              _this.content = "Please put your documentation in content.md. You can see an example file in content.md.example.";
            });
        },
        controllerAs: "content"
      };
    });
}));

<|endoftext|>


<commit_before>var stats, scene, renderer, composer, camera, cameraControl, currentSong, PIseconds;
var canvas = document.getElementsByTagName("canvas")[0];
var postFX = {};

// DANCER / SONG RELATED CODE IN HERE
var dancer = new Dancer();
dancer.intervals = [];
songs = {};

function bpm2ms(bpm) {
    return 1 / (bpm / 60000);
}

// events is an array of objects , each containing
// "time" , the value in seconds for when to trigger, &
// "handler", the function that actually modifies behavior
var SongSettings = function (options) {
    this.url = options.url;
    this.bpm = options.bpm;
    this.kick = dancer.createKick(options.kickSettings);
    this.events = options.events;
    this.renderLoop = options.renderLoop;

    // "setup" is an optional func run before each song starts, needs "done" callback
    if (typeof options.setup === 'undefined') {
        this.setup = function () { };
    } else {
        this.setup = options.setup;
    }
}

// extension methodS for dancer.js follow
// feed this one a SongSettings object
dancer.startNewSong = function (song) {
    console.log(song);
    currentSong = song;
    this.load({ src: song.url });
    song.events.forEach(function (event) {
        dancer.onceAt(event.time, event.handler);   // register custom events
    })
    song.kick.on();
    song.setup(function() {console.log("song setup complete");});
    this.play();
}

dancer.setInterval = function (func) {
    this.intervals.push(setInterval(func));
}

dancer.clearAllIntervals = function () {
    this.intervals.forEach(function (e) {
        clearInterval(e);       // stop all the shufflin'
    });
}
// WEBGL / THREE.js CODE AFTER HERE
var randomIntTable = [];
for (var i = 1e4, randomIntTable = []; i--;) {
    var negative = 1;
    if (Math.random() > .5) { negative = -1;};
    randomIntTable.push((Math.random() * 32 | 0) * negative);
}
function randomInt() {
    return ++i >= randomIntTable.length ? randomIntTable[i = 0] : randomIntTable[i];
}

function shuffle(chance) {
    scene.traverse(function (object3d, i) {
        if (object3d instanceof THREE.Mesh === false) return
        if (Math.random() < chance) {
            object3d.position.set(randomInt(), randomInt(), randomInt());
        }
    })
}

function moveUp(distance) {
    var chance = 0.5;
    scene.traverse(function (object3d, i) {
        if (object3d instanceof THREE.Mesh === false) return
        if (Math.random() < chance) {
            object3d.position.y += distance;
        }
    })

}

function shuffleTween() {
    var chance = 0.05;
    scene.traverse(function (object3d, i) {
        if (object3d instanceof THREE.Mesh === false) return
        if (Math.random() < chance) {
            newPosition = new THREE.Vector3(randomInt(), randomInt(), randomInt());
            moveObject(object3d, newPosition);
        }
    })
}
function addMultipleRandom(geometryType, count, size) {
    for (var i = 1 ; i <= count; i++) {
        var geometry = new geometryType(size, size, size);
        var material = new THREE.MeshPhongMaterial({ ambient: 0x808080, color: Math.random() * 0xffffff });
        var mesh = new THREE.Mesh(geometry, material);
        scene.add(mesh);
        mesh.position = new THREE.Vector3(randomInt(), randomInt(), randomInt());
    }
}
function moveObject(object, targetPosition) {
    //TWEEN.removeAll();
    new TWEEN.Tween(object.position.x)
    .to(targetPosition.x, 2000)
    .easing(TWEEN.Easing.Elastic.InOut)
    .onUpdate(render)
    .start();
};

if (!init()) animate();

// init the scene
function init() {

    if (Detector.webgl) {
        renderer = new THREE.WebGLRenderer({
            antialias: true,	// to get smoother output
            //preserveDrawingBuffer: true,	// to allow screenshot
            alpha: true                     // allow transparency
        });
        renderer.setClearColor(0x000000, 0);
    } else {
        Detector.addGetWebGLMessage();
        return true;
    }
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById('container').appendChild(renderer.domElement);

    // add Stats.js - https://github.com/mrdoob/stats.js
    stats = new Stats();
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.bottom = '0px';
    document.body.appendChild(stats.domElement);

    // TODO: break this out so we can create new scenes per song
    // create a scene
    scene = new THREE.Scene();

    // put a camera in the scene
    var cameraH = 3;
    var cameraW = cameraH / window.innerHeight * window.innerWidth;
    camera = new THREE.PerspectiveCamera(-cameraW / 2, +cameraW / 2, cameraH / 2, -cameraH / 2, -10000, 10000);
    camera.position.set(0, 0, 460);
    scene.add(camera);

    composer = new THREE.EffectComposer(renderer, new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, {
        format: THREE.RGBAFormat, // necessary for transparent rendering
        minFilter: THREE.LinearFilter
    }));
    composer.addPass(new THREE.RenderPass(scene, camera));

    postFX.DotScreen = new THREE.ShaderPass(THREE.DotScreenShader);
    postFX.DotScreen.uniforms['scale'].value = 4;
    /*composer.addPass(postFX.DotScreen);*/

    postFX.Kaleidoscope = new THREE.ShaderPass(THREE.KaleidoShader);
    postFX.Kaleidoscope.uniforms['sides'].value = 4;
    //postFX.Kaleidoscope.renderToScreen = true;
    //composer.addPass(postFX.Kaleidoscope);

    postFX.hueSaturation = new THREE.ShaderPass(THREE.HueSaturationShader);
    composer.addPass(postFX.hueSaturation);

    postFX.rgbShift = new THREE.ShaderPass(THREE.RGBShiftShader);
    postFX.rgbShift.uniforms['amount'].value = 0.0033;
    postFX.rgbShift.renderToScreen = true;
    composer.addPass(postFX.rgbShift);

    // create a camera contol
    cameraControls = new THREEx.DragPanControls(camera)

    // transparently support window resize
    THREEx.WindowResize.bind(renderer, camera);
    // allow 'f' to go fullscreen where this feature is supported
    if (THREEx.FullScreen.available()) {
        THREEx.FullScreen.bindKey();
    }

    var light = new THREE.AmbientLight(Math.random() * 0xffffff);
    scene.add(light);
    var light = new THREE.DirectionalLight(Math.random() * 0xffffff);
    light.position.set(Math.random(), Math.random(), Math.random()).normalize();
    scene.add(light);
    var light = new THREE.DirectionalLight(Math.random() * 0xffffff);
    light.position.set(Math.random(), Math.random(), Math.random()).normalize();
    scene.add(light);
    var light = new THREE.PointLight(Math.random() * 0xffffff);
    light.position.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5)
                .normalize().multiplyScalar(1.2);
    scene.add(light);

    for (var i = 1 ; i <= 240; i++) {
        var geometry = new THREE.BoxGeometry(.5, .5, .5);
        var material = new THREE.MeshLambertMaterial({ ambient: 0x888880, color: Math.random() * 0xffffff });
        var mesh = new THREE.Mesh(geometry, material);
        scene.add(mesh);
        mesh.position.set(randomInt(), randomInt(), randomInt());
    }
    for (var i = 1 ; i <= 200; i++) {
        var geometry = new THREE.BoxGeometry(1, 1, 1);
        var material = new THREE.MeshLambertMaterial({ ambient: 0x888880, color: Math.random() * 0xffffff });
        var mesh = new THREE.Mesh(geometry, material);
        scene.add(mesh);
        mesh.position.set(randomInt(), randomInt(), randomInt());
    }
    for (var i = 1 ; i <= 200; i++) {
        var geometry = new THREE.BoxGeometry(.333, .333, .333);
        var material = new THREE.MeshLambertMaterial({ ambient: 0x888880, color: Math.random() * 0xffffff });
        var mesh = new THREE.Mesh(geometry, material);
        scene.add(mesh);
        mesh.position.set(randomInt(), randomInt(), randomInt());
    }

    // dat.gui code
    var gui = new dat.GUI();
    gui.add(postFX.rgbShift.uniforms['amount'], 'value').name("RGB Shift value").listen();
    gui.add(postFX.rgbShift.uniforms['angle'], 'value').name("RGB Shift angle").listen();
    gui.add(postFX.hueSaturation.uniforms['hue'], 'value').name("Hue").listen();
    gui.add(postFX.hueSaturation.uniforms['saturation'], 'value').name("Saturation").listen()
        .min(0).max(10).step(0.05).listen();
    gui.add(postFX.DotScreen.uniforms['scale'], 'value').name("Dot Screen scale").listen();
    gui.add(postFX.Kaleidoscope.uniforms['angle'], 'value').name("Kaledioscope angle").listen();
    gui.add(postFX.Kaleidoscope.uniforms['sides'], 'value').name("Kaledioscope sides")
        .min(3).max(12).step(1).listen();
}

// animation loop
function animate() {
    requestAnimationFrame(animate);
    render();
    stats.update();
}

// render the scene
function render() {
    // variable which is increase by Math.PI every seconds - usefull for animation
    PIseconds = Date.now() * Math.PI;
    cameraControls.update();
    //song-specific code that goes in the render loop
    if (currentSong != null) {
        currentSong.renderLoop();
    }
    // actually render the scene
    composer.render(scene, camera);
}<commit_msg>refactor init() into logical blocks<commit_after>var stats, scene, renderer, composer, camera, cameraControl, gui, currentSong, PIseconds;
var canvas = document.getElementsByTagName("canvas")[0];
var prepare = {};
var postFX = {};

// DANCER / SONG RELATED CODE IN HERE
var dancer = new Dancer();
dancer.intervals = [];
songs = {};

function bpm2ms(bpm) {
    return 1 / (bpm / 60000);
}

// events is an array of objects , each containing
// "time" , the value in seconds for when to trigger, &
// "handler", the function that actually modifies behavior
var SongSettings = function (options) {
    this.url = options.url;
    this.bpm = options.bpm;
    this.kick = dancer.createKick(options.kickSettings);
    this.events = options.events;
    this.renderLoop = options.renderLoop;

    // "setup" is an optional func run before each song starts, needs "done" callback
    if (typeof options.setup === 'undefined') {
        this.setup = function () { };
    } else {
        this.setup = options.setup;
    }
}

// extension methodS for dancer.js follow
// feed this one a SongSettings object
dancer.startNewSong = function (song) {
    console.log(song);
    currentSong = song;
    this.load({ src: song.url });
    song.events.forEach(function (event) {
        dancer.onceAt(event.time, event.handler);   // register custom events
    })
    song.kick.on();
    song.setup(function() {console.log("song setup complete");});
    this.play();
}

dancer.setInterval = function (func) {
    this.intervals.push(setInterval(func));
}

dancer.clearAllIntervals = function () {
    this.intervals.forEach(function (e) {
        clearInterval(e);       // stop all the shufflin'
    });
}

// WEBGL / THREE.js CODE AFTER HERE
var randomIntTable = [];
for (var i = 1e4, randomIntTable = []; i--;) {
    var negative = 1;
    if (Math.random() > .5) { negative = -1;};
    randomIntTable.push((Math.random() * 32 | 0) * negative);
}
function randomInt() {
    return ++i >= randomIntTable.length ? randomIntTable[i = 0] : randomIntTable[i];
}

function makeRandomGeometries(sizes, count, geometryType, materialType) {
    for (var i = 1 ; i <= count; i++) {
        var geometry = new geometryType(sizes[0], sizes[1], sizes[2]);
        var material = new materialType({ ambient: 0x888880, color: Math.random() * 0xffffff });
        var mesh = new THREE.Mesh(geometry, material);
        scene.add(mesh);
        mesh.position.set(randomInt(), randomInt(), randomInt());
    }
}

function shuffle(chance) {
    scene.traverse(function (object3d, i) {
        if (object3d instanceof THREE.Mesh === false) return
        if (Math.random() < chance) {
            object3d.position.set(randomInt(), randomInt(), randomInt());
        }
    })
}

function moveUp(distance) {
    var chance = 0.5;
    scene.traverse(function (object3d, i) {
        if (object3d instanceof THREE.Mesh === false) return
        if (Math.random() < chance) {
            object3d.position.y += distance;
        }
    })
}

function moveObject(object, targetPosition) {
    new TWEEN.Tween(object.position.x)
    .to(targetPosition.x, 2000)
    .easing(TWEEN.Easing.Elastic.InOut)
    .onUpdate(render)
    .start();
};

// all these members of "prepare" run inside init()
prepare.renderer = function () {
    if (Detector.webgl) {
        renderer = new THREE.WebGLRenderer({
            antialias: true,	// to get smoother output
            alpha: true                     // allow transparency
        });
        renderer.setClearColor(0x000000, 0);
    } else {
        Detector.addGetWebGLMessage();
        return true;
    }
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById('container').appendChild(renderer.domElement);
}

prepare.camera = function () {
    var cameraH = 3;
    var cameraW = cameraH / window.innerHeight * window.innerWidth;
    camera = new THREE.PerspectiveCamera(-cameraW / 2, +cameraW / 2, cameraH / 2, -cameraH / 2, -10000, 10000);
    camera.position.set(0, 0, 460);
    scene.add(camera);
}

prepare.stats = function () {
    stats = new Stats();
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.bottom = '0px';
    document.body.appendChild(stats.domElement);
}

prepare.lights = function() {
    var light = new THREE.AmbientLight(Math.random() * 0xffffff);
    scene.add(light);
    for (var i = 0; i < 2; i++) {
        var light = new THREE.DirectionalLight(Math.random() * 0xffffff);
        light.position.set(Math.random(), Math.random(), Math.random()).normalize();
        scene.add(light);
    }
    var light = new THREE.PointLight(Math.random() * 0xffffff);
    light.position.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5)
                .normalize().multiplyScalar(1.2);
    scene.add(light);
}

prepare.shaderPostFX = function() {
    postFX.DotScreen = new THREE.ShaderPass(THREE.DotScreenShader);
    postFX.DotScreen.uniforms['scale'].value = 4;
    postFX.Kaleidoscope = new THREE.ShaderPass(THREE.KaleidoShader);
    postFX.Kaleidoscope.uniforms['sides'].value = 4;
    postFX.hueSaturation = new THREE.ShaderPass(THREE.HueSaturationShader);
    postFX.rgbShift = new THREE.ShaderPass(THREE.RGBShiftShader);
}

prepare.fxComposer = function() {
    composer = new THREE.EffectComposer(renderer, new THREE.WebGLRenderTarget(
        window.innerWidth, window.innerHeight, {
            format: THREE.RGBAFormat,               // necessary for transparent rendering
            minFilter: THREE.LinearFilter
        }));
    composer.addPass(new THREE.RenderPass(scene, camera));
}

prepare.datGUI = function() {
    gui = new dat.GUI();
    gui.add(postFX.rgbShift.uniforms['amount'], 'value').name("RGB Shift value").listen();
    gui.add(postFX.rgbShift.uniforms['angle'], 'value').name("RGB Shift angle").listen();
    gui.add(postFX.hueSaturation.uniforms['hue'], 'value').name("Hue").listen();
    gui.add(postFX.hueSaturation.uniforms['saturation'], 'value').name("Saturation").listen()
        .min(0).max(10).step(0.05).listen();
    gui.add(postFX.DotScreen.uniforms['scale'], 'value').name("Dot Screen scale").listen();
    gui.add(postFX.Kaleidoscope.uniforms['angle'], 'value').name("Kaledioscope angle").listen();
    gui.add(postFX.Kaleidoscope.uniforms['sides'], 'value').name("Kaledioscope sides")
        .min(3).max(12).step(1).listen();
}

if (!init()) animate();

// init the scene
function init() {
    scene = new THREE.Scene();
    prepare.renderer();
    prepare.camera();
    prepare.stats();
    prepare.lights();
    prepare.shaderPostFX();
    prepare.fxComposer();
    prepare.datGUI();

    cameraControls = new THREEx.DragPanControls(camera)
    // transparently support window resize
    THREEx.WindowResize.bind(renderer, camera);     // support window resizing

    // insert starting geometry
    makeRandomGeometries([.333, .333, .333], 200, THREE.BoxGeometry, THREE.MeshLambertMaterial);
    makeRandomGeometries([.5, .5, .5], 200, THREE.BoxGeometry, THREE.MeshLambertMaterial);
    makeRandomGeometries([1, 1, 1], 200, THREE.BoxGeometry, THREE.MeshLambertMaterial);
}

// animation loop
function animate() {
    requestAnimationFrame(animate);
    render();
    stats.update();
}

// render the scene
function render() {
    // variable which is increase by Math.PI every seconds - usefull for animation
    PIseconds = Date.now() * Math.PI;
    cameraControls.update();
    //song-specific code that goes in the render loop
    if (currentSong != null) {
        currentSong.renderLoop();
    }
    // if we only have a RenderPass in the composer, skip it and directly render
    // this allows instantiating the composer before we want to use effects
    if (composer.passes.length > 1) {
        composer.render(scene, camera);
    } else {
        renderer.render(scene, camera);
    }
}<|endoftext|>


<commit_before>(function(){
  'use strict';

  var $           = Snap.select,
      $$          = Snap.selectAll,
      i           = 0,
      ang         = 0,
      danceDelay  = 3000,
      prevScrollX = 0,
      foodPoints  = [],
      isScrollingForward, food, initSkate, lookTimer, dancing, danceTimer, scrollTimer, hairTimer;

  var fancypants  = $('.fp'),
      head        = $('#Face'),
      eyes        = $$('#Right_eye,#Left_eye'),
      smile       = $('#Smile'),
      mouth       = $('#Open_mouth_1_'),
      spine       = $('#Spine'),
      hand1       = $('#Left_hand'),
      hand2       = $('#Right_hand'),
      belt        = $('#Belt_1_'),
      pant1       = $('#Left_leg'),
      pant2       = $('#Right_leg'),
      legCrack    = $('#Leg_crack'),
      leftFolds   = $('#Left_pant_folds'),
      rightFolds  = $('#Right_pant_folds'),
      pants       = $$('#Right_leg,#Left_leg'),
      wheels      = $$('#wheel,#wheel_1_'),
      eatables    = $$('.eatable'),
      hairFront   = document.getElementById('hair-front'),
      hairBack    = document.getElementById('hair-back');

  var pivots = {
    'spine':[spine.attr('x1'),spine.attr('y1')],
    'hand1':[hand1.attr('x1'),hand1.attr('y1')],
    'hand2':[hand2.attr('x1'),hand2.attr('y1')],
    'hair':[head.attr('cx'),head.attr('cy')],
    'folds': [legCrack.attr('x2'), legCrack.attr('y2')]
  };

  var init = function(){
    eatables.forEach(function(el){
      foodPoints.push({'el':el,'isEaten': false});
    });

    setTimeout(function(){
      lookLeft();
      initSkate = setInterval(function(){skate('front');},20);
      fancypants.attr('class','fp');
      setTimeout(function(){
        clearTimeout(initSkate);
        lookStraight();
        setTimeout(blinkEyes,500);
      },1000);
    },1000);

    document.addEventListener('scroll',function(){ onScroll(); });

    danceTimer = setTimeout(function(){
      dancing = setInterval(dance,500);
    }, danceDelay);
  };

  window.addEventListener('load', init, false);
  var scrollHelper = document.querySelector('.scroll-helper');

  function onScroll(){
    scrollHelper.style.display = 'none';

    if (danceTimer)  {
      clearInterval(dancing);
      resetFancyPants();
      clearTimeout(danceTimer);
    }

    danceTimer = setTimeout(function(){
      dancing = setInterval(dance,500);
    },danceDelay);

    isScrollingForward = window.scrollX - prevScrollX > 0;
    prevScrollX = window.scrollX;

    if(isScrollingForward) {
      skate('front');
      hairBack.beginElement();
      lookLeft();
    } else {
      skate('back');
      hairFront.beginElement();
      lookRight();
    }

    if (scrollTimer) { clearTimeout(scrollTimer); }
    if (hairTimer) { clearTimeout(hairTimer); }

    hairTimer = setTimeout(function(){
      hairFront.beginElement();
    }, 100);

    scrollTimer = setTimeout(function(){
      eat();
    }, 1);

    if(lookTimer) { clearTimeout(lookTimer); }
    lookTimer = setTimeout(lookStraight,100);
  }

  function skate(dir){
    wheels.forEach(function(el){
      ang = (dir === 'front' ? ang+1 : ang-1);
      el.transform('r'+[10*ang]);
    });
  }

  function eat(){
    for (var i = foodPoints.length - 1; i >= 0; i--) {
      food = foodPoints[i];
      if(window.scrollX > food.el.node.offsetLeft - 250 && !food.isEaten){
        openMouth();
      }
      if(window.scrollX > food.el.node.offsetLeft - 170 && !food.isEaten){
        food.el.node.style.display = 'none';
        closeMouth();
        changePants(food.el.node.getAttribute('color'));
        food.isEaten = true;
      }
    }
  }

  function blinkEyes(){
    eyes.forEach(function(el){
      el.attr({'r':0});
    });
    setTimeout(function(){
      eyes.forEach(function(el){
        el.attr({'r':4.08});
      });
    },100);
  }

  function changePants(color){
    pants.forEach(function(el){
      el.animate({'fill': color},200);
    });
  }

  function lookLeft(){
    eyes.forEach(function(el){
      el.animate({transform:'t'+[10,0]},50);
    });
  }

  function lookRight(){
    eyes.forEach(function(el){
      el.animate({transform:'t'+[-10,0]},50);
    });
  }

  function openMouth(){
    smile.attr('display','none');
    mouth.attr('display','inline').animate({transform:'t'+[-26,0]},20);
  }

  function closeMouth(){
    smile.attr('display','inline');
    mouth.attr('display','none').animate({transform:'t'+[0,0]},20);
  }

  function lookStraight(){
    eyes.forEach(function(el){
      el.animate({transform:'t'+[0,0]},50);
    });
  }

  function dance(){
    pant1.animate({transform:'t'+[-7,0]},200);
    pant2.animate({transform:'t'+[-7,0]},200);
    spine.animate({transform:'r'+[5,pivots.spine]},200);
    legCrack.animate({transform:'t'+[-7,0]+'r'+[-10,pivots.folds]},200);
    leftFolds.animate({transform:'t'+[-7,0]+'r'+[-10,pivots.folds]},200);
    rightFolds.animate({transform:'t'+[-7,0]+'r'+[-10,pivots.folds]},200);
    hand1.animate({transform:'r'+[-7,pivots.spine]},200);
    hand2.animate({transform:'r'+[-7,pivots.spine]},200);
    belt.animate({transform:'t'+[-7,0]},200);
    setTimeout(function(){
      pant1.animate({transform:'t'+[7,0]},200);
      pant2.animate({transform:'t'+[7,0]},200);
      spine.animate({transform:'r'+[-5,pivots.spine]},200);
      legCrack.animate({transform:'t'+[7,0]+'r'+[15,pivots.folds]},200);
      leftFolds.animate({transform:'t'+[7,0]+'r'+[15,pivots.folds]},200);
      rightFolds.animate({transform:'t'+[7,0]+'r'+[15,pivots.folds]},200);
      hand1.animate({transform:'r'+[7,pivots.spine]},200);
      hand2.animate({transform:'r'+[7,pivots.spine]},200);
      belt.animate({transform:'t'+[7,0]},200);
    }, 250);
  }

  function resetFancyPants(){
    pant1.animate({transform:'t'+[0,0]},200);
    pant2.animate({transform:'t'+[0,0]},200);
    spine.animate({transform:'r'+[0,pivots.spine]},200);
    legCrack.animate({transform:'t'+[0,0]+'r'+[0,pivots.folds]},200);
    leftFolds.animate({transform:'t'+[0,0]+'r'+[0,pivots.folds]},200);
    rightFolds.animate({transform:'t'+[0,0]+'r'+[0,pivots.folds]},200);
    hand1.animate({transform:'r'+[0,pivots.spine]},200);
    hand2.animate({transform:'r'+[0,pivots.spine]},200);
    belt.animate({transform:'t'+[0,0]},200);
  }

})(Snap);<commit_msg>Fixes global variables<commit_after>/*global Snap */

(function(){
  'use strict';

  var $           = Snap.select,
      $$          = Snap.selectAll,
      ang         = 0,
      danceDelay  = 3000,
      prevScrollX = 0,
      foodPoints  = [],
      isScrollingForward, food, initSkate, lookTimer, dancing, danceTimer, scrollTimer, hairTimer;

  var fancypants  = $('.fp'),
      head        = $('#Face'),
      eyes        = $$('#Right_eye,#Left_eye'),
      smile       = $('#Smile'),
      mouth       = $('#Open_mouth_1_'),
      spine       = $('#Spine'),
      hand1       = $('#Left_hand'),
      hand2       = $('#Right_hand'),
      belt        = $('#Belt_1_'),
      pant1       = $('#Left_leg'),
      pant2       = $('#Right_leg'),
      legCrack    = $('#Leg_crack'),
      leftFolds   = $('#Left_pant_folds'),
      rightFolds  = $('#Right_pant_folds'),
      pants       = $$('#Right_leg,#Left_leg'),
      wheels      = $$('#wheel,#wheel_1_'),
      eatables    = $$('.eatable'),
      hairFront   = document.getElementById('hair-front'),
      hairBack    = document.getElementById('hair-back');

  var pivots = {
    'spine':[spine.attr('x1'),spine.attr('y1')],
    'hand1':[hand1.attr('x1'),hand1.attr('y1')],
    'hand2':[hand2.attr('x1'),hand2.attr('y1')],
    'hair':[head.attr('cx'),head.attr('cy')],
    'folds': [legCrack.attr('x2'), legCrack.attr('y2')]
  };

  var init = function(){
    eatables.forEach(function(el){
      foodPoints.push({'el':el,'isEaten': false});
    });

    setTimeout(function(){
      lookLeft();
      initSkate = setInterval(function(){skate('front');},20);
      fancypants.attr('class','fp');
      setTimeout(function(){
        clearTimeout(initSkate);
        lookStraight();
        setTimeout(blinkEyes,500);
      },1000);
    },1000);

    document.addEventListener('scroll',function(){ onScroll(); });

    danceTimer = setTimeout(function(){
      dancing = setInterval(dance,500);
    }, danceDelay);
  };

  window.addEventListener('load', init, false);
  var scrollHelper = document.querySelector('.scroll-helper');

  function onScroll(){
    scrollHelper.style.display = 'none';

    if (danceTimer)  {
      clearInterval(dancing);
      resetFancyPants();
      clearTimeout(danceTimer);
    }

    danceTimer = setTimeout(function(){
      dancing = setInterval(dance,500);
    },danceDelay);

    isScrollingForward = window.scrollX - prevScrollX > 0;
    prevScrollX = window.scrollX;

    if(isScrollingForward) {
      skate('front');
      hairBack.beginElement();
      lookLeft();
    } else {
      skate('back');
      hairFront.beginElement();
      lookRight();
    }

    if (scrollTimer) { clearTimeout(scrollTimer); }
    if (hairTimer) { clearTimeout(hairTimer); }

    hairTimer = setTimeout(function(){
      hairFront.beginElement();
    }, 100);

    scrollTimer = setTimeout(function(){
      eat();
    }, 1);

    if(lookTimer) { clearTimeout(lookTimer); }
    lookTimer = setTimeout(lookStraight,100);
  }

  function skate(dir){
    wheels.forEach(function(el){
      ang = (dir === 'front' ? ang+1 : ang-1);
      el.transform('r'+[10*ang]);
    });
  }

  function eat(){
    for (var i = foodPoints.length - 1; i >= 0; i--) {
      food = foodPoints[i];
      if(window.scrollX > food.el.node.offsetLeft - 250 && !food.isEaten){
        openMouth();
      }
      if(window.scrollX > food.el.node.offsetLeft - 170 && !food.isEaten){
        food.el.node.style.display = 'none';
        closeMouth();
        changePants(food.el.node.getAttribute('color'));
        food.isEaten = true;
      }
    }
  }

  function blinkEyes(){
    eyes.forEach(function(el){
      el.attr({'r':0});
    });
    setTimeout(function(){
      eyes.forEach(function(el){
        el.attr({'r':4.08});
      });
    },100);
  }

  function changePants(color){
    pants.forEach(function(el){
      el.animate({'fill': color},200);
    });
  }

  function lookLeft(){
    eyes.forEach(function(el){
      el.animate({transform:'t'+[10,0]},50);
    });
  }

  function lookRight(){
    eyes.forEach(function(el){
      el.animate({transform:'t'+[-10,0]},50);
    });
  }

  function openMouth(){
    smile.attr('display','none');
    mouth.attr('display','inline').animate({transform:'t'+[-26,0]},20);
  }

  function closeMouth(){
    smile.attr('display','inline');
    mouth.attr('display','none').animate({transform:'t'+[0,0]},20);
  }

  function lookStraight(){
    eyes.forEach(function(el){
      el.animate({transform:'t'+[0,0]},50);
    });
  }

  function dance(){
    pant1.animate({transform:'t'+[-7,0]},200);
    pant2.animate({transform:'t'+[-7,0]},200);
    spine.animate({transform:'r'+[5,pivots.spine]},200);
    legCrack.animate({transform:'t'+[-7,0]+'r'+[-10,pivots.folds]},200);
    leftFolds.animate({transform:'t'+[-7,0]+'r'+[-10,pivots.folds]},200);
    rightFolds.animate({transform:'t'+[-7,0]+'r'+[-10,pivots.folds]},200);
    hand1.animate({transform:'r'+[-7,pivots.spine]},200);
    hand2.animate({transform:'r'+[-7,pivots.spine]},200);
    belt.animate({transform:'t'+[-7,0]},200);
    setTimeout(function(){
      pant1.animate({transform:'t'+[7,0]},200);
      pant2.animate({transform:'t'+[7,0]},200);
      spine.animate({transform:'r'+[-5,pivots.spine]},200);
      legCrack.animate({transform:'t'+[7,0]+'r'+[15,pivots.folds]},200);
      leftFolds.animate({transform:'t'+[7,0]+'r'+[15,pivots.folds]},200);
      rightFolds.animate({transform:'t'+[7,0]+'r'+[15,pivots.folds]},200);
      hand1.animate({transform:'r'+[7,pivots.spine]},200);
      hand2.animate({transform:'r'+[7,pivots.spine]},200);
      belt.animate({transform:'t'+[7,0]},200);
    }, 250);
  }

  function resetFancyPants(){
    pant1.animate({transform:'t'+[0,0]},200);
    pant2.animate({transform:'t'+[0,0]},200);
    spine.animate({transform:'r'+[0,pivots.spine]},200);
    legCrack.animate({transform:'t'+[0,0]+'r'+[0,pivots.folds]},200);
    leftFolds.animate({transform:'t'+[0,0]+'r'+[0,pivots.folds]},200);
    rightFolds.animate({transform:'t'+[0,0]+'r'+[0,pivots.folds]},200);
    hand1.animate({transform:'r'+[0,pivots.spine]},200);
    hand2.animate({transform:'r'+[0,pivots.spine]},200);
    belt.animate({transform:'t'+[0,0]},200);
  }

})(Snap);<|endoftext|>


<commit_before><commit_msg>scaffold<commit_after>// sidebar window-height
$(function() {
  function overlapListener() {
    var h = $(window).height(),
    nTop = $("ul.links").offset().top,
    nHeight = $("ul.links").height(),
    nBottom = nTop + nHeight,
    f = $("section.nav-footer").offset().top

    if($(f) <= nBottom) {
      console.log('hi')
    }
  }

  $(window).on("load", function() {

    overlapListener()

  })

  $(window).on("resize", function() {
    overlapListener()
  })

})<|endoftext|>


<commit_before>function setup() {
    createCanvas(windowWidth, windowHeight);

    word = 'SEVENTYFIVE'

    words = [
        'UNITED STATES',
        'MEXICO',
        'BRAZIL',
        'IRAN',
        'ISLAMIC REPUBLIC',
        'TURKEY',
        'EGYPT',
        'NIGERIA',
        'CONGO',
        // 'DEMOCRATIC REPUBLIC',
        'ETHIOPIA',
        'TANZANIA',
        'CHINA',
        'PAKISTAN',
        'PHILLIPPINES',
        'VIETNAM',
        'INDONESIA',
        'THAILAND',
        'MYANMAR',
        'BANGLADESH',
        // 'RUSSIAN FEDERATION'
        'RUSSIA',
        'RURAL',
        'LOW INCOME',
        'ELDERLY',
        'ILLITERATE',
        'FEMALE',
        'INCENTIVES',
        'AFFORDABILITY',
        'USER CAPABILITY',
        'INFRASTRUCTURE'
    ];

    currentLetter = '';
    letterCount = 0;
    letterWordRepeat = 2;
    letterFadeDuration = 1000;

    currentWord = '';
    wordCount = 0;
    wordDuration = 90;

    titleColor = 255;
    titleDuration = 15000;

    captionDuration = 1000;

    backgroundColor = 255;

    textFont('Helvetica Neue, Helvetica, Arial, sans-serif');
    textStyle(BOLD);

    noStroke();

    setupAnimation();
}

function setupAnimation() {
    MOTION.removeAll();

    ended = false;

    titleLetters = []

    titleLettersSequence = new MOTION.Sequence();

    titleLettersSequence.add(new MOTION.Tween(captionDuration)
            .add('captionColor', [0, 255]))
        // .add('titleColor', [0, 255]))

    titleLettersSequence.add(new MOTION(titleDuration))

    titleLettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [0, 255], this.duration()).play()
        }).onEnd(function() {
            ended = false;
            lettersSequence.play()
        })

    letters = [];
    letters.offset = textWidth(word) / 2;

    letters.x = width / 2 - letters.offset;
    letters.y = height / 2;

    for (var i = 0; i < word.length; i++) {
        var letter = word.charAt(i);
        var letterWords = [];

        for (var j in words)
            for (var k in words[j])
                if (words[j][k] === letter)
                    for (var l = 0; l < letterWordRepeat; l++)
                        letterWords.push({
                            word: words[j],
                            index: k,
                            offset: textWidth(words[j].substring(0, k))
                        })

        letters.push({
            letter: letter,
            offset: textWidth(word.substring(0, i)),
            words: shuffle(letterWords)
        })
    }

    lettersSequence = new MOTION.Sequence();

    for (var i in letters) {
        for (var j in letters[i].words) {
            var m = new MOTION(wordDuration).onStart(function() {
                currentLetter = this.letter;
                currentWord = this.word;
            });
            m.letter = letters[i];
            m.word = letters[i].words[j];

            lettersSequence.add(m)
        }
    }

    lettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [255, 0], this.duration()).play()
            titleColorTween = new MOTION.Sequence()
                .add(new MOTION.Tween('titleColor', [255, 0], letterFadeDuration))
                .add(new MOTION.Tween('titleColor', [0, 255], this.duration() - letterFadeDuration))
                .play()
        })
        .onEnd(function() {
            ended = true;
            titleLettersSequence.play();
        })
        .play()

    // titleLettersSequence.play().onEnd(function() {});
}

function pauseSequence() {
    lettersSequence.pause();
    titleColorTween.pause();
    backgroundColorTween.pause();
}

function resumeSequence() {
    if (!lettersSequence.isPlaying()) {
        lettersSequence.resume();
        titleColorTween.resume();
        backgroundColorTween.resume();
    }
}

function draw() {
    MOTION.update(millis());

    background(backgroundColor);
    // blur(3);
    //     Filters.filterImage(Filters.convolute, image,
    //   [ 1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9 ]
    // );

    if (!ended) {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(1, letters.x, letters.y)
        text(currentWord.word, letters.x + currentLetter.offset - currentWord.offset, letters.y)

        fill(255)
        text(currentLetter.letter, letters.x + currentLetter.offset, letters.y)
    } else {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(word, letters.x, letters.y)

        textSize(captionHeight)
        textAlign(CENTER);
        fill(captionColor)
        text('percent of the 4.4 billion people offline worldwide are in 20 countries\nincluding the U.S., which has 50 million; 1 out of 6 people...', width / 2, letters.y + captionHeight * 2)
    }
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight);

    titleHeight = width * .125;
    captionHeight = max(width * .015, 14);;

    textSize(titleHeight);

    setupAnimation();
}

function mouseMoved() {
    if (ended) return false;

    if (mouseY > height / 2 - titleHeight && mouseY < height / 2)
        pauseSequence();
    else
        resumeSequence();
}

function touchStarted() {
    pauseSequence();
}

function touchEnded() {
    resumeSequence();
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o) { //v1.0
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
<commit_msg>fixing resizing<commit_after>function setup() {
    createCanvas(windowWidth, windowHeight);

    word = 'SEVENTYFIVE'

    words = [
        'UNITED STATES',
        'MEXICO',
        'BRAZIL',
        'IRAN',
        'ISLAMIC REPUBLIC',
        'TURKEY',
        'EGYPT',
        'NIGERIA',
        'CONGO',
        // 'DEMOCRATIC REPUBLIC',
        'ETHIOPIA',
        'TANZANIA',
        'CHINA',
        'PAKISTAN',
        'PHILLIPPINES',
        'VIETNAM',
        'INDONESIA',
        'THAILAND',
        'MYANMAR',
        'BANGLADESH',
        // 'RUSSIAN FEDERATION'
        'RUSSIA',
        'RURAL',
        'LOW INCOME',
        'ELDERLY',
        'ILLITERATE',
        'FEMALE',
        'INCENTIVES',
        'AFFORDABILITY',
        'USER CAPABILITY',
        'INFRASTRUCTURE'
    ];

    currentLetter = '';
    letterCount = 0;
    letterWordRepeat = 2;
    letterFadeDuration = 1000;

    currentWord = '';
    wordCount = 0;
    wordDuration = 90;

    titleColor = 255;
    titleDuration = 15000;

    captionDuration = 1000;

    backgroundColor = 255;

    textFont('Helvetica Neue, Helvetica, Arial, sans-serif');
    textStyle(BOLD);

    noStroke();

    setupAnimation();
}

function setupAnimation() {
    titleHeight = width * .125
    captionHeight = max(width * .015, 14);;

    textSize(titleHeight);

    MOTION.removeAll();

    ended = false;

    titleLettersSequence = new MOTION.Sequence();

    titleLettersSequence.add(new MOTION.Tween(captionDuration)
            .add('captionColor', [0, 255]))
        // .add('titleColor', [0, 255]))

    titleLettersSequence.add(new MOTION(titleDuration))

    titleLettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [0, 255], this.duration()).play()
        }).onEnd(function() {
            ended = false;
            lettersSequence.play()
        })

    letters = [];
    letters.offset = textWidth(word) / 2;

    letters.x = width / 2 - letters.offset;
    letters.y = height / 2;

    for (var i = 0; i < word.length; i++) {
        var letter = word.charAt(i);
        var letterWords = [];

        for (var j in words)
            for (var k in words[j])
                if (words[j][k] === letter)
                    for (var l = 0; l < letterWordRepeat; l++)
                        letterWords.push({
                            word: words[j],
                            index: k,
                            offset: textWidth(words[j].substring(0, k))
                        })

        letters.push({
            letter: letter,
            offset: textWidth(word.substring(0, i)),
            words: shuffle(letterWords)
        })
    }

    lettersSequence = new MOTION.Sequence();

    for (var i in letters) {
        for (var j in letters[i].words) {
            var m = new MOTION(wordDuration).onStart(function() {
                currentLetter = this.letter;
                currentWord = this.word;
            });
            m.letter = letters[i];
            m.word = letters[i].words[j];

            lettersSequence.add(m)
        }
    }

    lettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [255, 0], this.duration()).play()
            titleColorTween = new MOTION.Sequence()
                .add(new MOTION.Tween('titleColor', [255, 0], letterFadeDuration))
                .add(new MOTION.Tween('titleColor', [0, 255], this.duration() - letterFadeDuration))
                .play()
        })
        .onEnd(function() {
            ended = true;
            titleLettersSequence.play();
        })
        .play()

    // titleLettersSequence.play().onEnd(function() {});
}

function pauseSequence() {
    lettersSequence.pause();
    titleColorTween.pause();
    backgroundColorTween.pause();
}

function resumeSequence() {
    if (!lettersSequence.isPlaying()) {
        lettersSequence.resume();
        titleColorTween.resume();
        backgroundColorTween.resume();
    }
}

function draw() {
    MOTION.update(millis());

    background(backgroundColor);
    // blur(3);
    //     Filters.filterImage(Filters.convolute, image,
    //   [ 1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9 ]
    // );

    if (!ended) {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(1, letters.x, letters.y)
        text(currentWord.word, letters.x + currentLetter.offset - currentWord.offset, letters.y)

        fill(255)
        text(currentLetter.letter, letters.x + currentLetter.offset, letters.y)
    } else {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(word, letters.x, letters.y)

        textSize(captionHeight)
        textAlign(CENTER);
        fill(captionColor)
        text('percent of the 4.4 billion people offline worldwide are in 20 countries\nincluding the U.S., which has 50 million; 1 out of 6 people...', width / 2, letters.y + captionHeight * 2)
    }
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight);
    setupAnimation();
}

function mouseMoved() {
    if (ended) return false;

    if (mouseY > height / 2 - titleHeight && mouseY < height / 2)
        pauseSequence();
    else
        resumeSequence();
}

function touchStarted() {
    pauseSequence();
}

function touchEnded() {
    resumeSequence();
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o) { //v1.0
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
<|endoftext|>


<commit_before>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/
var dataUrl = 'https://cepatsembuh.firebaseio.com/';

function getPasien(faskes) {
  // Firebase ref
  var dataRef = new Firebase(dataUrl + faskes + '/pasien');

  // Friendly message
  alert('Syncing data..');

  // Show data
  dataRef.once('value', function(snapshot) {
    var data = snapshot.numChildren();
    alert('The total is:' + data);
  });
}

function getFaskes(faskes) {
  // Firebase ref
  var dataRef = new Firebase(dataUrl + faskes + '/faskes');

  // Friendly message
  alert('Syncing data..');

  // Show data
  dataRef.once('value', function(snapshot) {
    var data = snapshot.numChildren();
    alert('The total is:' + data);
  });
}

function link(page) {
  var url = page + '.html';
  window.location.href = url;
}

function updateBed() {
  var username = $('#username').val(),
      tipe = $('#tipe').val(),
      breanna = $('#breanna').val(),
      brea = $('#brea').val(),
      yde = $('#yde').val();

  if (username === '' || tipe === '' || brea === '' || breanna === '' || yde === '') {
    alert('Mohon isi semua input');
  } else {
    // Define firebase URL
    console.log('Defining firebase URL...');
    var ref = new Firebase(dataUrl + tipe + '/faskes/' + username + '/tempat_tidur'),
        brea_is_pretty = Number(breanna),
        brea_is_beatiful = Number(brea),
        crush_on_brea = Number(yde);

    // Friendly message
    update = 'Updating data...';
    console.log(update);
    alert(update);

    // Update the data
    ref.update({
      satu: brea_is_pretty,
      dua: brea_is_beatiful,
      tiga: crush_on_brea
    }, function(error){
      if (!error) {
        // Reload page
        location.reload();
      } else {
        // Error handler
        alert('Gagal meng-update data')
      }
    });
  }
}

function totalPasien() {
  // Get input value
  var username = $('#username').val(),
      tipe = $('#tipe').val();

  // Firebase ref
  var url = dataUrl + tipe + '/faskes/' + username + '/pasien';
  var dataRef = new Firebase(url);

  // Friendly message
  alert('Syncing data..');

  // Show data
   dataRef.once('value', function(snapshot) {
    var data = snapshot.numChildren();
    alert('Jumlah Pasien:' + data);
  });
}
<commit_msg>HTTP protocol<commit_after>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/
var dataUrl = 'http://cepatsembuh.firebaseio.com/';

function getPasien(faskes) {
  // Firebase ref
  var dataRef = new Firebase(dataUrl + faskes + '/pasien');

  // Friendly message
  alert('Syncing data..');

  // Show data
  dataRef.once('value', function(snapshot) {
    var data = snapshot.numChildren();
    alert('The total is:' + data);
  });
}

function getFaskes(faskes) {
  // Firebase ref
  var dataRef = new Firebase(dataUrl + faskes + '/faskes');

  // Friendly message
  alert('Syncing data..');

  // Show data
  dataRef.once('value', function(snapshot) {
    var data = snapshot.numChildren();
    alert('The total is:' + data);
  });
}

function link(page) {
  var url = page + '.html';
  window.location.href = url;
}

function updateBed() {
  var username = $('#username').val(),
      tipe = $('#tipe').val(),
      breanna = $('#breanna').val(),
      brea = $('#brea').val(),
      yde = $('#yde').val();

  if (username === '' || tipe === '' || brea === '' || breanna === '' || yde === '') {
    alert('Mohon isi semua input');
  } else {
    // Define firebase URL
    console.log('Defining firebase URL...');
    var ref = new Firebase(dataUrl + tipe + '/faskes/' + username + '/tempat_tidur'),
        brea_is_pretty = Number(breanna),
        brea_is_beatiful = Number(brea),
        crush_on_brea = Number(yde);

    // Friendly message
    update = 'Updating data...';
    console.log(update);
    alert(update);

    // Update the data
    ref.update({
      satu: brea_is_pretty,
      dua: brea_is_beatiful,
      tiga: crush_on_brea
    }, function(error){
      if (!error) {
        // Reload page
        location.reload();
      } else {
        // Error handler
        alert('Gagal meng-update data')
      }
    });
  }
}

function totalPasien() {
  // Get input value
  var username = $('#username').val(),
      tipe = $('#tipe').val();

  // Firebase ref
  var url = dataUrl + tipe + '/faskes/' + username + '/pasien';
  var dataRef = new Firebase(url);

  // Friendly message
  alert('Syncing data..');

  // Show data
   dataRef.once('value', function(snapshot) {
    var data = snapshot.numChildren();
    alert('Jumlah Pasien:' + data);
  });
}
<|endoftext|>


<commit_before>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
      window.fbAsyncInit = function() {
    Parse.FacebookUtils.init({ // this line replaces FB.init({
      appId      : '971388552927772', // Facebook App ID
      status     : true,  // check Facebook Login status
      cookie     : true,  // enable cookies to allow Parse to access the session
      xfbml      : true,  // initialize Facebook social plugins on the page
      version    : 'v2.3' // point to the latest Facebook Graph API version
    });

        // Run code after the Facebook SDK is loaded
  };

function checkLoginState() {
      Parse.FacebookUtils.logIn(null, {
            success: function(user) {
                  if (!user.existed()) {
                        alert("User signed up and logged in through Facebook!");
                  } else {
                        alert("User logged in through Facebook!");
                  }
            },
            error: function(user, error) {
                  alert("User cancelled the Facebook login or did not fully authorize.");
            }
      });
}

      (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
<commit_msg>Update main.js<commit_after>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
      window.fbAsyncInit = function() {
    Parse.FacebookUtils.init({ // this line replaces FB.init({
      appId      : '971388552927772', // Facebook App ID
      status     : true,  // check Facebook Login status
      cookie     : true,  // enable cookies to allow Parse to access the session
      xfbml      : true,  // initialize Facebook social plugins on the page
      version    : 'v2.3' // point to the latest Facebook Graph API version
    });

        // Run code after the Facebook SDK is loaded
  };

function checkLoginState() {
      if (typeof FB !== 'undefined') {
            Parse.FacebookUtils.logIn(null, {
                  success: function(user) {
                        if (!user.existed()) {
                              alert("User signed up and logged in through Facebook!");
                        } else {
                              alert("User logged in through Facebook!");
                        }
                  },
                  error: function(user, error) {
                        alert("Please login to access the Locaholic services!!");
                  }
            });
      }
      else{
            alert("Your network does not support FaceBook Login!!")
      }
}

      (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
<|endoftext|>


<commit_before>/* **********************************************
 * This project will allow a user to select a file,
 * and a type of encryption, and then see what effects
 * the encryption has on the file.
 *
 * Author: Matthew Shrider
 * **********************************************/

/* Get our "before" canvas */
var before=document.getElementById("img1");
before.width = 300;
before.height = 300;
var beforectx = before.getContext("2d");

var encrypting = true;

/* Get our visible canvas */
var can=document.getElementById("img2");
can.width = 300;
can.height = 300;
var ctx=can.getContext("2d");

/* Create an invisible canvas for saving files in the full size */
var offscreen = document.createElement('canvas');
var ctxoff=offscreen.getContext("2d");

var imgData;

function fileChanged(e) {
   console.log(e);
   var files = e.target.files;

   readFile(files[0]);
}

//add listener to the upload button
var uploadButton = document.getElementById('filechooser');
uploadButton.addEventListener('change', fileChanged, false);
save.addEventListener('click', function(){
   var dataURL = can.toDataURL("image/png");
   window.open(dataURL);
}, false);

/* Gets the file URL of a dropped file onto the page */
function droppedFile(e) {
   console.log(e);
   e.stopPropagation();
   e.preventDefault();

   var files = e.dataTransfer.files;
   readFile(files[0]);
}

/* Stylizes the drop effect of dropping a file onto the page */
function draggedFile(e) {
   e.stopPropagation();
   e.preventDefault();
   e.dataTransfer.dropEffect = 'copy';
}

//add drop listener to container for listeners to be called
var dropElement = document.getElementById('container');
dropElement.addEventListener('dragover', draggedFile, false);
dropElement.addEventListener('drop', droppedFile, false);

// Toggle encrypting variable
$("#encrypt, #decrypt").change(function (){
   encrypting = $("#encrypt")[0].checked;
   console.log(encrypting);
});

/* load the opened file into the website (img1) */
function readFile(file){

   var reader = new FileReader();

   reader.onload = (function(theFile) {
      return function(e) {

         /* After loading, create and draw the images */
         createContext(e.target.result);
      };
      })(file);

   reader.readAsDataURL(file);
}

/* This function creates our drawing elements, and will draw both the
 * before image, and the after image to the screen */
function createContext(imgurl){
   console.log(imgurl);

   /* Create an image object from our data url (from reader) */
   var image = new Image();
   image.src=imgurl;

   beforectx.drawImage(image, 0, 0, 300, 300);
   ctxoff.drawImage(image, 0, 0);

   /* Before drawing, apply a cipher to the second image */
   imgData = beforectx.getImageData(0,0, before.width, before.height);

   drawEncryption();
}

/* Helper function chooses which encryption type to use */
function drawEncryption(){

   var red = parseInt($("#redshift").val());
   var blue = parseInt($("#blueshift").val());
   var green = parseInt($("#greenshift").val());

   document.getElementById("output").innerHTML = red + ", " + green + ", " + blue;

   var data = beforectx.getImageData(0, 0, before.width, before.height);

   console.log(data);
   if (data.data.length != 0){
      switch($("#selector").val()){
         case("caesar"):
               ctx.putImageData(shiftCipher(data, red, green, blue), 0, 0);
         break;
         case("affine"):
         break;
         case("vigenere"):
         break;
         case("aes"):
         break;
         default:
         console.log("Yur dumb u haker");
      }
   }
}

/* Add the draw function to the range inputs */
document.getElementById("redshift").addEventListener('change', drawEncryption, false);
document.getElementById("greenshift").addEventListener('change', drawEncryption, false);
document.getElementById("blueshift").addEventListener('change', drawEncryption, false);

/* **********************************************************
 * begin functions
 * *********************************************************/

function shiftCipher(data, keyred, keygreen, keyblue) {
   console.log(keyred, keygreen, keyblue);

   // Encrypt
   if (encrypting){
      for (var i=0; i<data.data.length; i+=4){

         data.data[i] = (data.data[i] + keyred) % 256;
         data.data[i+1] = (data.data[i+1] + keygreen) % 256;
         data.data[i+2] = (data.data[i+2] + keyblue) % 256;
      }

   }else{

      for (var i=0; i<data.data.length; i+=4){

         data.data[i] = (data.data[i] + 256 - keyred) % 256;
         data.data[i+1] = (data.data[i+1] + 256 - keygreen) % 256;
         data.data[i+2] = (data.data[i+2] + 256 - keyblue) % 256;

      }
   }

   return data;
}

<commit_msg>Added new caesar cipher with one key<commit_after>/* **********************************************
 * This project will allow a user to select a file,
 * and a type of encryption, and then see what effects
 * the encryption has on the file.
 *
 * Author: Matthew Shrider
 * **********************************************/

/* Get our "before" canvas */
var before=document.getElementById("img1");
before.width = 300;
before.height = 300;
var beforectx = before.getContext("2d");

var encrypting = true;

/* Get our visible canvas */
var can=document.getElementById("img2");
can.width = 300;
can.height = 300;
var ctx=can.getContext("2d");

/* Create an invisible canvas for saving files in the full size */
var offscreen = document.createElement('canvas');
var ctxoff=offscreen.getContext("2d");

var imgData;

function fileChanged(e) {
   console.log(e);
   var files = e.target.files;

   readFile(files[0]);
}

//add listener to the upload button
var uploadButton = document.getElementById('filechooser');
uploadButton.addEventListener('change', fileChanged, false);
save.addEventListener('click', function(){
   var dataURL = can.toDataURL("image/png");
   window.open(dataURL);
}, false);

function changeCipher(){
   console.log("changing cipher");
   var div = $('#sliders')[0];
   console.log(div);
   switch ($('#selector').val()){
      case("caesar"):
      break;
      case("affine"):
         div.innerHTML = "<input type='range' name='red' min='0' max='16581375' id='redshift' value='10'>"
         $('#redshift').change(drawEncryption);
         console.log("it changed, dummy");
      break;
      case("vigenere"):
      break;
      case("aes"):
      break;
      default:
         console.log("Yur dumb u haker");
   }

}
//add listener to combo box
$('#selector').change(changeCipher);

/* Gets the file URL of a dropped file onto the page */
function droppedFile(e) {
   console.log(e);
   e.stopPropagation();
   e.preventDefault();

   var files = e.dataTransfer.files;
   readFile(files[0]);
}

/* Stylizes the drop effect of dropping a file onto the page */
function draggedFile(e) {
   e.stopPropagation();
   e.preventDefault();
   e.dataTransfer.dropEffect = 'copy';
}

//add drop listener to container for listeners to be called
var dropElement = document.getElementById('container');
dropElement.addEventListener('dragover', draggedFile, false);
dropElement.addEventListener('drop', droppedFile, false);

// Toggle encrypting variable
$("#encrypt, #decrypt").change(function (){
   encrypting = $("#encrypt")[0].checked;
   console.log(encrypting);
});

/* load the opened file into the website (img1) */
function readFile(file){

   var reader = new FileReader();

   reader.onload = (function(theFile) {
      return function(e) {

         /* After loading, create and draw the images */
         createContext(e.target.result);
      };
      })(file);

   reader.readAsDataURL(file);
}

/* This function creates our drawing elements, and will draw both the
 * before image, and the after image to the screen */
function createContext(imgurl){
   console.log(imgurl);

   /* Create an image object from our data url (from reader) */
   var image = new Image();
   image.src=imgurl;

   beforectx.drawImage(image, 0, 0, 300, 300);
   ctxoff.drawImage(image, 0, 0);

   /* Before drawing, apply a cipher to the second image */
   imgData = beforectx.getImageData(0,0, before.width, before.height);

   drawEncryption();
}

/* Helper function chooses which encryption type to use */
function drawEncryption(){

   var data = beforectx.getImageData(0, 0, before.width, before.height);

   console.log(data);
   if (data.data.length != 0){
      switch($("#selector").val()){
         case("caesar"):
            var red = parseInt($("#redshift").val());
            var blue = parseInt($("#blueshift").val());
            var green = parseInt($("#greenshift").val());

            document.getElementById("output").innerHTML = red + ", " + green + ", " + blue;
            ctx.putImageData(shiftCipher(data, red, green, blue), 0, 0);
         break;
         case("affine"):
            var key = parseInt($('#redshift').val());
            ctx.putImageData(affineCipher(data, key), 0, 0);
         break;
         case("vigenere"):
         break;
         case("aes"):
         break;
         default:
         console.log("Yur dumb u haker");
      }
   }
}

/* Add the draw function to the range inputs */
document.getElementById("redshift").addEventListener('change', drawEncryption, false);
document.getElementById("greenshift").addEventListener('change', drawEncryption, false);
document.getElementById("blueshift").addEventListener('change', drawEncryption, false);

/* **********************************************************
 * begin functions
 * *********************************************************/

function shiftCipher(data, keyred, keygreen, keyblue) {
   console.log(keyred, keygreen, keyblue);

   // Encrypt
   if (encrypting){
      for (var i=0; i<data.data.length; i+=4){

         data.data[i] = (data.data[i] + keyred) % 256;
         data.data[i+1] = (data.data[i+1] + keygreen) % 256;
         data.data[i+2] = (data.data[i+2] + keyblue) % 256;
      }

   }else{

      for (var i=0; i<data.data.length; i+=4){

         data.data[i] = (data.data[i] + 256 - keyred) % 256;
         data.data[i+1] = (data.data[i+1] + 256 - keygreen) % 256;
         data.data[i+2] = (data.data[i+2] + 256 - keyblue) % 256;

      }
   }

   return data;
}

function affineCipher(data, key) {
   if (encrypting){
      for (var i=0; i<data.data.length; i+=4){
         data.data[i] = (data.data[i] + (key & 255)) % 256;
         data.data[i+1] = (data.data[i+1] + ((key >> 8) & 255)) % 256;
         data.data[i+2] = (data.data[i+2] + ((key >> 16) & 255)) % 256;
      }
   } else {

   }

   return data;
}

<|endoftext|>


<commit_before>"use strict";

/**
 * Lightweight Console
 *
 * @param consoleDiv dom of div holding the console
 * @param consoleOutDOM dom of text-area for console-output
 * @param consoleInDOM dom of text-input for console-input
 * @param hostname included in motd, may have further use in the future
 * @constructor
 */
function LWConsole(consoleDiv, consoleOutDOM, consoleInDOM, hostname) {
    let consoleOut = "";
    let motd = "Welcome to " + hostname + "!\nType 'help' for help.\n";
    let isInverted = false;
    let commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "ip",
            description: "Lookup an IP: Usage: ip [ip] (queries your IP if no argument is provided)",
            visible: true,
            handler: ipCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                isInverted = !isInverted;
                invert(isInverted);
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("display") === "flex";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            e.preventDefault();
            let value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================
    /**
     * Changes visibility of console-div depending on parameter
     * @param state boolean true = visible; false = hidden
     */
    this.show = function (state) {
        if (state) {
            consoleDiv.style.display = "flex";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.display = "none";
            this.visible = false;
        }
    };

    /**
     * Getter for visibility state
     * @returns {boolean}
     */
    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        let splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    /**
     * Takes command as array and calls corresponding cmd-handler on match
     * @param cmd command-array. cmd[0] is command name, cmd[>1] is parameter
     * @returns {String} result of command
     */
    function executeCMD(cmd) {
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].name === cmd[0].toLowerCase()) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[i].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        let msg = "Available commands:";
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].visible) {
                msg += "\n" + commands[i].name + ": " + commands[i].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        let init = true;
        let str = "";

        for (let i = 0; i < args.length; i++) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[i];
        }
        return str;
    }

    function ipCMD(args) {
        let queryUrl = "https://ipinfo.io/";

        if (args.length > 1) {
            return "Invalid Syntax! ip [addr]";
        }
        else {
            if (args.length === 1) { //one arg => query arg ip
                queryUrl += args[0] + "/"
            }
        }

        queryUrl += "json";

        let request = new XMLHttpRequest();
        request.onload = function () {
            if (request.status !== 200) {
                print("\nError: ipinfo.io returned code " + request.status);
            }
            print(request.responseText);
        };
        request.onerror = function (e) {
            console.error(e);
            print("Error: Could not send request to ipinfo.io. Check your internet connection.");
        };
        request.open("GET", queryUrl, true);
        request.send();
        return "Getting data ...";
    }

    function invert(state) {
        let invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }
}

function JSUtil() {
    let lwConsole = new LWConsole(
        document.getElementById("lwConsole"),
        document.getElementById("consoleOut"),
        document.getElementById("consoleIn"),
        window.location.hostname
    );

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    };

    /**
     * Handler for  console shortcuts 'C'=> open and 'ESC'=> close
     */
    document.addEventListener("keydown", function (e) {
        if (!lwConsole.isVisible() && e.keyCode == 67) {
            e.preventDefault();
            lwConsole.show(true);
        }
        else if (lwConsole.isVisible() && e.keyCode == 27) {
            e.preventDefault();
            lwConsole.show(false);
        }

    });
}
let util = new JSUtil();<commit_msg>added easter-egg commands<commit_after>"use strict";

/**
 * Lightweight Console
 *
 * @param consoleDiv dom of div holding the console
 * @param consoleOutDOM dom of text-area for console-output
 * @param consoleInDOM dom of text-input for console-input
 * @param hostname included in motd, may have further use in the future
 * @constructor
 */
function LWConsole(consoleDiv, consoleOutDOM, consoleInDOM, hostname) {
    let consoleOut = "";
    let motd = "Welcome to " + hostname + "!\nType 'help' for help.\n";
    let isInverted = false;
    let commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "ip",
            description: "Lookup an IP: Usage: ip [ip] (queries your IP if no argument is provided)",
            visible: true,
            handler: ipCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                isInverted = !isInverted;
                invert(isInverted);
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        },
        {
            name: "shutdown",
            description: "",
            visible: false,
            handler: function () {
                return "You're not my master!";
            }
        },
        {
            name: "make_me_a_sandwich",
            description: "<3 xkcd",
            visible: false,
            handler: function () {
                return "Make it yourself!";
            }
        },
        {
            name: "rm",
            description: "",
            visible: false,
            handler: function () {
                return "Please don't delete anything. We don't have any backups.";
            }
        },
        {
            name: "ls",
            description: "",
            visible: false,
            handler: function () {
                return "cia_secrets, cute_cat_gifs, videos, passwords.txt";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("display") === "flex";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            e.preventDefault();
            let value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================
    /**
     * Changes visibility of console-div depending on parameter
     * @param state boolean true = visible; false = hidden
     */
    this.show = function (state) {
        if (state) {
            consoleDiv.style.display = "flex";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.display = "none";
            this.visible = false;
        }
    };

    /**
     * Getter for visibility state
     * @returns {boolean}
     */
    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        let splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    /**
     * Takes command as array and calls corresponding cmd-handler on match
     * @param cmd command-array. cmd[0] is command name, cmd[>1] is parameter
     * @returns {String} result of command
     */
    function executeCMD(cmd) {
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].name === cmd[0].toLowerCase()) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[i].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        let msg = "Available commands:";
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].visible) {
                msg += "\n" + commands[i].name + ": " + commands[i].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        let init = true;
        let str = "";

        for (let i = 0; i < args.length; i++) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[i];
        }
        return str;
    }

    function ipCMD(args) {
        let queryUrl = "https://ipinfo.io/";

        if (args.length > 1) {
            return "Invalid Syntax! ip [addr]";
        }
        else {
            if (args.length === 1) { //one arg => query arg ip
                queryUrl += args[0] + "/"
            }
        }

        queryUrl += "json";

        let request = new XMLHttpRequest();
        request.onload = function () {
            if (request.status !== 200) {
                print("\nError: ipinfo.io returned code " + request.status);
            }
            print(request.responseText);
        };
        request.onerror = function (e) {
            console.error(e);
            print("Error: Could not send request to ipinfo.io. Check your internet connection.");
        };
        request.open("GET", queryUrl, true);
        request.send();
        return "Getting data ...";
    }

    function invert(state) {
        let invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }
}

function JSUtil() {
    let lwConsole = new LWConsole(
        document.getElementById("lwConsole"),
        document.getElementById("consoleOut"),
        document.getElementById("consoleIn"),
        window.location.hostname
    );

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    };

    /**
     * Handler for  console shortcuts 'C'=> open and 'ESC'=> close
     */
    document.addEventListener("keydown", function (e) {
        if (!lwConsole.isVisible() && e.keyCode == 67) {
            e.preventDefault();
            lwConsole.show(true);
        }
        else if (lwConsole.isVisible() && e.keyCode == 27) {
            e.preventDefault();
            lwConsole.show(false);
        }

    });
}
let util = new JSUtil();<|endoftext|>


<commit_before>'use strict';

function repo_init(){
    core_repo_init({
      'audios': {
        'boop': {
          'duration': .1,
        },
      },
      'events': {
        'start-button': {
          'onclick': function(){
              core_escape();
              start();
          },
        },
      },
      'globals': {
        'game_running': false,
        'score': 0,
        'time': 0,
      },
      'info': '<input id=start-button type=button value=Restart>',
      'keybinds': {
        72: {
          'todo': function(){
              stop();
              start();
          },
        },
      },
      'menu': true,
      'storage': {
        'game-mode': 1,
        'grid-dimensions': 5,
        'max': 30,
        'negative-frequency': 1,
        'negative-onclick': 0,
        'negative-points': -1,
        'positive-frequency': 1,
        'positive-points': 1,
      },
      'storage-menu': '

<select id=grid-dimensions><option value=1>1x1</option><option value=2>2x2</option><option value=3>3x3</option><option value=4>4x4</option><option value=5>5x5</option></select>Dimensions
<input id=max>Max <select id=game-mode><option value=0>Points</option><option value=1>Time</option></select>
<input id=negative-frequency>Negative Frequency
<input id=negative-points>Negative Points
<select id=negative-onclick><option value=0>Lose Points</option><option value=1>End Game</option></select>Negative Click
<input id=positive-frequency>Positive Frequency
<input id=positive-points>Positive Points
',
      'title': 'SpeedButton.htm',
    });

    // Create game-div buttons.
    var dimensions = core_storage_data['grid-dimensions'] * core_storage_data['grid-dimensions'];
    var output = '';
    for(var loop_counter = 0; loop_counter < dimensions; loop_counter++){
        if(loop_counter % core_storage_data['grid-dimensions'] === 0
          && loop_counter !== 0){
            output += '
';
        }

        output += '<input class=gridbuttonclickable disabled id=' + loop_counter
          + ' onclick=click_button(' + loop_counter
          + ') type=button value=" ">';
    }
    document.getElementById('game-div').innerHTML = output + '
';

    var loop_counter = dimensions - 1;
    do{
        document.getElementById(loop_counter).style.background = '#2a2a2a';
    }while(loop_counter--);
}
<commit_msg>improved storage order<commit_after>'use strict';

function repo_init(){
    core_repo_init({
      'audios': {
        'boop': {
          'duration': .1,
        },
      },
      'events': {
        'start-button': {
          'onclick': function(){
              core_escape();
              start();
          },
        },
      },
      'globals': {
        'game_running': false,
        'score': 0,
        'time': 0,
      },
      'info': '<input id=start-button type=button value=Restart>',
      'keybinds': {
        72: {
          'todo': function(){
              stop();
              start();
          },
        },
      },
      'menu': true,
      'storage': {
        'game-mode': 1,
        'grid-dimensions': 5,
        'max': 30,
        'negative-frequency': 1,
        'negative-onclick': 0,
        'negative-points': -1,
        'positive-frequency': 1,
        'positive-points': 1,
      },
      'storage-menu': '

<select id=grid-dimensions><option value=1>1x1</option><option value=2>2x2</option><option value=3>3x3</option><option value=4>4x4</option><option value=5>5x5</option></select>Dimensions
<input id=max>Max <select id=game-mode><option value=0>Points</option><option value=1>Time</option></select>
<select id=negative-onclick><option value=0>Lose Points</option><option value=1>End Game</option></select>Negative Click
<input id=negative-frequency>Negative Frequency
<input id=negative-points>Negative Points
<input id=positive-frequency>Positive Frequency
<input id=positive-points>Positive Points
',
      'title': 'SpeedButton.htm',
    });

    // Create game-div buttons.
    var dimensions = core_storage_data['grid-dimensions'] * core_storage_data['grid-dimensions'];
    var output = '';
    for(var loop_counter = 0; loop_counter < dimensions; loop_counter++){
        if(loop_counter % core_storage_data['grid-dimensions'] === 0
          && loop_counter !== 0){
            output += '
';
        }

        output += '<input class=gridbuttonclickable disabled id=' + loop_counter
          + ' onclick=click_button(' + loop_counter
          + ') type=button value=" ">';
    }
    document.getElementById('game-div').innerHTML = output + '
';

    var loop_counter = dimensions - 1;
    do{
        document.getElementById(loop_counter).style.background = '#2a2a2a';
    }while(loop_counter--);
}
<|endoftext|>