<commit_before>define('app/views/machine_list_item', [
    'text!app/templates/machine_list_item.html','ember'],
    /**
     *
     * Machine List Item View
     *
     * @returns Class
     */
    function(machine_list_item_html) {
        return Ember.View.extend({
                tagName:false,

                fetchLoadavg: function(machine){
                    if (machine.hasMonitoring){
                        var uri = URL_PREFIX + '/backends/' + machine.backend.id + '/machines/' + machine.id + '/loadavg.png';
                        var bgimage = new Image();
                        var timestamp = new Date().getTime();
                        bgimage.src = uri + '?' + timestamp + '&auth_key=' + Mist.auth_key;
                        // update load graph after the image is loaded
                        bgimage.onload = function () {
                           $('#' + machine.id + ' span.monitoring-icon').css('background-image', 'url(' + bgimage.src + ')');
                        };
                        timestamp = new Date().getTime();
                    }
                },

                didInsertElement: function(){
                    $('#machines-list').listview('refresh');
                    $("#machines-list").trigger('create');
                    var machine = this.machine;
                    setInterval(this.fetchLoadavg, 4*60*1000, machine);
                    if (this.machine.isGhost){
                        this.switchToGhost();
                    }
                },

                disabledMonitoringClass: function() {
                    var machine = this.machine;
                    if (machine && machine.hasMonitoring) {
                        this.fetchLoadavg(machine);
                        return '';
                    } else {
                        return 'ui-disabled';
                    }
                }.property('machine.hasMonitoring'),

                machineSelected: function(){
                    var len = 0;

                    Mist.backendsController.forEach(function(backend) {
                        backend.machines.forEach(function(machine) {
                            if (machine.selected){
                        	len++;
                            }
                        });
                    });

                    if (len > 1) {
                        $('.machines-footer').fadeIn(140);
                        $('.machines #footer-console').addClass('ui-disabled');
                    } else if (len == 1) {
                        $('.machines-footer').fadeIn(140);
                        $('.machines #footer-console').removeClass('ui-disabled');
                    } else {
                        $('.machines-footer').fadeOut(200);
                    }

                }.observes('machine.selected'),

                switchToGhost: function() {
                    $('#machines-list a[href="#/machines/' + this.machine.name + '"]').eq(0)
                    .removeAttr('href')
                    .attr('id', this.machine.name)
                    .parent().addClass('ghost-machine');
                },

                disassociateGhostMachine: function() {
                    var key = this.get('controller').get('model');
                    Mist.keysController.disassociateKey(key, this.machine);
                    $('#machines-list a[id="' + this.machine.name + '"]').eq(0).parent().parent().parent().remove();
                },

                template: Ember.Handlebars.compile(machine_list_item_html),
        });

    }
);
<commit_msg>Add confirmation dialog for ghost machine disassociation<commit_after>define('app/views/machine_list_item', [
    'text!app/templates/machine_list_item.html','ember'],
    /**
     *
     * Machine List Item View
     *
     * @returns Class
     */
    function(machine_list_item_html) {
        return Ember.View.extend({
                tagName:false,

                fetchLoadavg: function(machine){
                    if (machine.hasMonitoring){
                        var uri = URL_PREFIX + '/backends/' + machine.backend.id + '/machines/' + machine.id + '/loadavg.png';
                        var bgimage = new Image();
                        var timestamp = new Date().getTime();
                        bgimage.src = uri + '?' + timestamp + '&auth_key=' + Mist.auth_key;
                        // update load graph after the image is loaded
                        bgimage.onload = function () {
                           $('#' + machine.id + ' span.monitoring-icon').css('background-image', 'url(' + bgimage.src + ')');
                        };
                        timestamp = new Date().getTime();
                    }
                },

                didInsertElement: function(){
                    $('#machines-list').listview('refresh');
                    $("#machines-list").trigger('create');
                    var machine = this.machine;
                    setInterval(this.fetchLoadavg, 4*60*1000, machine);
                    if (this.machine.isGhost){
                        this.switchToGhost();
                    }
                },

                disabledMonitoringClass: function() {
                    var machine = this.machine;
                    if (machine && machine.hasMonitoring) {
                        this.fetchLoadavg(machine);
                        return '';
                    } else {
                        return 'ui-disabled';
                    }
                }.property('machine.hasMonitoring'),

                machineSelected: function(){
                    var len = 0;

                    Mist.backendsController.forEach(function(backend) {
                        backend.machines.forEach(function(machine) {
                            if (machine.selected){
                        	len++;
                            }
                        });
                    });

                    if (len > 1) {
                        $('.machines-footer').fadeIn(140);
                        $('.machines #footer-console').addClass('ui-disabled');
                    } else if (len == 1) {
                        $('.machines-footer').fadeIn(140);
                        $('.machines #footer-console').removeClass('ui-disabled');
                    } else {
                        $('.machines-footer').fadeOut(200);
                    }

                }.observes('machine.selected'),

                switchToGhost: function() {
                    $('#machines-list a[href="#/machines/' + this.machine.name + '"]').eq(0)
                    .removeAttr('href')
                    .attr('id', this.machine.name)
                    .parent().addClass('ghost-machine');
                },

                disassociateGhostMachine: function() {
                    var that = this;
                    Mist.confirmationController.set('title', 'Disassociate Ghost Machine');
                    Mist.confirmationController.set('text', 'Are you sure you want to disassociate ' + this.machine.name + ' ?');
                    Mist.confirmationController.set('callback', function() {
                        var key = that.get('controller').get('model');
                        Mist.keysController.disassociateKey(key, that.machine);
                        $('#machines-list a[id="' + that.machine.name + '"]').eq(0).parent().parent().parent().remove();
                    });
                    Mist.confirmationController.set('fromDialog', true);
                    Mist.confirmationController.show();
                },

                template: Ember.Handlebars.compile(machine_list_item_html),
        });

    }
);
<|endoftext|>


<commit_before>(function() {
    var app = angular.module('workStore', []);

    // app.filter('checks', function() {
    //   return function
    // });
    app.filter('unsafe', function($sce) {
        return function(val) {
            return $sce.trustAsHtml(val);
        };
    });

    app.filter('dateSplit', function() {
        return function(val) {
            if (val === 'Present') {
                return 'Present';
            }
            var split = val.split(',');
            var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep"];
            return months[split[1]-1] + " " + split[2] + ", " + split[0];
        };
    });

    app.controller('StoreController', function($scope){
        $scope.works = details;
        $scope.selected = {
            item: $scope.works[0]
        };
    });

    var details = [
        {
            "startDate":"2020,7,7",
            "endDate":"2021,7,7",
            "headline":"HBO",
            "title": "Staff Software Engineer, Direct Commerce and Subscriber Lifecycle\nSr Software Engineer, Direct Commerce and Subscriber Lifecycl",
            "location": "Seattle, WA",
            "text":"Lead cross team feature crews for the international expansion of HBO Commerce Services into LATAM and EU.\nDesigned multi-stack architectures to create the first in house credit card processing and billing system.\nDeveloped internal tooling to help the organization make the move to using OpenAPI for build and testing systems",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2018,7,7",
            "endDate":"2020,7,7",
            "headline":"HBO",
            "title": "Software Engineer II,  Direct Commerce ",
            "location": "Seattle, WA",
            "text":"Lead a small team over a span of 2 months to design and reestablish an end to end commerce system using Stripe.\nDeveloped systems to interact with existing third party commerce solutions and built accompanying financial tooling.\nDesign and execute large scale load testing for commerce services to enable subscriber signups for Game of Thrones.\nUtilized SQL and Python to generate data visualizations for data-driven system and product improvements",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2017,8,7",
            "endDate":"2018,7,7",
            "headline":"HBO",
            "title": "Software Engineer I, In App Commerce ",
            "location": "Seattle, WA",
            "text":"Working on backend services with the Purchase and Identity team, focussing on interaction with payment providers, billing databases and testing.",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2016,6,13",
            "endDate":"2015,8,19",
            "headline":"HBO",
            "title": "Software Engineering Intern",
            "location": "New York City, NY",
            "text":"Worked on the User and Accounts team. Developed new authentication strategies for internal service communication. Improved validation across all services to meet HBO standards. Created project plans for intern project as well as future projects stemming from the summer project.",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2015,6,15",
            "endDate":"2015,8,28",
            "headline":"Shippable",
            "title": "Software Engineering Intern",
            "location": "Seattle, WA",
            "text":"Worked in a group of 4 front and back-end interns and helped in post-development fixes and changes for the Shippable 3.0 platform, used Angular and Node, working on multi-stack.",
            "asset":
            {
                "media":"/images/shippable.png",
                "thumbnail":"/images/shippablethumb.png",
                "caption":"Shippable"
            }
        },
        {
            "startDate":"2014,7,2",
            "endDate":"2014,8,15",
            "headline":"IBM",
            "title": "Software Marketing Intern",
            "location": "Mumbai, India",
            "text":"Created marketing and competitive reports on various IBM products/services (Cognos BI, SPSS). Created personas of various executive officers from companies in the IBM client list. Generated reports for Watson, its use cases and possible companies under the current client list which can use Watson to benefit their industry along with possible efficiency changes.",
            "asset":
            {
                "media":"/images/ibmmain.gif",
                "thumbnail":"/images/ibmthumb.png",
                "caption":"IBM"
            }
        },
        {
            "startDate":"2013,6,7",
            "endDate":"2013,6,31",
            "headline":"Fine 'Linnen' Company",
            "location": "Mumbai, India",
            "title": "Web Developer",
            "text":"
Helped redesign the company website according specification provided by the CEO. The company is in the business of bed and bath linen for hotels and other chains.",
            "asset":
            {
                "media":"/images/flcmain.png",
                "thumbnail":"/images/flcthumb.png",
                "caption":"Fine 'Linnen' Company"
            }
        },
        {
            "startDate":"2012,7,2",
            "endDate":"2012,8,15",
            "headline":"VMware",
            "location": "Singapore",
            "title": "Consulting and Developing Intern",
            "text":"Used previously learnt Java knowledge to learn different Application Programming Interfaces and create a log in system and alarm to read the data from different VMs (virtual machines). Assisted a group of consultants to learn the benefits of using virtualization as well as joined in on to the VMSTART, a program for the new recruits.",
            "asset":{
                "media":"/images/vmware.png",
                "thumbnail":"/images/vmthumb.png",
                "caption":"VMware"
            }
        },
        {
            "startDate":"2012,6,7",
            "endDate":"2012,6,30",
            "headline":"Datamatics Global Services",
            "location": "Mumbai, India",
            "title": "Consulting and Developing Intern",
            "text":"Completed a course in learning Android programming alongside the ‘Sencha’ Platform, as well as iOS application programming, and applied them successfully in the assignments given. Assisted in designing and mobile enabling an e-Process Manager with a single sign on for Android, iOS and BB-OS devices.",
            "asset":
            {
                "media":"/images/datamatics.png",
                "thumbnail":"/images/datamaticsthumb.png",
                "caption":"Datamatics: GSS"
            }
        },
        {
            "startDate":"2011,5,1",
            "endDate":"2011,9,30",
            "headline":"Harvard Model United Nations",
            "location": "Mumbai, India",
            "title": "Business, Revenue and Social Media Intern",
            "text":"Member of hotel relations team for the conference; helped market rooms and organized transport for MUN attendees. In charge of designing merchandise and creating a 5-month social media marketing plan to implement pre- and post-conference. Maintained relations with the hotel to manage the guests while maximizing profit",
            "asset":
            {
                "media":"/images/hmun.png",
                "thumbnail":"/images/hmunthumb.png",
                "caption":"Harvard Model United Nations"
            }
        },
        {
            "startDate":"2010,7,1",
            "endDate":"2010,7,31",
            "headline":"Viacom 18",
            "location": "Mumbai, India",
            "title": "Digital Services Intern",
            "text":"Worked in creating and editing of live data trends between hits on Media Channels and Twitter/Google for MTV. Submitted creative ideas for Social Media Marketing which were later implemented.",
            "asset":
            {
                "media":"/images/viacom18.jpg",
                "thumbnail":"/images/viacom18.jpg",
                "caption":"Viacom 18"
            }
        }
    ];
})();
<commit_msg>update positions<commit_after>(function() {
    var app = angular.module('workStore', []);

    // app.filter('checks', function() {
    //   return function
    // });
    app.filter('unsafe', function($sce) {
        return function(val) {
            return $sce.trustAsHtml(val);
        };
    });

    app.filter('dateSplit', function() {
        return function(val) {
            if (val === 'Present') {
                return 'Present';
            }
            var split = val.split(',');
            var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep"];
            return months[split[1]-1] + " " + split[2] + ", " + split[0];
        };
    });

    app.controller('StoreController', function($scope){
        $scope.works = details;
        $scope.selected = {
            item: $scope.works[0]
        };
    });

    var details = [
        {
            "startDate":"2020,8,7",
            "endDate":"2021,7,7",
            "headline":"HBO",
            "title": "Staff Software Engineer
Sr Software Engineer, Direct Commerce and Subscriber Lifecycle",
            "location": "Seattle, WA",
            "text":"Lead cross team feature crews for the international expansion of HBO Commerce Services into LATAM and EU.
Designed multi-stack architectures to create the first in house credit card processing and billing system.
Developed internal tooling to help the organization make the move to using OpenAPI for build and testing systems",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2018,7,7",
            "endDate":"2020,7,7",
            "headline":"HBO",
            "title": "Software Engineer II,  Direct Commerce ",
            "location": "Seattle, WA",
            "text":"Lead a small team over a span of 2 months to design and reestablish an end to end commerce system using Stripe.
Developed systems to interact with existing third party commerce solutions and built accompanying financial tooling.
Design and execute large scale load testing for commerce services to enable subscriber signups for Game of Thrones.
Utilized SQL and Python to generate data visualizations for data-driven system and product improvements",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2017,8,7",
            "endDate":"2018,7,7",
            "headline":"HBO",
            "title": "Software Engineer I, In App Commerce ",
            "location": "Seattle, WA",
            "text":"Working on backend services with the Purchase and Identity team, focussing on interaction with payment providers, billing databases and testing.",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2016,6,13",
            "endDate":"2015,8,19",
            "headline":"HBO",
            "title": "Software Engineering Intern",
            "location": "New York City, NY",
            "text":"Worked on the User and Accounts team. Developed new authentication strategies for internal service communication. Improved validation across all services to meet HBO standards. Created project plans for intern project as well as future projects stemming from the summer project.",
            "asset":
            {
                "media":"/images/hbo.png",
                "thumbnail":"/images/hbothumb.png",
                "caption":"HBO"
            }
        },
        {
            "startDate":"2015,6,15",
            "endDate":"2015,8,28",
            "headline":"Shippable",
            "title": "Software Engineering Intern",
            "location": "Seattle, WA",
            "text":"Worked in a group of 4 front and back-end interns and helped in post-development fixes and changes for the Shippable 3.0 platform, used Angular and Node, working on multi-stack.",
            "asset":
            {
                "media":"/images/shippable.png",
                "thumbnail":"/images/shippablethumb.png",
                "caption":"Shippable"
            }
        },
        {
            "startDate":"2014,7,2",
            "endDate":"2014,8,15",
            "headline":"IBM",
            "title": "Software Marketing Intern",
            "location": "Mumbai, India",
            "text":"Created marketing and competitive reports on various IBM products/services (Cognos BI, SPSS). Created personas of various executive officers from companies in the IBM client list. Generated reports for Watson, its use cases and possible companies under the current client list which can use Watson to benefit their industry along with possible efficiency changes.",
            "asset":
            {
                "media":"/images/ibmmain.gif",
                "thumbnail":"/images/ibmthumb.png",
                "caption":"IBM"
            }
        },
        {
            "startDate":"2013,6,7",
            "endDate":"2013,6,31",
            "headline":"Fine 'Linnen' Company",
            "location": "Mumbai, India",
            "title": "Web Developer",
            "text":"
Helped redesign the company website according specification provided by the CEO. The company is in the business of bed and bath linen for hotels and other chains.",
            "asset":
            {
                "media":"/images/flcmain.png",
                "thumbnail":"/images/flcthumb.png",
                "caption":"Fine 'Linnen' Company"
            }
        },
        {
            "startDate":"2012,7,2",
            "endDate":"2012,8,15",
            "headline":"VMware",
            "location": "Singapore",
            "title": "Consulting and Developing Intern",
            "text":"Used previously learnt Java knowledge to learn different Application Programming Interfaces and create a log in system and alarm to read the data from different VMs (virtual machines). Assisted a group of consultants to learn the benefits of using virtualization as well as joined in on to the VMSTART, a program for the new recruits.",
            "asset":{
                "media":"/images/vmware.png",
                "thumbnail":"/images/vmthumb.png",
                "caption":"VMware"
            }
        },
        {
            "startDate":"2012,6,7",
            "endDate":"2012,6,30",
            "headline":"Datamatics Global Services",
            "location": "Mumbai, India",
            "title": "Consulting and Developing Intern",
            "text":"Completed a course in learning Android programming alongside the ‘Sencha’ Platform, as well as iOS application programming, and applied them successfully in the assignments given. Assisted in designing and mobile enabling an e-Process Manager with a single sign on for Android, iOS and BB-OS devices.",
            "asset":
            {
                "media":"/images/datamatics.png",
                "thumbnail":"/images/datamaticsthumb.png",
                "caption":"Datamatics: GSS"
            }
        },
        {
            "startDate":"2011,5,1",
            "endDate":"2011,9,30",
            "headline":"Harvard Model United Nations",
            "location": "Mumbai, India",
            "title": "Business, Revenue and Social Media Intern",
            "text":"Member of hotel relations team for the conference; helped market rooms and organized transport for MUN attendees. In charge of designing merchandise and creating a 5-month social media marketing plan to implement pre- and post-conference. Maintained relations with the hotel to manage the guests while maximizing profit",
            "asset":
            {
                "media":"/images/hmun.png",
                "thumbnail":"/images/hmunthumb.png",
                "caption":"Harvard Model United Nations"
            }
        },
        {
            "startDate":"2010,7,1",
            "endDate":"2010,7,31",
            "headline":"Viacom 18",
            "location": "Mumbai, India",
            "title": "Digital Services Intern",
            "text":"Worked in creating and editing of live data trends between hits on Media Channels and Twitter/Google for MTV. Submitted creative ideas for Social Media Marketing which were later implemented.",
            "asset":
            {
                "media":"/images/viacom18.jpg",
                "thumbnail":"/images/viacom18.jpg",
                "caption":"Viacom 18"
            }
        }
    ];
})();
<|endoftext|>


<commit_before>"use strict";
const assert = require('chai').assert;

describe("geek value equals 42", () => {
  let geek = 42;
  it("should return 42", () => {
    assert.equal(geek, 42)
  });
});
<commit_msg>Update basic.js<commit_after>"use strict";
const assert = require('chai').assert;

describe("geek value equals 42", () => {
  let geek = 42;
  it("should return 42", () => {
    assert.equal(geek, 423)
  });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Mercator
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Google Meet Matrix Rain
// @author       Xing
// @match        https://meet.google.com/*
// @grant        none
// ==/UserScript==

(async function() {
    ‘use strict’;

    class mercatorMediaStream extends MediaStream {
        constructor(old_stream) {
            super(old_stream)

            const camera = document.createElement(‘canvas’);
            const matrix = document.createElement(‘canvas’);
            const comp = document.createElement(‘canvas’);

            const video = document.createElement(‘video’);

            // Matrix rain
            const katakana = `1234567890ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺーヽヾヿ`;

            video.setAttribute(‘playsinline’,’');
            video.setAttribute(‘autoplay’,’');

            document.body.appendChild(video);

            video.style=’position:fixed;left:0;top:0;width:50px;height:50px;z-index:9999999;background:black’;

            const constraints = {audio: false, video: true};

            video.srcObject = old_stream

            const old_stream_settings = old_stream.getVideoTracks()[0].getSettings()

            const w = old_stream_settings.width
            const h = old_stream_settings.height
            const aspect_ratio = w/h
            const r = w/64
            matrix.width = w*1.5
            matrix.height = h
            comp.width = w
            comp.height = h
            camera.width = w/r
            camera.height = h/r
            const matrix_ctx = matrix.getContext(‘2d’)
            const camera_ctx = camera.getContext(‘2d’)
            const comp_ctx = comp.getContext(‘2d’)
            matrix_ctx.font = r+’px monospace’
            matrix_ctx.textAlign = ‘center’
            matrix_ctx.translate(w*1.5, 0)
            matrix_ctx.scale(-1,1)
            camera_ctx.filter = ‘brightness(0.8) contrast(2.5)’

            matrix_ctx.fillStyle=’#020’
            matrix_ctx.fillRect(0,0,w*1.5,h)
            matrix_ctx.fillStyle = ‘#8f8’
            matrix_ctx.lineWidth = r/10
            matrix_ctx.strokeStyle = ‘#080’

            const text_offset = r/2
            for(let x = text_offset; x < w*1.5; x+=r*1.5){
                for(let y = 0; y < h; y+=r){
                    const rand_text = katakana[Math.floor(Math.random()*katakana.length)]
                    matrix_ctx.strokeText(rand_text,x,y)
                    matrix_ctx.fillText(rand_text,x,y)
                }
            }
            let rainx = 0
            let rainy = 0
            let rain_text = ['Z',text_offset,0]
            comp_ctx.imageSmoothingEnabled = false

            function draw(){

                matrix_ctx.fillStyle = ‘#020’
                matrix_ctx.fillRect(rainx,rainy,r*1.5,-r)

                matrix_ctx.strokeStyle = ‘#080’
                matrix_ctx.fillStyle = ‘#8f8’
                matrix_ctx.strokeText(…rain_text)
                matrix_ctx.fillText(…rain_text)

                rainx = Math.floor(Math.random*w/r)*r*1.5
                rainy = Math.floor(Math.random*h/r)*r
                rain_text = [
                    katakana[Math.floor(Math.random()*katakana.length)],
                    rainx+text_offset,
                    rainy
                ]

                matrix_ctx.strokeStyle = ‘#0f0’
                matrix_ctx.fillStyle = ‘#fff’
                matrix_ctx.strokeText(…rain_text)
                matrix_ctx.fillText(…rain_text)

                camera_ctx.drawImage(video, 0, 0, w/r, h/r)

                comp_ctx.clearRect(0,0,w,h)
                comp_ctx.globalCompositeOperation = ‘source_over’
                comp_ctx.drawImage(camera,0,0,w,h)
                comp_ctx.globalCompositeOperation = ‘color’
                comp_ctx.drawImage(matrix,0,0,w,h)
                comp_ctx.globalCompositeOperation = ‘multiply’
                comp_ctx.drawImage(matrix,0,0,w,h)

                requestAnimationFrame(draw)
            }
            draw()

            return comp.captureStream(10)
        }
    }

    async function newGetUserMedia(constraints) {
        if (constraints && constraints.video && !constraints.audio) {
            return new mercatorMediaStream(await navigator.mediaDevices.oldGetUserMedia(constraints))
        } else {
            return navigator.mediaDevices.oldGetUserMedia(constraints)
        }
    }
    MediaDevices.prototype.oldGetUserMedia = MediaDevices.prototype.getUserMedia
    MediaDevices.prototype.getUserMedia = newGetUserMedia

})();
<commit_msg>ideograph baseline<commit_after>// ==UserScript==
// @name         Mercator
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Google Meet Matrix Rain
// @author       Xing
// @match        https://meet.google.com/*
// @grant        none
// ==/UserScript==

(async function() {
    'use strict';

    class mercatorMediaStream extends MediaStream {
        constructor(old_stream) {
            super(old_stream)

            const camera = document.createElement('canvas');
            const matrix = document.createElement('canvas');
            const comp = document.createElement('canvas');

            const video = document.createElement('video');

            // Matrix rain
            const katakana = `1234567890ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺーヽヾヿ`;

            video.setAttribute('playsinline','');
            video.setAttribute('autoplay','');

            document.body.appendChild(video);

            video.style='position:fixed;left:0;top:0;width:50px;height:50px;z-index:9999999;background:black';

            const constraints = {audio: false, video: true};

            video.srcObject = old_stream

            const old_stream_settings = old_stream.getVideoTracks()[0].getSettings()

            const w = old_stream_settings.width
            const h = old_stream_settings.height
            const aspect_ratio = w/h
            const r = w/64
            matrix.width = w*1.5
            matrix.height = h
            comp.width = w
            comp.height = h
            camera.width = w/r
            camera.height = h/r
            const matrix_ctx = matrix.getContext('2d')
            const camera_ctx = camera.getContext('2d')
            const comp_ctx = comp.getContext('2d')
            matrix_ctx.font = 0.9*r+'px monospace'
            matrix_ctx.textAlign = 'center'
            matrix_ctx.translate(w*1.5, 0)
            matrix_ctx.scale(-1,1)
            camera_ctx.filter = 'brightness(0.8) contrast(2.5)'

            matrix_ctx.fillStyle='#020'
            matrix_ctx.fillRect(0,0,w*1.5,h)
            matrix_ctx.fillStyle = '#8f8'
            matrix_ctx.lineWidth = r/10
            matrix_ctx.strokeStyle = '#080'
            matrix_ctx.textBaseline = 'ideographic'

            const text_offset = r*1.5/2
            for(let x = text_offset; x < w*1.5; x+=r*1.5){
                for(let y = 0; y < h; y+=r){
                    const rand_text = katakana[Math.floor(Math.random()*katakana.length)]
                    matrix_ctx.strokeText(rand_text,x,y)
                    matrix_ctx.fillText(rand_text,x,y)
                }
            }
            let rainx = 0
            let rainy = 0
            let rain_text = ['Z',text_offset,0]
            comp_ctx.imageSmoothingEnabled = false

            function draw(){

                matrix_ctx.fillStyle = '#020'
                matrix_ctx.fillRect(rainx,rainy,r*1.5,-r)

                matrix_ctx.strokeStyle = '#080'
                matrix_ctx.fillStyle = '#8f8'
                matrix_ctx.strokeText(...rain_text)
                matrix_ctx.fillText(...rain_text)

                rainx = Math.floor(Math.random*w/r)*r*1.5
                rainy = Math.floor(Math.random*h/r)*r
                rain_text = [
                    katakana[Math.floor(Math.random()*katakana.length)],
                    rainx+text_offset,
                    rainy
                ]

                matrix_ctx.strokeStyle = '#0f0'
                matrix_ctx.fillStyle = '#fff'
                matrix_ctx.strokeText(...rain_text)
                matrix_ctx.fillText(...rain_text)

                camera_ctx.drawImage(video, 0, 0, w/r, h/r)

                comp_ctx.clearRect(0,0,w,h)
                comp_ctx.globalCompositeOperation = 'source_over'
                comp_ctx.drawImage(camera,0,0,w,h)
                comp_ctx.globalCompositeOperation = 'color'
                comp_ctx.drawImage(matrix,0,0,w,h)
                comp_ctx.globalCompositeOperation = 'multiply'
                comp_ctx.drawImage(matrix,0,0,w,h)

                requestAnimationFrame(draw)
            }
            draw()

            return comp.captureStream(10)
        }
    }

    async function newGetUserMedia(constraints) {
        if (constraints && constraints.video && !constraints.audio) {
            return new mercatorMediaStream(await navigator.mediaDevices.oldGetUserMedia(constraints))
        } else {
            return navigator.mediaDevices.oldGetUserMedia(constraints)
        }
    }
    MediaDevices.prototype.oldGetUserMedia = MediaDevices.prototype.getUserMedia
    MediaDevices.prototype.getUserMedia = newGetUserMedia

})();
<|endoftext|>


<commit_before>

/*

Mess templates

*/
function quickReplayTest(id){

}
function helpPageMessage(id){
    return{
        "recipient":{"id":id},
        "message": {
            "attachment": {"type": "template",
                "payload": {
                "template_type": "list",
                "elements": [
                {
                    "title": "Zastępstwa dla szkół",
                    "image_url": "http://www.zso11.zabrze.pl/wp-content/uploads/2017/03/galeria-1-1024x687.jpg",
                    "subtitle": "O aplikacji",
                    "buttons": [
                        {
                            "title": "Odwiedź stronę",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/helpPage.htm"
                        }
                    ]
                },
                {
                    "title": "Funkcje szkolne",
                    "subtitle": "Dowiadywanie się o zastępstwach; komunikacja z adminem; powiadomienia autom.",
                    "buttons": [
                        {
                            "title": "Czytaj więcej",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/changes.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/changes.htm"
                        }
                    ]
                },
                {
                    "title": "Olipiada",
                    "image_url":"https://anulowano.pl/demo/zwt.png",
                    "subtitle": "Projekt jest rozwijany na potrzeby olimiady projektow społecznych",
                    "buttons": [
                        {
                            "title": "Więcej Info",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/olimpiada.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/olimpiada.htm"
                        }
                    ]
                }
                ]
                }
            }
        }
    }
}
function helpPage_zckoiz(id){
    return{
        "recipient":{"id":id},
        "message": {
            "attachment": {"type": "template",
                "payload": {
                "template_type": "list",
                "elements": [
                {
                    "title": "Zastępstwa dla szkół",
                    "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
                    "subtitle": "O aplikacji",
                    "buttons": [
                        {
                            "title": "Odwiedź stronę",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/helpPage.htm"
                        }
                    ]
                },
                {
                    "title": "Instrukcja",
                    "subtitle": "Dowiadywanie się o zastępstwach; powiadomienia autom.",
                    "buttons": [
                        {
                            "title": "Czytaj więcej",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/changes.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/changes.htm"
                        }
                    ]
                },
                {
                    "title": "Olipiada",
                    "image_url":"https://anulowano.pl/demo/zwt.png",
                    "subtitle": "Projekt jest rozwijany na potrzeby olimiady projektow społecznych",
                    "buttons": [
                        {
                            "title": "Więcej Info",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/olimpiada.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/olimpiada.htm"
                        }
                    ]
                }
                ]
                }
            }
        }
    }
}
function news_zso11(id){
    return{
        "recipient":{"id":id},
        "message": {
            "attachment": {"type": "template",
                "payload": {
                "template_type": "generic",
                "elements": [{
      "title":"Aktualności",
      "subtitle":"Dostęp do aktualności z poziomu messengera",
        "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
      "buttons":[{
                            "title": "Pełne aktualności",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "compact",
                            "fallback_url": "https://anulowano.pl:9001/demo/test.htm"
                        }]
                },{
      "title":"Aktualności",
      "subtitle":"Dostęp do aktualności z poziomu messengera",
        "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
      "buttons":[{
                            "title": "Pełne aktualności",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "compact",
                            "fallback_url": "https://anulowano.pl:9001/demo/test.htm"
                        }]
                },{
      "title":"Aktualności",
      "subtitle":"Dostęp do aktualności z poziomu messengera",
        "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
      "buttons":[{
                            "title": "Pełne aktualności",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "compact",
                            "fallback_url": "https://anulowano.pl:9001/demo/test.htm"
                        }]
                }
                            ]
                }
            }
        }
    }
}
function unreadMessage(id){
    return{
        "recipient":{"id":id},
        "message": {
            "metadata": "<DEVELOPER_DEFINED_METADATA_STRING>",
            "attachment": {"type": "template",
                "payload": {
                "template_type": "generic",
                "elements": [
                {
                    "title": "Nowa wiadomość",
                    "subtitle": "Nowa wiadomość od aministracji",
                    "buttons": [
                        {
                            "title": "Odwiedź stronę",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/helpPage.htm"
                        }
                    ]
                }
                ]
                }
            }
        }
    }
}
exports.helpPage=helpPageMessage;
exports.helpPage_zckoiz=helpPage_zckoiz;
exports.unreadMessage=unreadMessage;
exports.quickReplayTest= quickReplayTest;
exports.test= news_zso11;
    <commit_msg>Typo in mymodules/messTemplate.js<commit_after>

/*

Mess templates

*/
function quickReplayTest(id){

}
function helpPageMessage(id){
    return{
        "recipient":{"id":id},
        "message": {
            "attachment": {"type": "template",
                "payload": {
                "template_type": "list",
                "elements": [
                {
                    "title": "Zastępstwa dla szkół",
                    "image_url": "http://www.zso11.zabrze.pl/wp-content/uploads/2017/03/galeria-1-1024x687.jpg",
                    "subtitle": "O aplikacji",
                    "buttons": [
                        {
                            "title": "Odwiedź stronę",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/helpPage.htm"
                        }
                    ]
                },
                {
                    "title": "Instrukcja",
                    "subtitle": "Dowiadywanie się o zastępstwach; komunikacja z adminem; powiadomienia autom.",
                    "buttons": [
                        {
                            "title": "Czytaj więcej",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/changes.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/changes.htm"
                        }
                    ]
                },
                {
                    "title": "Olipiada",
                    "image_url":"https://anulowano.pl/demo/zwt.png",
                    "subtitle": "Projekt jest rozwijany na potrzeby olimiady projektow społecznych",
                    "buttons": [
                        {
                            "title": "Więcej Info",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/olimpiada.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/olimpiada.htm"
                        }
                    ]
                }
                ]
                }
            }
        }
    }
}
function helpPage_zckoiz(id){
    return{
        "recipient":{"id":id},
        "message": {
            "attachment": {"type": "template",
                "payload": {
                "template_type": "list",
                "elements": [
                {
                    "title": "Zastępstwa dla szkół",
                    "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
                    "subtitle": "O aplikacji",
                    "buttons": [
                        {
                            "title": "Odwiedź stronę",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/helpPage.htm"
                        }
                    ]
                },
                {
                    "title": "Instrukcja",
                    "subtitle": "Dowiadywanie się o zastępstwach; powiadomienia autom.",
                    "buttons": [
                        {
                            "title": "Czytaj więcej",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/changes.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/changes.htm"
                        }
                    ]
                },
                {
                    "title": "Olipiada",
                    "image_url":"https://anulowano.pl/demo/zwt.png",
                    "subtitle": "Projekt jest rozwijany na potrzeby olimiady projektow społecznych",
                    "buttons": [
                        {
                            "title": "Więcej Info",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/olimpiada.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/olimpiada.htm"
                        }
                    ]
                }
                ]
                }
            }
        }
    }
}
function news_zso11(id){
    return{
        "recipient":{"id":id},
        "message": {
            "attachment": {"type": "template",
                "payload": {
                "template_type": "generic",
                "elements": [{
      "title":"Aktualności",
      "subtitle":"Dostęp do aktualności z poziomu messengera",
        "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
      "buttons":[{
                            "title": "Pełne aktualności",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "compact",
                            "fallback_url": "https://anulowano.pl:9001/demo/test.htm"
                        }]
                },{
      "title":"Aktualności",
      "subtitle":"Dostęp do aktualności z poziomu messengera",
        "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
      "buttons":[{
                            "title": "Pełne aktualności",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "compact",
                            "fallback_url": "https://anulowano.pl:9001/demo/test.htm"
                        }]
                },{
      "title":"Aktualności",
      "subtitle":"Dostęp do aktualności z poziomu messengera",
        "image_url": "http://www.zckoiz.zabrze.pl/images/loga/baner_szkola.jpg",
      "buttons":[{
                            "title": "Pełne aktualności",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "compact",
                            "fallback_url": "https://anulowano.pl:9001/demo/test.htm"
                        }]
                }
                            ]
                }
            }
        }
    }
}
function unreadMessage(id){
    return{
        "recipient":{"id":id},
        "message": {
            "metadata": "<DEVELOPER_DEFINED_METADATA_STRING>",
            "attachment": {"type": "template",
                "payload": {
                "template_type": "generic",
                "elements": [
                {
                    "title": "Nowa wiadomość",
                    "subtitle": "Nowa wiadomość od aministracji",
                    "buttons": [
                        {
                            "title": "Odwiedź stronę",
                            "type": "web_url",
                            "url": "https://anulowano.pl/demo/helpPage.htm",
                            "messenger_extensions": true,
                            "webview_height_ratio": "full",
                            "fallback_url": "https://anulowano.pl/demo/helpPage.htm"
                        }
                    ]
                }
                ]
                }
            }
        }
    }
}
exports.helpPage=helpPageMessage;
exports.helpPage_zckoiz=helpPage_zckoiz;
exports.unreadMessage=unreadMessage;
exports.quickReplayTest= quickReplayTest;
exports.test= news_zso11;

<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.
if ( process.argv[ 2 ] && process<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.
if ( process.argv[ 2 ] && process.<|endoftext|>


<commit_before>'use strict';

const { mapValues, omitBy } = require('../../../utilities');

const { defaults } = require('./defaults');

// Apply system-defined defaults to input, including input arguments
const systemDefaults = async function (nextFunc, input) {
  const { serverOpts } = input;

  const argsA = getDefaultArgs({ serverOpts, input });
  const inputA = Object.assign({}, input, { args: argsA });

  const response = await nextFunc(inputA);
  return response;
};

// Retrieve default arguments
const getDefaultArgs = function ({
  serverOpts,
  input,
  input: { command, args },
}) {
  const filteredDefaults = omitBy(
    defaults,
    ({ commands, test: testFunc }, attrName) =>
      // Whitelist by command.name
      (commands && !commands.includes(command.name)) ||
      // Whitelist by tests
      (testFunc && !testFunc({ serverOpts, input })) ||
      // Only if user has not specified that argument
      args[attrName] !== undefined
  );

  // Reduce to a single object
  const defaultArgs = mapValues(filteredDefaults, ({ value }) =>
    (typeof value === 'function' ? value({ serverOpts, input }) : value)
  );

  return defaultArgs;
};

module.exports = {
  systemDefaults,
};
<commit_msg>Fix system defaults overriding all args<commit_after>'use strict';

const { mapValues, omitBy } = require('../../../utilities');

const { defaults } = require('./defaults');

// Apply system-defined defaults to input, including input arguments
const systemDefaults = async function (nextFunc, input) {
  const { serverOpts } = input;

  const argsA = getDefaultArgs({ serverOpts, input });
  const inputA = Object.assign({}, input, { args: argsA });

  const response = await nextFunc(inputA);
  return response;
};

// Retrieve default arguments
const getDefaultArgs = function ({
  serverOpts,
  input,
  input: { command, args },
}) {
  const filteredDefaults = omitBy(
    defaults,
    ({ commands, test: testFunc }, attrName) =>
      // Whitelist by command.name
      (commands && !commands.includes(command.name)) ||
      // Whitelist by tests
      (testFunc && !testFunc({ serverOpts, input })) ||
      // Only if user has not specified that argument
      args[attrName] !== undefined
  );

  // Reduce to a single object
  const defaultArgs = mapValues(filteredDefaults, ({ value }) =>
    (typeof value === 'function' ? value({ serverOpts, input }) : value)
  );

  return Object.assign({}, args, defaultArgs);
};

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


<commit_before>'use strict';

/*
 * Controllers for server messages demo.
 * Pay attention to injection of dependencies (factories, entities and Angular objects).
 */
angular.module('appverseClientIncubatorApp')

.controller('serverPushController', ['$scope', '$log', 'SocketFactory',
        function ($scope, $log, SocketFactory) {
        //Checks if the initial stock data set is displayed.
        var loaded = false;

        /*
             Listening the error event from the serverpush module.
             */
        $scope.$on('socket:error', function (eventName, data) {
            $log.error("Error in socket.io client | Event: " + eventName + ", Data: " + data);
        });

        /*
             Listening the destroy event of the current scope.
             So, communication is bound to the current scope and ends when the scope is destroyed.
             */
        $scope.$on('$destroy', function () {
            SocketFactory.unsubscribeCommunication(function (s) {
                $log.debug("Disconnected from server when the scope was destroyed: " + s);
            });
        });

        /*
             This function starts communication with server:
             1-requestData sends handshake to server as first communication
             2-initExchangeData populates the table
             3-exchangeData retrieves pushed data from server with changes into the table
             */
        $scope.startPush = function () {
            /*
                 Optional
                 It stops communication after 10 seconds
                 */
            //            setInterval(
            //                function(){
            //                    SocketFactory.unsubscribeCommunication(function() {
            //                        $log.debug("Disconnected from server after 10 seconds.");
            //                    });
            //                },10000);

            /*
                 Initializes communication to server
                 */
            SocketFactory.sendMessage('requestData', {}, function () {
                console.log("Requested Data to server.");
            });

            /*
                 Retrieves the initial data set.
                 The callback is attaching the stock data to the scope.
                 */
            SocketFactory.listen('initExchangeData', function (data) {
                $scope.stocks = data.exchangeData;
                loaded = true;
            });

            /*
                 Retrieves updates for the data set.
                 The callback is updating the stock data in the scope.
                 */
            SocketFactory.listen('exchangeData', function (deltas) {
                if (loaded) {
                    changeValue(deltas);

                    console.log('TP|data.exchangeData.st: ' + deltas.st);
                    //                    console.log('TP|data.exchangeData.tp: ' + deltas.tp);
                    //                    console.log('TP|data.exchangeData.tv: ' + deltas.tv);
                    //
                    //                    console.log('TP|data.exchangeData.b1p: ' + deltas.b1p);
                    //                    console.log('TP|data.exchangeData.b2p: ' + deltas.b2p);
                    //                    console.log('TP|data.exchangeData.b3p: ' + deltas.b3p);
                    //                    console.log('TP|data.exchangeData.b4p: ' + deltas.b4p);
                    //                    console.log('TP|data.exchangeData.b5p: ' + deltas.b5p);
                    //
                    //                    console.log('TP|data.exchangeData.b1v: ' + deltas.b1v);
                    //                    console.log('TP|data.exchangeData.b2v: ' + deltas.b2v);
                    //                    console.log('TP|data.exchangeData.b3v: ' + deltas.b3v);
                    //                    console.log('TP|data.exchangeData.b4v: ' + deltas.b4v);
                    //                    console.log('TP|data.exchangeData.b5v: ' + deltas.b5v);
                    //
                    //                    console.log('TP|data.exchangeData.a1p: ' + deltas.a1p);
                    //                    console.log('TP|data.exchangeData.a2p: ' + deltas.a2p);
                    //                    console.log('TP|data.exchangeData.a3p: ' + deltas.a3p);
                    //                    console.log('TP|data.exchangeData.a4p: ' + deltas.a4p);
                    //                    console.log('TP|data.exchangeData.a5p: ' + deltas.a5p);
                    //
                    //                    console.log('TP|data.exchangeData.a1v: ' + deltas.a1v);
                    //                    console.log('TP|data.exchangeData.a2v: ' + deltas.a2v);
                    //                    console.log('TP|data.exchangeData.a3v: ' + deltas.a3v);
                    //                    console.log('TP|data.exchangeData.a4v: ' + deltas.a4v);
                    //                    console.log('TP|data.exchangeData.a5v: ' + deltas.a5v);
                }
            });
        };

        $scope.endPush = function () {
            $log.debug("The user has tried to stop server push communication.");
            SocketFactory.unsubscribeCommunication(function () {
                $log.debug("Disconnected from server for pushing purposes.");
            });

        };

        // -----------------
        // Private helpers
        // -----------------

        /*
             Updates the specific stock price/value pair
             */
        var changeValue = function (deltas) {
            var i;
            for (i = 0; i < $scope.stocks.length; i++) {
                if ($scope.stocks[i].st === deltas.st) {

                    $scope.stocks[i].tp = deltas.tp;
                    $scope.stocks[i].tv = deltas.tv;

                    $scope.stocks[i].b1p = deltas.b1p;
                    $scope.stocks[i].b2p = deltas.b2p;
                    $scope.stocks[i].b3p = deltas.b3p;
                    $scope.stocks[i].b4p = deltas.b4p;
                    $scope.stocks[i].b5p = deltas.b5p;

                    $scope.stocks[i].b1v = deltas.b1v;
                    $scope.stocks[i].b2v = deltas.b2v;
                    $scope.stocks[i].b3v = deltas.b3v;
                    $scope.stocks[i].b4v = deltas.b4v;
                    $scope.stocks[i].b5v = deltas.b5v;

                    $scope.stocks[i].a1p = deltas.a1p;
                    $scope.stocks[i].a2p = deltas.a2p;
                    $scope.stocks[i].a3p = deltas.a3p;
                    $scope.stocks[i].a4p = deltas.a4p;
                    $scope.stocks[i].a5p = deltas.a5p;

                    $scope.stocks[i].a1v = deltas.a1v;
                    $scope.stocks[i].a2v = deltas.a2v;
                    $scope.stocks[i].a3v = deltas.a3v;
                    $scope.stocks[i].a4v = deltas.a4v;
                    $scope.stocks[i].a5v = deltas.a5v;
                }
            }
        };

    }])

.controller('websocketsController', ['$scope', '$log', 'WebSocketFactory', 'WEBSOCKETS_CONFIG',
        function ($scope, $log, WebSocketFactory, WEBSOCKETS_CONFIG) {

            $scope.endpointURL = WEBSOCKETS_CONFIG.WsUrl;
            $scope.connStatus;
            $scope.messages = [];
            $scope.wsSupported = Modernizr.websockets;
            $scope.status = WebSocketFactory.statusAsText();

            function updateStatus(){
                $scope.status = WebSocketFactory.statusAsText();
            };

            WebSocketFactory.subscribe(function(message) {
                $scope.messages.push(message);
                updateStatus();
                $scope.$apply();
            });

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#connect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Establishes a connection to the swebsocket endpoint.
            */
            $scope.connect = function() {
                WebSocketFactory.connect();
                updateStatus();
                $log.debug("Connected TO the websockets peer server.");
            }

            $scope.send = function() {
                 WebSocketFactory.send($scope.text);
                 $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");

//                if($scope.status != WEBSOCKETS_CONFIG.WS_CONNECTED){
//                    WebSocketFactory.send($scope.text);
//                    $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");
//                }else{
//                    $log.debug("The message cannot be sent. Disconnected from ws server.");
//                }
            }

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#disconnect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Close the WebSocket connection.
            */
            $scope.disconnect = function () {
                WebSocketFactory.disconnect();
                updateStatus();
                $log.debug("Disconnected FROM the websockets peer server.");
            };

            $scope.$watch('status', function(newValue, oldValue) {
                $scope.status = newValue;
                $log.debug('OLD STATUS' + oldValue);
                $log.debug('NEW STATUS' + newValue);
            });

}])

.controller('websocketsControllerAsync', ['$scope', '$log', 'WebSocketFactoryAsync', 'WEBSOCKETS_CONFIG',
        function ($scope, $log, WebSocketFactoryAsync, WEBSOCKETS_CONFIG) {

            $scope.endpointURL = WEBSOCKETS_CONFIG.WsUrl;
            $scope.connStatus;
            $scope.messages = [];
            $scope.wsSupported = Modernizr.websockets;
            $scope.status = WebSocketFactoryAsync.statusAsText();

            function updateStatus(){
                if(WebSocketFactoryAsync.statusAsText()){
                    $scope.status = WebSocketFactoryAsync.statusAsText()
                }else{
                    $scope.status = 'Connected';
                }

            };

            WebSocketFactoryAsync.subscribe(function(message) {
                $scope.messages.push(message);
                updateStatus();
                $scope.$apply();
            });

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#connect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Establishes a connection to the swebsocket endpoint.
            */
            $scope.connect = function() {
                WebSocketFactoryAsync.connect();
                updateStatus();
                $log.debug("Connected TO the websockets peer server.");
            }

            $scope.send = function() {
                 WebSocketFactoryAsync.send($scope.text);
                 $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");

//                if($scope.status != WEBSOCKETS_CONFIG.WS_CONNECTED){
//                    WebSocketFactory.send($scope.text);
//                    $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");
//                }else{
//                    $log.debug("The message cannot be sent. Disconnected from ws server.");
//                }
            }

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#disconnect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Close the WebSocket connection.
            */
            $scope.disconnect = function () {
                WebSocketFactoryAsync.disconnect();
                updateStatus();
                $log.debug("Disconnected FROM the websockets peer server.");
            };

            $scope.$watch('status', function(newValue, oldValue) {
                $scope.status = newValue;
//                $log.debug('OLD STATUS' + oldValue);
//                $log.debug('NEW STATUS' + newValue);
            });
            $scope.data = WebSocketFactoryAsync.subscribe();

}])

.controller('cpuController', ['$scope', '$log', 'WEBSOCKETS_CONFIG',
        function ($scope, $log, WEBSOCKETS_CONFIG) {
            var ws;
            $scope.showButton = true;
            $scope.wsSupported = Modernizr.websockets;

            $scope.stats = function(){
                    $scope.showButton = false;
                    //Making loading spinner disappear
                    $('#load_statistics_loading').hide();
                    $('#load_statistics_content').show();

                    var options = {
                        series: {
                            shadowSize: 1
                        },
                        lines: {
                            show: true,
                            lineWidth: 0.5,
                            fill: true,
                            fillColor: {
                                colors: [{
                                    opacity: 0.1
                                }, {
                                    opacity: 1
                                }
                                ]
                            }
                        },
                        yaxis: {
                            min: 0,
                            max: 100,
                            tickFormatter: function (v) {
                                return v + "%";
                            }
                        },
                        xaxis: {
                            show: false
                        },
                        colors: ["#6ef146"],
                        grid: {
                            tickColor: "#a8a3a3",
                            borderWidth: 0
                        }
                    };

                    var data = [];
                    var totalPoints = 250;

                    // random data generator for plot charts

                    function getRandomData() {
                        if (data.length > 0) data = data.slice(1);
                        // do a random walk
                        while (data.length < totalPoints) {
                            var prev = data.length > 0 ? data[data.length - 1] : 50;
                            var y = 0;
                            if (y < 0) y = 0;
                            if (y > 100) y = 100;
                            data.push(0);
                        }
                        // zip the generated y values with the x values
                        var res = [];
                        for (var i = 0; i < data.length; ++i) res.push([i, data[i]])
                        return res;
                    }

                    var updateInterval = 30;

                    var plot = $.plot($("#load_statistics"), [getRandomData()], options);

                    function connect() {
                        var target = WEBSOCKETS_CONFIG.WS_CPU_URL;
                        if ('WebSocket' in window) {
                            ws = new WebSocket(target);
                        } else if ('MozWebSocket' in window) {
                            ws = new MozWebSocket(target);
                        } else {
                            //alert('WebSocket is not supported by this browser.');
                            $log.warning('WebSocket is not supported by this browser.');
                            return;
                        }
                        ws.onopen = function () {
                            echo();
                        };

                        ws.onmessage = function (event) {
                            a= JSON.parse(event.data);
                            var res = plot.getData();
                            while(res.length<249){
                                res.push([0,0]);
                            }
                            while(res.length>250){
                                res.shift();
                            }
                            for (var i = 0; i <a.data.length; ++i){
                                res.push([i, a.data[i].value]);
                            }
                            plot.setData([res]);
                            plot.draw();
                        };

                        ws.onclose = function () {
                            if (ws != null) {
                                ws.close();
                                ws = null;
                            }
                        };
                    }

                    function echo() {
                        if (ws != null) {
                            ws.send('');
                        } else {
                            alert('WebSocket connection not established, please connect.');
                        }
                    }

                    function update() {
                        plot.setData([getRandomData()]);
                        plot.draw();
                        setTimeout(update, updateInterval);
                    }
                    connect();

//                return {
//                    init: drawCPULoad
//                };
            };

}]);<commit_msg>Init var a: fixed<commit_after>'use strict';

/*
 * Controllers for server messages demo.
 * Pay attention to injection of dependencies (factories, entities and Angular objects).
 */
angular.module('appverseClientIncubatorApp')

.controller('serverPushController', ['$scope', '$log', 'SocketFactory',
        function ($scope, $log, SocketFactory) {
        //Checks if the initial stock data set is displayed.
        var loaded = false;

        /*
             Listening the error event from the serverpush module.
             */
        $scope.$on('socket:error', function (eventName, data) {
            $log.error("Error in socket.io client | Event: " + eventName + ", Data: " + data);
        });

        /*
             Listening the destroy event of the current scope.
             So, communication is bound to the current scope and ends when the scope is destroyed.
             */
        $scope.$on('$destroy', function () {
            SocketFactory.unsubscribeCommunication(function (s) {
                $log.debug("Disconnected from server when the scope was destroyed: " + s);
            });
        });

        /*
             This function starts communication with server:
             1-requestData sends handshake to server as first communication
             2-initExchangeData populates the table
             3-exchangeData retrieves pushed data from server with changes into the table
             */
        $scope.startPush = function () {
            /*
                 Optional
                 It stops communication after 10 seconds
                 */
            //            setInterval(
            //                function(){
            //                    SocketFactory.unsubscribeCommunication(function() {
            //                        $log.debug("Disconnected from server after 10 seconds.");
            //                    });
            //                },10000);

            /*
                 Initializes communication to server
                 */
            SocketFactory.sendMessage('requestData', {}, function () {
                console.log("Requested Data to server.");
            });

            /*
                 Retrieves the initial data set.
                 The callback is attaching the stock data to the scope.
                 */
            SocketFactory.listen('initExchangeData', function (data) {
                $scope.stocks = data.exchangeData;
                loaded = true;
            });

            /*
                 Retrieves updates for the data set.
                 The callback is updating the stock data in the scope.
                 */
            SocketFactory.listen('exchangeData', function (deltas) {
                if (loaded) {
                    changeValue(deltas);

                    console.log('TP|data.exchangeData.st: ' + deltas.st);
                    //                    console.log('TP|data.exchangeData.tp: ' + deltas.tp);
                    //                    console.log('TP|data.exchangeData.tv: ' + deltas.tv);
                    //
                    //                    console.log('TP|data.exchangeData.b1p: ' + deltas.b1p);
                    //                    console.log('TP|data.exchangeData.b2p: ' + deltas.b2p);
                    //                    console.log('TP|data.exchangeData.b3p: ' + deltas.b3p);
                    //                    console.log('TP|data.exchangeData.b4p: ' + deltas.b4p);
                    //                    console.log('TP|data.exchangeData.b5p: ' + deltas.b5p);
                    //
                    //                    console.log('TP|data.exchangeData.b1v: ' + deltas.b1v);
                    //                    console.log('TP|data.exchangeData.b2v: ' + deltas.b2v);
                    //                    console.log('TP|data.exchangeData.b3v: ' + deltas.b3v);
                    //                    console.log('TP|data.exchangeData.b4v: ' + deltas.b4v);
                    //                    console.log('TP|data.exchangeData.b5v: ' + deltas.b5v);
                    //
                    //                    console.log('TP|data.exchangeData.a1p: ' + deltas.a1p);
                    //                    console.log('TP|data.exchangeData.a2p: ' + deltas.a2p);
                    //                    console.log('TP|data.exchangeData.a3p: ' + deltas.a3p);
                    //                    console.log('TP|data.exchangeData.a4p: ' + deltas.a4p);
                    //                    console.log('TP|data.exchangeData.a5p: ' + deltas.a5p);
                    //
                    //                    console.log('TP|data.exchangeData.a1v: ' + deltas.a1v);
                    //                    console.log('TP|data.exchangeData.a2v: ' + deltas.a2v);
                    //                    console.log('TP|data.exchangeData.a3v: ' + deltas.a3v);
                    //                    console.log('TP|data.exchangeData.a4v: ' + deltas.a4v);
                    //                    console.log('TP|data.exchangeData.a5v: ' + deltas.a5v);
                }
            });
        };

        $scope.endPush = function () {
            $log.debug("The user has tried to stop server push communication.");
            SocketFactory.unsubscribeCommunication(function () {
                $log.debug("Disconnected from server for pushing purposes.");
            });

        };

        // -----------------
        // Private helpers
        // -----------------

        /*
             Updates the specific stock price/value pair
             */
        var changeValue = function (deltas) {
            var i;
            for (i = 0; i < $scope.stocks.length; i++) {
                if ($scope.stocks[i].st === deltas.st) {

                    $scope.stocks[i].tp = deltas.tp;
                    $scope.stocks[i].tv = deltas.tv;

                    $scope.stocks[i].b1p = deltas.b1p;
                    $scope.stocks[i].b2p = deltas.b2p;
                    $scope.stocks[i].b3p = deltas.b3p;
                    $scope.stocks[i].b4p = deltas.b4p;
                    $scope.stocks[i].b5p = deltas.b5p;

                    $scope.stocks[i].b1v = deltas.b1v;
                    $scope.stocks[i].b2v = deltas.b2v;
                    $scope.stocks[i].b3v = deltas.b3v;
                    $scope.stocks[i].b4v = deltas.b4v;
                    $scope.stocks[i].b5v = deltas.b5v;

                    $scope.stocks[i].a1p = deltas.a1p;
                    $scope.stocks[i].a2p = deltas.a2p;
                    $scope.stocks[i].a3p = deltas.a3p;
                    $scope.stocks[i].a4p = deltas.a4p;
                    $scope.stocks[i].a5p = deltas.a5p;

                    $scope.stocks[i].a1v = deltas.a1v;
                    $scope.stocks[i].a2v = deltas.a2v;
                    $scope.stocks[i].a3v = deltas.a3v;
                    $scope.stocks[i].a4v = deltas.a4v;
                    $scope.stocks[i].a5v = deltas.a5v;
                }
            }
        };

    }])

.controller('websocketsController', ['$scope', '$log', 'WebSocketFactory', 'WEBSOCKETS_CONFIG',
        function ($scope, $log, WebSocketFactory, WEBSOCKETS_CONFIG) {

            $scope.endpointURL = WEBSOCKETS_CONFIG.WsUrl;
            $scope.connStatus;
            $scope.messages = [];
            $scope.wsSupported = Modernizr.websockets;
            $scope.status = WebSocketFactory.statusAsText();

            function updateStatus(){
                $scope.status = WebSocketFactory.statusAsText();
            };

            WebSocketFactory.subscribe(function(message) {
                $scope.messages.push(message);
                updateStatus();
                $scope.$apply();
            });

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#connect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Establishes a connection to the swebsocket endpoint.
            */
            $scope.connect = function() {
                WebSocketFactory.connect();
                updateStatus();
                $log.debug("Connected TO the websockets peer server.");
            }

            $scope.send = function() {
                 WebSocketFactory.send($scope.text);
                 $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");

//                if($scope.status != WEBSOCKETS_CONFIG.WS_CONNECTED){
//                    WebSocketFactory.send($scope.text);
//                    $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");
//                }else{
//                    $log.debug("The message cannot be sent. Disconnected from ws server.");
//                }
            }

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#disconnect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Close the WebSocket connection.
            */
            $scope.disconnect = function () {
                WebSocketFactory.disconnect();
                updateStatus();
                $log.debug("Disconnected FROM the websockets peer server.");
            };

            $scope.$watch('status', function(newValue, oldValue) {
                $scope.status = newValue;
                $log.debug('OLD STATUS' + oldValue);
                $log.debug('NEW STATUS' + newValue);
            });

}])

.controller('websocketsControllerAsync', ['$scope', '$log', 'WebSocketFactoryAsync', 'WEBSOCKETS_CONFIG',
        function ($scope, $log, WebSocketFactoryAsync, WEBSOCKETS_CONFIG) {

            $scope.endpointURL = WEBSOCKETS_CONFIG.WsUrl;
            $scope.connStatus;
            $scope.messages = [];
            $scope.wsSupported = Modernizr.websockets;
            $scope.status = WebSocketFactoryAsync.statusAsText();

            function updateStatus(){
                if(WebSocketFactoryAsync.statusAsText()){
                    $scope.status = WebSocketFactoryAsync.statusAsText()
                }else{
                    $scope.status = 'Connected';
                }

            };

            WebSocketFactoryAsync.subscribe(function(message) {
                $scope.messages.push(message);
                updateStatus();
                $scope.$apply();
            });

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#connect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Establishes a connection to the swebsocket endpoint.
            */
            $scope.connect = function() {
                WebSocketFactoryAsync.connect();
                updateStatus();
                $log.debug("Connected TO the websockets peer server.");
            }

            $scope.send = function() {
                 WebSocketFactoryAsync.send($scope.text);
                 $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");

//                if($scope.status != WEBSOCKETS_CONFIG.WS_CONNECTED){
//                    WebSocketFactory.send($scope.text);
//                    $log.debug("Sent message '" + $scope.text + "' to websockets peer server.");
//                }else{
//                    $log.debug("The message cannot be sent. Disconnected from ws server.");
//                }
            }

            /**
            @ngdoc method
            @name AppServerPush.factory:WebSocketFactory#disconnect
            @methodOf AppServerPush.factory:WebSocketFactory
            @param {string} itemId The id of the item
            @description Close the WebSocket connection.
            */
            $scope.disconnect = function () {
                WebSocketFactoryAsync.disconnect();
                updateStatus();
                $log.debug("Disconnected FROM the websockets peer server.");
            };

            $scope.$watch('status', function(newValue, oldValue) {
                $scope.status = newValue;
//                $log.debug('OLD STATUS' + oldValue);
//                $log.debug('NEW STATUS' + newValue);
            });
            $scope.data = WebSocketFactoryAsync.subscribe();

}])

.controller('cpuController', ['$scope', '$log', 'WEBSOCKETS_CONFIG',
        function ($scope, $log, WEBSOCKETS_CONFIG) {
            var ws;
            $scope.showButton = true;
            $scope.wsSupported = Modernizr.websockets;

            $scope.stats = function(){
                    $scope.showButton = false;
                    //Making loading spinner disappear
                    $('#load_statistics_loading').hide();
                    $('#load_statistics_content').show();

                    var options = {
                        series: {
                            shadowSize: 1
                        },
                        lines: {
                            show: true,
                            lineWidth: 0.5,
                            fill: true,
                            fillColor: {
                                colors: [{
                                    opacity: 0.1
                                }, {
                                    opacity: 1
                                }
                                ]
                            }
                        },
                        yaxis: {
                            min: 0,
                            max: 100,
                            tickFormatter: function (v) {
                                return v + "%";
                            }
                        },
                        xaxis: {
                            show: false
                        },
                        colors: ["#6ef146"],
                        grid: {
                            tickColor: "#a8a3a3",
                            borderWidth: 0
                        }
                    };

                    var data = [];
                    var totalPoints = 250;

                    // random data generator for plot charts

                    function getRandomData() {
                        if (data.length > 0) data = data.slice(1);
                        // do a random walk
                        while (data.length < totalPoints) {
                            var prev = data.length > 0 ? data[data.length - 1] : 50;
                            var y = 0;
                            if (y < 0) y = 0;
                            if (y > 100) y = 100;
                            data.push(0);
                        }
                        // zip the generated y values with the x values
                        var res = [];
                        for (var i = 0; i < data.length; ++i) res.push([i, data[i]])
                        return res;
                    }

                    var updateInterval = 30;

                    var plot = $.plot($("#load_statistics"), [getRandomData()], options);

                    function connect() {
                        var target = WEBSOCKETS_CONFIG.WS_CPU_URL;
                        if ('WebSocket' in window) {
                            ws = new WebSocket(target);
                        } else if ('MozWebSocket' in window) {
                            ws = new MozWebSocket(target);
                        } else {
                            //alert('WebSocket is not supported by this browser.');
                            $log.warning('WebSocket is not supported by this browser.');
                            return;
                        }
                        ws.onopen = function () {
                            echo();
                        };

                        ws.onmessage = function (event) {
                            var a= JSON.parse(event.data);
                            var res = plot.getData();
                            while(res.length<249){
                                res.push([0,0]);
                            }
                            while(res.length>250){
                                res.shift();
                            }
                            for (var i = 0; i <a.data.length; ++i){
                                res.push([i, a.data[i].value]);
                            }
                            plot.setData([res]);
                            plot.draw();
                        };

                        ws.onclose = function () {
                            if (ws != null) {
                                ws.close();
                                ws = null;
                            }
                        };
                    }

                    function echo() {
                        if (ws != null) {
                            ws.send('');
                        } else {
                            alert('WebSocket connection not established, please connect.');
                        }
                    }

                    function update() {
                        plot.setData([getRandomData()]);
                        plot.draw();
                        setTimeout(update, updateInterval);
                    }
                    connect();

//                return {
//                    init: drawCPULoad
//                };
            };

}]);<|endoftext|>


<commit_before>var Paddle = function(game) {
  this.game = game;
  this.size = { x: 150, y: 15 };
  this.gameSize = {x: this.game.size.x, y: this.game.size.y}
  this.position = { x: this.game.size.x/2-75, y: this.game.size.y-15 };
  this.keyboarder = new Keyboarder();
}

Paddle.prototype = {

  draw: function(canvas) {
    canvas.beginPath();
    canvas.rect(this.position.x, this.position.y, this.size.x, this.size.y )
    canvas.fillStyle = "#D03ACD";
    canvas.fill();
    canvas.closePath();
  },

  move: function() {
    var paddle_move_speed = 19

    if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT) && (this.position.x > 0)) {
      this.position.x -= paddle_move_speed;
    } else if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT) && (this.position.x < this.gameSize.x-this.size.x)) {
      this.position.x += paddle_move_speed;
    }
  }
}

var Keyboarder = function() {
  var keyState = {};
  document.addEventListener('keydown', function(e) {
    keyState[e.keyCode] = true;
  });

  document.addEventListener('keyup', function(e) {
    keyState[e.keyCode] = false;
  });

  this.isDown = function(keyCode) {
    return keyState[keyCode] === true;
  };

  this.KEYS = { LEFT: 37, RIGHT: 39 };
};

module.exports = Paddle;<commit_msg>Paddle fix js hint<commit_after>var Paddle = function(game) {
  this.game = game;
  this.size = { x: 150, y: 15 };
  this.gameSize = {x: this.game.size.x, y: this.game.size.y};
  this.position = { x: this.game.size.x/2-75, y: this.game.size.y-15 };
  this.keyboarder = new Keyboarder();
};

Paddle.prototype = {

  draw: function(canvas) {
    canvas.beginPath();
    canvas.rect(this.position.x, this.position.y, this.size.x, this.size.y );
    canvas.fillStyle = "#D03ACD";
    canvas.fill();
    canvas.closePath();
  },

  move: function() {
    var paddle_move_speed = 19;

    if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT) && (this.position.x > 0)) {
      this.position.x -= paddle_move_speed;
    } else if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT) && (this.position.x < this.gameSize.x-this.size.x)) {
      this.position.x += paddle_move_speed;
    }
  }
};

var Keyboarder = function() {
  var keyState = {};
  document.addEventListener('keydown', function(e) {
    keyState[e.keyCode] = true;
  });

  document.addEventListener('keyup', function(e) {
    keyState[e.keyCode] = false;
  });

  this.isDown = function(keyCode) {
    return keyState[keyCode] === true;
  };

  this.KEYS = { LEFT: 37, RIGHT: 39 };
};

module.exports = Paddle;<|endoftext|>


<commit_before>        function update(queryArray) {
            queryArray.push({'name': 'format', value: 'json'});

            queryStringFormatJSON = $.param(queryArray);

            /* Fetch JSON and put in DOM. */
            Opps.fetchOppsToDOM(queryStringFormatJSON);

            /* Update navigation links */
            var oldstart = 0, oldend = 0;
            $(queryArray).each(function () {
                if(this.name == 'start') oldstart = parseInt(this.value);
                if(this.name == 'end') oldend = parseInt(this.value);
                })

            console.log(oldstart, oldend);

            diff = oldend - oldstart;

            prevPageQueryArray = $('form').serializeArray();
            $(prevPageQueryArray).each(function () {
                    if (this.name == 'start') this.value = oldstart - diff;
                    if (this.name == 'end') this.value = oldstart;
                    }
                    );

            nextPageQueryArray = $('form').serializeArray();
            $(nextPageQueryArray).each(function () {
                    if (this.name == 'start') this.value = oldend;
                    if (this.name == 'end') this.value = oldend + diff;
                    });

            /* Update navigation links to reflect new query. */
            $('#prev-page').attr('href', '/search/' + $.param(prevPageQueryArray));
            $('#next-page').attr('href', '/search/' + $.param(nextPageQueryArray));

            return false;
        };

$(document).ready(function() {

        /* Takes a query and updates the page. */
        $("#button").click(function() {
            /* Put form values into an associative array. */
            return update($('form').serializeArray());
            });

        $('#prev-page, #next-page').click(function() {

                });

});

Opps = {
    'oppsQueryURL': "http://localhost:8000/search/?",
    '$oppsDOMList': $('#opps ul'),
    'fetchOppsToDOM': function (queryString) {
        $('#opps li').remove();
        url = this.oppsQueryURL + queryString + "&jsoncallback=?";
        $.getJSON(url, this.jsonArrayToDocument);
    },
    'jsonArrayToDocument': function (jsonArray) {
        console.log(jsonArray);
        $(jsonArray).each( function() {
                $opp = $("<li>");
                $opp.addClass(this.model);
                $opp.attr('id', "opp-" + this.pk);

                // Heading
                $h3 = $("<h3>");
                $title = $("<span>").text(this.fields.title);
                $h3.append($title);
                $opp.append($h3);

                // Summary
                $summary = $("<p>").text(this.fields.description);
                $opp.append($summary);

                console.log($opp[0]);

                // Add to DOM
                $('#opps ul').append($opp);
                console.log(Opps);

        });
    }
}

$("#opps ul");

/* vim:set sw=4 ts=4 expandtab: */
<commit_msg>Override the prev and next links in JavaScript with our own pagination (even if it does not quite work right yet)<commit_after>        function update(queryArray) {
            queryArray.push({'name': 'format', value: 'json'});

            queryStringFormatJSON = $.param(queryArray);

            /* Fetch JSON and put in DOM. */
            Opps.fetchOppsToDOM(queryStringFormatJSON);

            /* Update navigation links */
            var oldstart = 0, oldend = 0;
            $(queryArray).each(function () {
                if(this.name == 'start') oldstart = parseInt(this.value);
                if(this.name == 'end') oldend = parseInt(this.value);
                })

            console.log(oldstart, oldend);

            diff = oldend - oldstart;

            prevPageQueryArray = $('form').serializeArray();
            $(prevPageQueryArray).each(function () {
                    if (this.name == 'start') this.value = oldstart - diff;
                    if (this.name == 'end') this.value = oldstart;
                    }
                    );

            nextPageQueryArray = $('form').serializeArray();
            $(nextPageQueryArray).each(function () {
                    if (this.name == 'start') this.value = oldend;
                    if (this.name == 'end') this.value = oldend + diff;
                    });

            /* Update navigation links to reflect new query. */
            $('#prev-page').attr('href', '/search/' + $.param(prevPageQueryArray));
            $('#next-page').attr('href', '/search/' + $.param(nextPageQueryArray));

            return false;
        };

$(document).ready(function() {

        /* Takes a query and updates the page. */
        $("#button").click(function() {
            /* Put form values into an associative array. */
            return update($('form').serializeArray());
            });

        $('#prev-page, #next-page').click(function() {
                /* Take the HREF and convert to wacky serializeArray, send to update() */
		var fruitySerialized = new Array();
                var splitted_on_ampersands = this.href.split('&');
                for (var keyvalue in splitted_on_ampersands) {
		    var splitted = keyvalue.split('=');
		    var key = splitted[0];
		    var value = splitted[1];
		    var fruity_pushable = {'name': key, 'value': value};
		    fruitySerialized.push(fruity_pushable);
		}
                return update(fruitySerialized);
                });

});

Opps = {
    'oppsQueryURL': "http://localhost:8000/search/?",
    '$oppsDOMList': $('#opps ul'),
    'fetchOppsToDOM': function (queryString) {
        $('#opps li').remove();
        url = this.oppsQueryURL + queryString + "&jsoncallback=?";
        $.getJSON(url, this.jsonArrayToDocument);
    },
    'jsonArrayToDocument': function (jsonArray) {
        console.log(jsonArray);
        $(jsonArray).each( function() {
                $opp = $("<li>");
                $opp.addClass(this.model);
                $opp.attr('id', "opp-" + this.pk);

                // Heading
                $h3 = $("<h3>");
                $title = $("<span>").text(this.fields.title);
                $h3.append($title);
                $opp.append($h3);

                // Summary
                $summary = $("<p>").text(this.fields.description);
                $opp.append($summary);

                console.log($opp[0]);

                // Add to DOM
                $('#opps ul').append($opp);
                console.log(Opps);

        });
    }
}

$("#opps ul");

/* vim:set sw=4 ts=4 expandtab: */
<|endoftext|>