<commit_before>// IMPORT ASSETS
import '../css/App.scss'
import '../img/feed.png'
import '../img/split.png'
//import virusImage from '../img/virus.png'
import '../audio/spawn.mp3'
import '../audio/split.mp3'
import '../audio/plop.mp3'
import { THREE } from 'three'
import orbitFn from 'three-orbit-controls'
import flyFn from 'three-fly-controls'
import firstFn from 'three-first-person-controls'
const OrbitControls = orbitFn(THREE),
    FlyControls = flyFn(THREE),
    FirstPersonControls = firstFn(THREE)
import io from 'socket.io-client'

//TODO switch to FirstPersonControls

function debug(msg) {
    console.log(msg)
}

function $get(id) {
    return document.getElementById(id)
}

let camera, controls, scene, renderer, socket, state
const allMeshes = {},
    movementSpeed = 3,
    shininess = {
        f: 20,
        v: 150,
        p: 20,
        b: 20
    },
    specular = {
        f: 0x003300,
        v: 0xffffff,
        p: 0xffffff,
        b: 0xffffff
    }
let geoms = { }

const startBtn = $get('start'),
    startWrapper = $get('start-wrapper'),
    nameField = $get('name'),
    nameLabel = $get('my-name'),
    colourField = $get('colour'),
    massLabel = $get('my-mass'),
    radiusLabel = $get('my-radius'),
    speedLabel = $get('my-speed'),
    leaderboardDom = $get('leaderboard'),
    spawnAudio = $get('spawn_cell'),
    eatAudio = $get('eat'),
    leaderboard = {}
nameField.focus()

startBtn.addEventListener('click', () => {
    startGame(nameField.value, colourField.value)
    startWrapper.classList.add('hide')
})

function addBlob(options){
    const material = new THREE.MeshPhongMaterial({
            color: options.c,
            specular: options.specular,
            shininess: options.shininess
        }),
        mesh = new THREE.Mesh(options.geom, material)
    mesh.position.x = options.x
    mesh.position.y = options.y
    mesh.position.z = options.z
    mesh.updateMatrix()
    mesh.matrixAutoUpdate = false
    allMeshes[options.id] = mesh
    return mesh
}

function init(s) {
    scene = new THREE.Scene()
    scene.fog = new THREE.FogExp2(0xcccccc, 0.002)
    renderer = new THREE.WebGLRenderer()
    renderer.setClearColor(scene.fog.color)
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)

    const container = $get('container')
    container.appendChild(renderer.domElement)

    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000)
    camera.position.x = s.me.x
    camera.position.y = s.me.y
    camera.position.z = s.me.z

    controls = THREE.FlyControls(camera, renderer.domElement)
    //controls = THREE.FirstPersonControls(camera, renderer.domElement)
    controls.movementSpeed = movementSpeed
    controls.rollSpeed = 0.01
    //controls.lookSpeed = 0.125
    //controls.lookVertical = true
    //controls.constrainVertical = true
    //controls.verticalMin = 1.1
    //controls.verticalMax = 2.2

    const {things, config} = s
    geoms = {
        f: new THREE.SphereGeometry(config.foodRadius, 20, 20),
        v: new THREE.SphereGeometry(config.virusRadius, 20, 20),
        p: new THREE.SphereGeometry(config.startRadius, 20, 20),
        b: new THREE.SphereGeometry(config.startRadius, 20, 20)
    }

    things.forEach(t => {
        scene.add(addBlob(Object.assign(t, {
            shininess: shininess[t.t],
            specular: specular[t.t],
            geom: geoms[t.t]
        })))
        if (t.t === 'p') {
            leaderboard[t.id] = t
        }
    })

    let light = new THREE.DirectionalLight(0xffffff)
    light.position.set(1, 1, 1)
    scene.add(light)

    light = new THREE.DirectionalLight(0x002288)
    light.position.set(-1, -1, -1)
    scene.add(light)

    light = new THREE.AmbientLight(0x222222)
    scene.add(light)

    window.addEventListener('resize', onWindowResize, false)
    return s
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
}

function render() {
    renderer.render(scene, camera)
}

let prevPosition = {
    x: 0,
    y: 0,
    z: 0
}

function pulseViruses(delta) {
    Object.keys(allMeshes).filter(k => allMeshes[k].geometry === geoms.v)
        .forEach(k => {
            const scale = 1 + (Math.sin(delta * 0.005 + parseInt(k, 10)) / 50)
            allMeshes[k].scale.set(scale, scale, scale)
            allMeshes[k].updateMatrix()
        })
}

function animate(delta) {
    requestAnimationFrame(animate)
    controls.update() // required if controls.enableDamping = true, or if controls.autoRotate = true
    pulseViruses(delta)
    render()
    if (prevPosition.x !== camera.position.x
        || prevPosition.y !== camera.position.y
        || prevPosition.z !== camera.position.z) {
        socket.emit('position', {
            x: camera.position.x,
            y: camera.position.y,
            z: camera.position.z
        })
        prevPosition = {
            x: camera.position.x,
            y: camera.position.y,
            z: camera.position.z
        }
    }
}

let me

function updateLeaderboard() {
    leaderboardDom.innerHTML = Object.keys(leaderboard)
        .map(k => leaderboard[k])
        .sort((a, b) => a.m < b.m)
        .reduce((txt, p) => txt + `<div style="color: ${p.c}">${p.name} : ${Math.round(p.m)}</div>`, '')
}

function setupSocket(sock) {
    sock.on('pong', () => {
        debug('pong')
    })

    // Handle error.
    sock.on('connect_failed', () => {
        sock.close()
    })

    sock.on('disconnect', () => {
        sock.close()
    })

    // Handle connection.
    sock.on('welcome', (s) => {
        state = init(s)
        me = state.me
        nameLabel.innerText = `Name: ${me.name}`   //TODO: xss vulnerability - html encode
        animate()
    })

    sock.on('update', s => {
        const {changed, deleted} = s
        changed.forEach(t => {
            const mesh = allMeshes[t.id]
            if (mesh) {
                if (t.t === 'p' || t.t === 'b') {
                    const scale = t.r / state.config.startRadius
                    mesh.scale.set(scale, scale, scale)
                    controls.movementSpeed = movementSpeed / scale
                }
                mesh.position.set(t.x, t.y, t.z)
                mesh.updateMatrix()
            } else {
                console.log(`we got a new thing ${JSON.stringify(t)}`)
                scene.add(addBlob(Object.assign(t, {
                    shininess: shininess[t.t],
                    specular: specular[t.t],
                    geom: geoms[t.t]
                })))
            }
            if (t.id === me.id) {
                massLabel.innerText = `Mass: ${Math.round(t.m)}`
                radiusLabel.innerText = `Radius: ${Math.round(t.r)}`
                speedLabel.innerText = `Speed: ${Math.round(controls.movementSpeed * 100)}`
            }
            if (t.t === 'p') {
                leaderboard[t.id] = t
            }
        })
        deleted.forEach(id => {
            console.log(`deleted thing ${id}`)
            scene.remove(allMeshes[id])
            delete leaderboard[id]
            if (id === me.id) {
                alert('You is dead!')
                window.location.reload()
            }
            eatAudio.play()
        })
        updateLeaderboard()
    })
    return sock
}

function startGame(name, colour) {
    socket = setupSocket(io({query: `name=${name}&colour=${colour}`}))
}
<commit_msg>sort of a first person control system. Hard to get exactly right<commit_after>// IMPORT ASSETS
import '../css/App.scss'
import '../img/feed.png'
import '../img/split.png'
//import virusImage from '../img/virus.png'
import '../audio/spawn.mp3'
import '../audio/split.mp3'
import '../audio/plop.mp3'
import { THREE } from 'three'
import orbitFn from 'three-orbit-controls'
import flyFn from 'three-fly-controls'
import firstFn from 'three-first-person-controls'
const OrbitControls = orbitFn(THREE),
    FlyControls = flyFn(THREE),
    FirstPersonControls = firstFn(THREE)
import io from 'socket.io-client'

//TODO switch to FirstPersonControls

function debug(msg) {
    console.log(msg)
}

function $get(id) {
    return document.getElementById(id)
}

let camera, controls, scene, renderer, socket, state, me
const allMeshes = {},
    movementSpeed = 3,
    shininess = {
        f: 20,
        v: 150,
        p: 20,
        b: 20
    },
    specular = {
        f: 0x003300,
        v: 0xffffff,
        p: 0xffffff,
        b: 0xffffff
    }
let geoms = { }

const startBtn = $get('start'),
    startWrapper = $get('start-wrapper'),
    nameField = $get('name'),
    nameLabel = $get('my-name'),
    colourField = $get('colour'),
    massLabel = $get('my-mass'),
    radiusLabel = $get('my-radius'),
    speedLabel = $get('my-speed'),
    leaderboardDom = $get('leaderboard'),
    spawnAudio = $get('spawn_cell'),
    eatAudio = $get('eat'),
    leaderboard = {}
nameField.focus()

startBtn.addEventListener('click', () => {
    startGame(nameField.value, colourField.value)
    startWrapper.classList.add('hide')
})

function addBlob(options){
    const material = new THREE.MeshPhongMaterial({
            color: options.c,
            specular: options.specular,
            transparent: options.transparent || false,
            opacity: options.opacity || 1,
            wireframe: options.wireframe,
            shininess: options.shininess
        }),
        mesh = new THREE.Mesh(options.geom, material)
    mesh.position.x = options.x
    mesh.position.y = options.y
    mesh.position.z = options.z
    allMeshes[options.id] = mesh
    return mesh
}

function init(s) {
    scene = new THREE.Scene()
    scene.fog = new THREE.FogExp2(0xcccccc, 0.002)
    renderer = new THREE.WebGLRenderer()
    renderer.setClearColor(scene.fog.color)
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)

    const container = $get('container')
    container.appendChild(renderer.domElement)

    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000)
    camera.position.set(s.me.x, s.me.y, s.me.z)
    camera.lookAt(scene.position)

    const {things, config} = s
    geoms = {
        f: new THREE.SphereGeometry(config.foodRadius, 20, 20),
        v: new THREE.SphereGeometry(config.virusRadius, 20, 20),
        p: new THREE.SphereGeometry(config.startRadius, 20, 20),
        b: new THREE.SphereGeometry(config.startRadius, 20, 20)
    }

    things.forEach(t => {
        scene.add(addBlob(Object.assign(t, {
            shininess: shininess[t.t],
            specular: specular[t.t],
            transparent: t.id === s.me.id,
            opacity: t.id === s.me.id ? 0.3 : 1,
            wireframe: t.id === s.me.id,
            geom: geoms[t.t]
        })))
        if (t.t === 'p') {
            leaderboard[t.id] = t
        }
    })

    controls = THREE.FlyControls(camera, renderer.domElement)
    //controls = THREE.FirstPersonControls(allMeshes[s.me.id], renderer.domElement)
    controls.movementSpeed = movementSpeed
    controls.rollSpeed = 0.01

    let light = new THREE.DirectionalLight(0xffffff)
    light.position.set(1, 1, 1)
    scene.add(light)

    light = new THREE.DirectionalLight(0x002288)
    light.position.set(-1, -1, -1)
    scene.add(light)

    light = new THREE.AmbientLight(0x222222)
    scene.add(light)

    window.addEventListener('resize', onWindowResize, false)
    return s
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
}

function render() {
    renderer.render(scene, camera)
}

let prevPosition = {
    x: 0,
    y: 0,
    z: 0
}

function pulseViruses(delta) {
    Object.keys(allMeshes).filter(k => allMeshes[k].geometry === geoms.v)
        .forEach(k => {
            const scale = 1 + (Math.sin(delta * 0.005 + parseInt(k, 10)) / 50)
            allMeshes[k].scale.set(scale, scale, scale)
            allMeshes[k].updateMatrix()
        })
}

function animate(delta) {
    requestAnimationFrame(animate)
    pulseViruses(delta)
    controls.update(delta) // required if controls.enableDamping = true, or if controls.autoRotate = true

    render()

    const scale = me.r / state.config.startRadius,
        rel = new THREE.Vector3(1, -20, -140 * Math.sqrt(scale)),
        myMesh = allMeshes[me.id],
        offSet = rel.applyMatrix4(camera.matrix)
    myMesh.position.copy(offSet)

    socket.emit('position', {
        x: offSet.x,
        y: offSet.y,
        z: offSet.z
    })
}

function updateLeaderboard() {
    leaderboardDom.innerHTML = Object.keys(leaderboard)
        .map(k => leaderboard[k])
        .sort((a, b) => a.m < b.m)
        .reduce((txt, p) => txt + `<div style="color: ${p.c}">${p.name} : ${Math.round(p.m)}</div>`, '')
}

function setupSocket(sock) {
    sock.on('pong', () => {
        debug('pong')
    })

    // Handle error.
    sock.on('connect_failed', () => {
        sock.close()
    })

    sock.on('disconnect', () => {
        sock.close()
    })

    // Handle connection.
    sock.on('welcome', (s) => {
        state = init(s)
        me = state.me
        nameLabel.innerText = `Name: ${me.name}`   //TODO: xss vulnerability - html encode
        animate()
    })

    sock.on('update', s => {
        const {changed, deleted} = s
        changed.forEach(t => {
            const mesh = allMeshes[t.id]
            if (mesh) {
                if (t.t === 'p' || t.t === 'b') {
                    const scale = t.r / state.config.startRadius
                    mesh.scale.set(scale, scale, scale)
                    controls.movementSpeed = movementSpeed / scale
                }
                if (t.id !== me.id) {
                    mesh.position.set(t.x, t.y, t.z)
                }
            } else {
                console.log(`we got a new thing ${JSON.stringify(t)}`)
                scene.add(addBlob(Object.assign(t, {
                    shininess: shininess[t.t],
                    specular: specular[t.t],
                    geom: geoms[t.t]
                })))
            }
            if (t.id === me.id) {
                massLabel.innerText = `Mass: ${Math.round(t.m)}`
                radiusLabel.innerText = `Radius: ${Math.round(t.r)}`
                speedLabel.innerText = `Speed: ${Math.round(controls.movementSpeed * 100)}`
                me = t
            }
            if (t.t === 'p') {
                leaderboard[t.id] = t
            }
        })
        deleted.forEach(id => {
            console.log(`deleted thing ${id}`)
            scene.remove(allMeshes[id])
            delete leaderboard[id]
            if (id === me.id) {
                alert('You is dead!')
                window.location.reload()
            }
            eatAudio.play()
        })
        updateLeaderboard()
    })
    return sock
}

function startGame(name, colour) {
    socket = setupSocket(io({query: `name=${name}&colour=${colour}`}))
}
<|endoftext|>


<commit_before>var url_check;

//click admin button
var admin_click = function(name){
    var val = name;
    if ( val !== '' ) {
      var url = "admin.html?q=" + val;
      url_check = url;
      window.location.href = url ;
      return false;
    }
  };

//click team button
var team_click = function(name){
    var val = name ;
    if ( val !== '' ) {
      var url = "team.html?q=" + val;
      url_check = url;
      window.location.href = url ;
      return false;
    }
  };

//click member button
var member_click = function(name){
    var val = name;
    if ( val !== '' ) {
      var url = "member.html?q=" + val;
      url_check = url;
      window.location.href = url ;
      return false;
    }
  };

var onReady = function(){

  $("#btn_admin")[0].setAttribute('onclick', "admin_click($('#input_text').val())");

  $("#btn_leader")[0].setAttribute('onclick', "team_click($('#input_text').val())");

  $("#btn_member")[0].setAttribute('onclick', "member_click($('#input_text').val())");

}

$(document).ready(onReady);

angular.module("indx-app", ["firebase", "ngMaterial"])
.controller("IndxCtlr", function($scope, $firebaseObject, $firebaseArray, $window, $mdDialog) {
    initializeFirebase();

    /* Facebook Authentication */
    var provider = new firebase.auth.FacebookAuthProvider();

    // login function
    $scope.login = function() {
        firebase.auth().signInWithRedirect(provider);
    };

    firebase.auth().getRedirectResult().then(function(result) {
        if (result.credential) {
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = result.credential.accessToken;
        }
        // The signed-in user info.
        var user = result.user;
    }).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
    });

    // logout function
    $scope.logout = function() {
        firebase.auth().signOut().then(function() {
            // Sign-out successful.
            console.log('sign-out successful');
        }, function(error) {
            // An error happened.
            console.log('sign-out error');
        });
    };

    $scope.user = null;

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            // User is signed in.
            console.log(user);

            // update the user's profile
            var userRef = firebase.database().ref().child("users").child(user.uid);
            var userObj = $firebaseObject(userRef);

            userRef.update({name: user.displayName});

            // refresh the scope
            $scope.$apply(function() {
                $scope.user = user;
            });
        } else {
            // No user is signed in.
            console.log('no user is signed in');

            // refresh the scope
            $scope.$apply(function() {
                $scope.user = null;
            });
        }
    });

    /* events */
    var eventRef = firebase.database().ref().child("events");

    var eventObj = $firebaseObject(eventRef);
    eventObj.$bindTo($scope, "events");

    // create new event function
    $scope.createEvent = function() {
        var eventNameInput = $mdDialog.prompt()
            .title("Create a New Event")
            .ok("Create")
            .cancel("Cancel");

        $mdDialog.show(eventNameInput)
            .then(function(event) {
                $window.open("admin.html?q=" + event, "_self");
            });
    };

    // join event function
    $scope.joinEvent = function(eventName) {
        var userProfileRef = firebase.database().ref().child("users").child($scope.user.uid);
        var userProfileObj = $firebaseObject(userProfileRef);

        userProfileObj.$loaded().then(function(userProfile) {
            // add the event to the user's profile
            var userEventsRef = firebase.database().ref().child("users").child($scope.user.uid).child("events").child(eventName);

            userEventsRef.update({team: ""});

            var member = {};
            member[$scope.user.uid] = {name: $scope.user.displayName, skills: userProfile.skills};

            var eventMemberRef = firebase.database().ref().child("events").child(eventName).child("member");
            var eventMemberObj = $firebaseObject(eventMemberRef);

            eventMemberRef.update(member);
        });
    };
})
.config(function($mdThemingProvider) {
    $mdThemingProvider.theme('default')
    .primaryPalette('blue')
    .accentPalette('indigo');
});<commit_msg>Delete main.js<commit_after><|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var should = require('should');
var util = require('util');
var CLITest = require('../../../framework/arm-cli-test');
var profile = require('../../../../lib/util/profile');
var utils = require('../../../../lib/util/utils');

var testPrefix = 'arm-cli-webapp-tests';

var sitename;
var createdSites = [];
var location = 'West US';
var createdGroups = [];
var createdResources = [];
var subscription = profile.current.getSubscription();
var resourceClient = utils.createResourceClient(subscription);
var hostingPlanName, groupName;

describe('arm', function () {
  var suite;

  before(function (done) {
    suite = new CLITest(this, testPrefix);
    suite.setupSuite(function () {
      sitename = suite.generateId('webappclitest', createdSites);
      groupName = suite.generateId('testrg1', createdGroups);
      if (!suite.isPlayback()) {
        suite.execute('group create %s --location %s --json', groupName, location, function (result) {
          result.exitStatus.should.equal(0);
          createHostingPlan(groupName, function (err, planId) {
            if (err) { return done(err); }
            done();
          });
        });
      } else {
        done();
      }

    });
  });

  after(function (done) {
    suite.teardownSuite(function () {
      if (!suite.isPlayback()) {
        createdGroups.forEach(function (item) {
          suite.execute('group delete %s --quiet --json', item, function (result) {
            result.exitStatus.should.equal(0);
            done();
          })
        });
      } else {
        done();
      }
    });
  });

  beforeEach(function (done) {
    suite.setupTest(done);
  });

  afterEach(function (done) {
    suite.teardownTest(done);
  });

  describe('webapp', function () {

    it('create should work', function (done) {
      suite.execute('webapp create --resourcegroup %s --name %s --location %s --plan %s --json', groupName, sitename, location, hostingPlanName, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('list should work', function (done) {
      suite.execute('webapp list --resourcegroup %s --json', groupName, function (result) {
        result.exitStatus.should.equal(0);
        var output = JSON.parse(result.text);
        output.length.should.be.above(0);
        done();
      });
    });

    it('show should work', function (done) {
      suite.execute('webapp show --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        var webapp = JSON.parse(result.text);
        webapp.webSite.name.should.equal(sitename);
        done();
      });
    });

    it('stop should work', function (done) {
      suite.execute('webapp stop --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('start should work', function (done) {
      suite.execute('webapp start --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('restart should work', function (done) {
      suite.execute('webapp restart --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('delete should work', function (done) {
      suite.execute('webapp delete --resourcegroup %s --name %s -q --json', groupName, createdSites[0], function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });
  });

  function createGroupAndPlan(done) {
    createGroup(function (err, groupName) {
      if (err) { return done(err); }
      createHostingPlan(groupName, function (err, planId) {
        if (err) { return done(err); }
        return done(null, { group: groupName, plan: planId });
      });
    });
  }

  function createHostingPlan(groupName, done) {
    hostingPlanName = suite.generateId(testPrefix, createdResources);
    var planToCreate = {
      resourceName: hostingPlanName,
      resourceProviderNamespace: 'Microsoft.Web',
      resourceType: 'serverFarms',
      resourceProviderApiVersion: '2014-06-01'
    };

    var planParameters = {
      properties: {
        sku: 'Free',
        numberOfWorkers: 1,
        workerSize: 'Small',
        hostingPlanName: hostingPlanName
      },
      location: location
    };

    resourceClient.resources.createOrUpdate(groupName, planToCreate, planParameters, function (err, planResource) {
      return done(err, planResource.resource.id);
    });
  }
});<commit_msg>try to mitigate a flakiness in webapp command<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var should = require('should');
var util = require('util');
var CLITest = require('../../../framework/arm-cli-test');
var profile = require('../../../../lib/util/profile');
var utils = require('../../../../lib/util/utils');

var testPrefix = 'arm-cli-webapp-tests';

var sitename;
var createdSites = [];
var location = 'West US';
var createdGroups = [];
var createdResources = [];
var hostingPlanName, groupName;
var resourceClient;

describe('arm', function () {
  var suite;

  before(function (done) {
    suite = new CLITest(this, testPrefix);
    suite.setupSuite(function () {
      sitename = suite.generateId('webappclitest', createdSites);
      groupName = suite.generateId('testrg1', createdGroups);
      var subscription = profile.current.getSubscription();
      resourceClient = utils.createResourceClient(subscription);
      if (!suite.isPlayback()) {
        suite.execute('group create %s --location %s --json', groupName, location, function (result) {
          result.exitStatus.should.equal(0);
          createHostingPlan(groupName, function (err, planId) {
            if (err) { return done(err); }
            done();
          });
        });
      } else {
        done();
      }

    });
  });

  after(function (done) {
    suite.teardownSuite(function () {
      if (!suite.isPlayback()) {
        createdGroups.forEach(function (item) {
          suite.execute('group delete %s --quiet --json', item, function (result) {
            result.exitStatus.should.equal(0);
            done();
          })
        });
      } else {
        done();
      }
    });
  });

  beforeEach(function (done) {
    suite.setupTest(done);
  });

  afterEach(function (done) {
    suite.teardownTest(done);
  });

  describe('webapp', function () {

    it('create should work', function (done) {
      suite.execute('webapp create --resourcegroup %s --name %s --location %s --plan %s --json', groupName, sitename, location, hostingPlanName, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('list should work', function (done) {
      suite.execute('webapp list --resourcegroup %s --json', groupName, function (result) {
        result.exitStatus.should.equal(0);
        var output = JSON.parse(result.text);
        output.length.should.be.above(0);
        done();
      });
    });

    it('show should work', function (done) {
      suite.execute('webapp show --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        var webapp = JSON.parse(result.text);
        webapp.webSite.name.should.equal(sitename);
        done();
      });
    });

    it('stop should work', function (done) {
      suite.execute('webapp stop --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('start should work', function (done) {
      suite.execute('webapp start --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('restart should work', function (done) {
      suite.execute('webapp restart --resourcegroup %s --name %s --json', groupName, sitename, function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });

    it('delete should work', function (done) {
      suite.execute('webapp delete --resourcegroup %s --name %s -q --json', groupName, createdSites[0], function (result) {
        result.exitStatus.should.equal(0);
        done();
      });
    });
  });

  function createGroupAndPlan(done) {
    createGroup(function (err, groupName) {
      if (err) { return done(err); }
      createHostingPlan(groupName, function (err, planId) {
        if (err) { return done(err); }
        return done(null, { group: groupName, plan: planId });
      });
    });
  }

  function createHostingPlan(groupName, done) {
    hostingPlanName = suite.generateId(testPrefix, createdResources);
    var planToCreate = {
      resourceName: hostingPlanName,
      resourceProviderNamespace: 'Microsoft.Web',
      resourceType: 'serverFarms',
      resourceProviderApiVersion: '2014-06-01'
    };

    var planParameters = {
      properties: {
        sku: 'Free',
        numberOfWorkers: 1,
        workerSize: 'Small',
        hostingPlanName: hostingPlanName
      },
      location: location
    };

    resourceClient.resources.createOrUpdate(groupName, planToCreate, planParameters, function (err, planResource) {
      return done(err, planResource.resource.id);
    });
  }
});<|endoftext|>


<commit_before>'use strict';

const DriveWatch = require('drive-watch');

let callbacks = [];

function runCallbacks(eventType, driveName) {
	console.log(`${eventType} on ${driveName}`);

	if (eventType !== 'mount') {
		return;
	}

	callbacks.forEach(callback => callback(driveName));
}

const dw = new DriveWatch(runCallbacks, {
	scanInterval: 60000
});

dw.start();

exports = module.exports = {
	watch: (callback) => {
		if (typeof callback === 'function') {
			callbacks.push(callback);
		}
	},
	unwatch: (callback) => {
		let index = callbacks.indexOf(callback);

		if (index >= 0) {
			callbacks = callbacks
				.slice(0, index)
				.concat(callbacks.slice(index + 1));
		}
	}
};<commit_msg>Wait for a bit before running<commit_after>'use strict';

const DriveWatch = require('drive-watch');

let callbacks = [];

function runCallbacks(eventType, driveName) {
	console.log(`${eventType} on ${driveName}`);

	if (eventType !== 'mount') {
		return;
	}

	setTimeout(() => callbacks.forEach(callback => callback(driveName)), 10000);
}

const dw = new DriveWatch(runCallbacks, {
	scanInterval: 60000
});

dw.start();

exports = module.exports = {
	watch: (callback) => {
		if (typeof callback === 'function') {
			callbacks.push(callback);
		}
	},
	unwatch: (callback) => {
		let index = callbacks.indexOf(callback);

		if (index >= 0) {
			callbacks = callbacks
				.slice(0, index)
				.concat(callbacks.slice(index + 1));
		}
	}
};<|endoftext|>


<commit_before>var easey = {};
// Handle double clicks, that zoom the map in one zoom level.
easey.DoubleClickHandler = function(map) {
    if (map !== undefined) {
        this.init(map);
    }
};

easey.DoubleClickHandler.prototype = {

    init: function(map) {
        this.map = map;
        com.modestmaps.addEvent(map.parent, 'dblclick', this.getDoubleClick());
    },

    doubleClickHandler: null,

    getDoubleClick: function() {
        // Ensure that this handler is attached once.
        if (!this.doubleClickHandler) {
            var theHandler = this;
            this.doubleClickHandler = function(e) {
                // Get the point on the map that was double-clicked
                var point = com.modestmaps.getMousePoint(e, theHandler.map);
                var n = 0;

                var zi = window.setInterval(function z() {
                    // use shift-double-click to zoom out
                    theHandler.map.zoomByAbout(e.shiftKey ? -0.1 : 0.1, point);
                    if (++n === 10) {
                        window.clearInterval(zi);
                        theHandler.map.setZoom(Math.round(theHandler.map.getZoom()));
                    }
                }, 5);

                return com.modestmaps.cancelEvent(e);
            };
        }
        return this.doubleClickHandler;
    }
};
<commit_msg>Simple easeIN<commit_after>var easey = {};

// Handle double clicks, that zoom the map in one zoom level.
easey.DoubleClickHandler = function(map) {
    if (map !== undefined) {
        this.init(map);
    }
};

easey.DoubleClickHandler.prototype = {

    init: function(map) {
        this.map = map;
        com.modestmaps.addEvent(map.parent, 'dblclick', this.getDoubleClick());
    },

    doubleClickHandler: null,

    getDoubleClick: function() {
        function easeIn(t) {
            return t * t;
        }

        // Ensure that this handler is attached once.
        if (!this.doubleClickHandler) {
            var theHandler = this;
            this.doubleClickHandler = function(e) {
                // Get the point on the map that was double-clicked
                var point = com.modestmaps.getMousePoint(e, theHandler.map);
                var n = 0;
                var duration = 100;

                var start = +new Date();
                var zs = theHandler.map.getZoom();
                var zc = theHandler.map.getCenter();
                var zi = window.setInterval(function z() {
                    // use shift-double-click to zoom out
                    var delta = +new Date() - start;
                    if (delta > duration) {
                        window.clearInterval(zi);
                        theHandler.map.setZoom(Math.round(theHandler.map.getZoom()));
                        return;
                    }
                    var t = delta / duration;
                    var za = zs + (easeIn(t) * (e.shiftKey ? -1 : 1));
                    theHandler.map.setZoom(za);
                }, 0);

                return com.modestmaps.cancelEvent(e);
            };
        }
        return this.doubleClickHandler;
    }
};
<|endoftext|>


<commit_before>var citizens = [];
var candidates = [];

var availableParties = [];
var availableCitizenAttributes = [];
var availableLocations = [];

function AttributeContainer(name, listOfAttributes){
	this.name = name;
	this.listOfAttributes = listOfAttributes;
}

AttributeContainer.prototype.getAttribute = function(){
	return this.listOfAttributes[Math.floor(Math.random() * this.listOfAttributes.length)];
}

function Citizen(party, attributes){
	this.party = party;
	this.attributes = attributes;
}

Citizen.prototype.hasAttribute = function(name){
	var index = this.attributes.indexOf(name);
	if(index == -1){
		return false;
	}
	else{
		return true;
	}
}

function Policy(title, positiveAffectedAttribute, negativeAffectedAttribute){
	this.title = title;
	this.positiveAffectedAttribute = positiveAffectedAttribute;
	this.negativeAffectedAttribute = negativeAffectedAttribute;
}

Policy.prototype.getPeoplePositivelyAffected = function(){
	var total = 0;
	for(var index = 0; index < citizens.length; index++){
		var citizen = citizens[index];
		if(citizen.hasAttribute(this.positiveAffectedAttribute)){
			total++;
		}
	}
	return total;
}

Policy.prototype.getPeopleNegativelyAffected = function(){
	var total = 0;
	for(var index = 0; index < citizens.length; index++){
		var citizen = citizens[index];
		if(citizen.hasAttribute(this.negativeAffectedAttribute)){
			total++;
		}
	}
	return total;
}

function Candidate(name, location, party, policies){
	this.name = name;
	this.location = location;
	this.party = party;
	this.policies = policies;
}

/*
* Used for creating game data when the game is loaded
*/
function init(){
	availableCitizenAttributes = [
	new AttributeContainer("Income", ["Lower class", "Middle class", "Upper class"]),
	new AttributeContainer("Age", ["Young", "Middle aged", "Elderly"]),
	new AttributeContainer("Job", ["Business owner", "Employed", "Not Employed"]),
	new AttributeContainer("Family", ["Parent", "Not parent"]),
	new AttributeContainer("Military", ["Active duty", "Veteran", "Civilian"]),
	new AttributeContainer("Criminal Record", ["Imprisoned", "Past record", "Clean record"]),
	new AttributeContainer("Communte Style", ["Car", "Bike", "Public transportation"])
	];
	availableParties = ["ReDublican Party", "DemoRat Party", "Ibertarian Party",
	"Lependent Party", "Labo Party", "Riberal Party"];
	availableLocations = ["Slightly New York", "The Outback", "Mars", "ISS", "Kalifornia",
	"FloorIda", "Wishonsolo", "The Choclate Factory", "Paris, Le French", "The North Pole",
	"West Korea", "Mother Russia", "象形字關転"];
	test();
}

//new AttributeContainer("", []),

/*
* Dynamically generate the UI
*/
$(document).ready(function(){

	var containerDiv = $('.container');
	for(var index = 0; index < candidates.length; index++){
		var candidate = candidates[index];
		var candidateDiv = $('

');

		var candidateName = $('

');
		$(candidateName).text(candidate.name);
		var candidateInfo = $('

');
		$(candidateInfo).text(candidate.location + " " + candidate.party);
		var policyHeader = $('
Policies
');

		candidateDiv.append(candidateName);
		candidateDiv.append(candidateInfo);
		candidateDiv.append(policyHeader);

		for(var pIndex = 0; pIndex < candidate.policies.length; pIndex++){
			var policy = candidate.policies[pIndex];

			var policyTitle = $('

');
			policyTitle.text(policy.title);
			candidateDiv.append(policyTitle);

			var policyEffects = $('

');
			var totalCitizens = citizens.length;
			var posEffect = (policy.getPeoplePositivelyAffected() / totalCitizens) * 100;
			var negEffect = (policy.getPeopleNegativelyAffected() / totalCitizens) * 100;
			var percentEffected = negEffect + posEffect;
			posEffect = posEffect.toFixed(2);
			negEffect = negEffect.toFixed(2);
			percentEffected = percentEffected.toFixed(2);
			$(policyEffects).text(percentEffected + "% of the population is effected by this policy. Of these people " + posEffect + "% positively and " + negEffect + "% negatively.")
			candidateDiv.append(policyEffects);
		}

		var seperator = $('
');
		candidateDiv.append(seperator);

		containerDiv.append(candidateDiv);
	}

	//After everything is done
	$('.REMOVE-AFTER-LOAD').remove();
});

function test(){
	for(var cIndex = 0; cIndex < 100; cIndex++){
		var party = getRandomParty();
		var attributes = [];
		for(aIndex = 0; aIndex < availableCitizenAttributes.length; aIndex++){
			attributes.push(availableCitizenAttributes[aIndex].getAttribute());
		}
		//console.log(party + " " + attributes); //These results are pretty funny
		citizens.push(new Citizen(party, attributes));
	}
	citizens.push(new Citizen("t1", ["good"]));
	citizens.push(new Citizen("t2", ["bad"]));
	citizens.push(new Citizen("t3", ["good"]));
	candidates.push(new Candidate("Senator Poopy Head", "Mars", "Toilet party", [new Policy("Test policy", "good", "bad"), new Policy("Test policy 2", "bad", "good")]));
	candidates.push(new Candidate("Mayor Poopy Head", "Mars", "Toilet party", [new Policy("Test policy", "good", "bad"), new Policy("Test policy 2", "bad", "good")]));
}

function getRandomParty(){
	return availableParties[Math.floor(Math.random() * availableParties.length)];
}<commit_msg>Did candidate generation and policies<commit_after>var citizens = [];
var candidates = [];

var availableParties = [];
var availableCitizenAttributes = [];
var availableLocations = [];
var availablePolicies = [];

function AttributeContainer(name, listOfAttributes){
	this.name = name;
	this.listOfAttributes = listOfAttributes;
}

AttributeContainer.prototype.getAttribute = function(){
	return this.listOfAttributes[Math.floor(Math.random() * this.listOfAttributes.length)];
}

function PolicyContainer(name, listOfPolicies){
	this.name = name;
	this.listOfPolicies = listOfPolicies;
}

PolicyContainer.prototype.getPolicy = function(){
	return this.listOfPolicies[Math.floor(Math.random() * this.listOfPolicies.length)];
}

function Citizen(party, attributes){
	this.party = party;
	this.attributes = attributes;
}

Citizen.prototype.hasAttribute = function(name){
	var index = this.attributes.indexOf(name);
	if(index == -1){
		return false;
	}
	else{
		return true;
	}
}

function Policy(title, positiveAffectedAttribute, negativeAffectedAttribute){
	this.title = title;
	this.positiveAffectedAttribute = positiveAffectedAttribute;
	this.negativeAffectedAttribute = negativeAffectedAttribute;
}

Policy.prototype.getPeoplePositivelyAffected = function(){
	var total = 0;
	for(var index = 0; index < citizens.length; index++){
		var citizen = citizens[index];
		if(citizen.hasAttribute(this.positiveAffectedAttribute)){
			total++;
		}
	}
	return total;
}

Policy.prototype.getPeopleNegativelyAffected = function(){
	var total = 0;
	for(var index = 0; index < citizens.length; index++){
		var citizen = citizens[index];
		if(citizen.hasAttribute(this.negativeAffectedAttribute)){
			total++;
		}
	}
	return total;
}

function Candidate(name, location, party, policies){
	this.name = name;
	this.location = location;
	this.party = party;
	this.policies = policies;
}

/*
* Used for creating game data when the game is loaded
*/
function init(){
	availableCitizenAttributes = [
	new AttributeContainer("Income", ["Lower class", "Middle class", "Upper class"]),
	new AttributeContainer("Age", ["Young", "Middle aged", "Elderly"]),
	new AttributeContainer("Job", ["Business owner", "Employed", "Not Employed"]),
	new AttributeContainer("Family", ["Parent", "Not parent"]),
	new AttributeContainer("Military", ["Active duty", "Veteran", "Civilian"]),
	new AttributeContainer("Criminal Record", ["Imprisoned", "Past record", "Clean record"]),
	new AttributeContainer("Communte Style", ["Car", "Bike", "Public transportation"]),
	new AttributeContainer("Activist", ["Anti-Violence", "Human Rights", "Not Activist"])
	];
	availablePolicies = [
		/*new PolicyContainer("Tax",
		[
			new Policy("Raise middle class tax", "", "Middle class"),
			new Policy("Lower middle class tax", "Middle class", ""),
			new Policy("Raise upper class tax & lower the middle class tax", "Middle class", "Upper class")
		]),*/
		new PolicyContainer("Public Transportation",[
			new Policy("Lower public transportation budget", "Car", "Public transportation"),
			new Policy("Raise public transportation budget", "Public transportation", "Car"),
			new Policy("Lower public transportation fair", "Public transportation", "Car"),
			new Policy("Raise public transportation fair", "Car", "Public transportation"),
			new Policy("Expand public transportation network", "Public transportation", "Car"),
			new Policy("Decrease public transportation network", "Car", "Public transportation")
		]),
		new PolicyContainer("Automobiles", [
			new Policy("Raise car tax", "Public transportation", "Car"),
			new Policy("Lower car tax", "Car", "Public transportation"),
			new Policy("Raise gas prices", "Bike", "Car"),
			new Policy("Lower gas prices", "Car", "Bike"),
			new Policy("Give tax benefits to zero emision commuters", "Bike", "Car")
		]),
		new PolicyContainer("Military", [
			new Policy("Lower Military budget", "Anti-Violence", "Active duty"),
			new Policy("Raise Military budget", "Active duty", "Anti-Violence"),
			new Policy("Increse veteran benefits", "Veteran", "Civilian"),
			new Policy("Decrease veteran benefits", "Civilian", "Veteran"),
			new Policy("Increase Military research budget", "Active duty", "Anti-Violence"),
			new Policy("Reduce Military research budget", "Anti-Violence", "Active duty")
		]),
		new PolicyContainer("Employment", [
			new Policy("Raise unemployment benefits", "Not Employed", "Employed"),
			new Policy("Lower unemployment benefits", "Employed", "Not Employed"),
			new Policy("Raise income tax", "Transportation", "Employed"),
			new Policy("Lower income tax", "Employed", "Transportation")
		]),
		new PolicyContainer("Business", [
			new Policy("Raise Business tax", "Transportation", "Business owner"),
			new Policy("Lower Business tax", "Business owner", "Transportation"),
			new Policy("Support small Business", "Business owner", "Upper class")
		])

		//Criminal stuff
		//Gov. aid
		//Law

	];
	availableParties = ["ReDublican Party", "DemoRat Party", "Ibertarian Party",
	"Lependent Party", "Labo Party", "Riberal Party"];
	availableLocations = ["Slightly New York", "The Outback", "Mars", "ISS", "Kalifornia",
	"FloorIda", "Wishonsolo", "The Choclate Factory", "Paris, Le French", "The North Pole",
	"West Korea", "Mother Russia", "象形字關転"];
	test();
}

/*
* Dynamically generate the UI
*/
$(document).ready(function(){

	var containerDiv = $('.container');
	for(var index = 0; index < candidates.length; index++){
		var candidate = candidates[index];
		var candidateDiv = $('

');

		var candidateName = $('

');
		$(candidateName).text(candidate.name);
		var candidateInfo = $('

');
		$(candidateInfo).text(candidate.location + " " + candidate.party);
		var policyHeader = $('
Policies
');

		candidateDiv.append(candidateName);
		candidateDiv.append(candidateInfo);
		candidateDiv.append(policyHeader);

		for(var pIndex = 0; pIndex < candidate.policies.length; pIndex++){
			var policy = candidate.policies[pIndex];

			var policyTitle = $('

');
			policyTitle.text(policy.title);
			candidateDiv.append(policyTitle);

			var policyEffects = $('

');
			var totalCitizens = citizens.length;
			var posEffect = (policy.getPeoplePositivelyAffected() / totalCitizens) * 100;
			var negEffect = (policy.getPeopleNegativelyAffected() / totalCitizens) * 100;
			var percentEffected = negEffect + posEffect;
			posEffect = posEffect.toFixed(0);
			negEffect = negEffect.toFixed(0);
			percentEffected = percentEffected.toFixed(0);
			$(policyEffects).text(percentEffected + "% of the population is effected by this policy. Of these people " + posEffect + "% are affected positively and " + negEffect + "% are affected negatively.")
			candidateDiv.append(policyEffects);
		}

		var seperator = $('
');
		candidateDiv.append(seperator);

		containerDiv.append(candidateDiv);
	}

	//After everything is done
	$('.REMOVE-AFTER-LOAD').remove();
});

function test(){
	generateCitizens();
	generateCandidates();
	//candidates.push(new Candidate("Senator Poopy Head", "Mars", "Toilet party", [new Policy("Raise middle class tax", "", "Middle class"), new Policy("Test policy 2", "bad", "good")]));
	//candidates.push(new Candidate("Mayor Poopy Head", "Mars", "Toilet party", [new Policy("Test policy", "good", "bad"), new Policy("Test policy 2", "bad", "good")]));
}

function generateCitizens(){
	for(var cIndex = 0; cIndex < 100; cIndex++){
		var party = getRandomParty();
		var attributes = [];
		for(aIndex = 0; aIndex < availableCitizenAttributes.length; aIndex++){
			attributes.push(availableCitizenAttributes[aIndex].getAttribute());
		}
		//console.log(party + " " + attributes); //These results are pretty funny
		citizens.push(new Citizen(party, attributes));
	}
}

function generateCandidates(){
	for(var cIndex = 0; cIndex < 3; cIndex++){
		var party = getRandomParty();
		var policies = [];
		for(pIndex = 0; pIndex < availablePolicies.length; pIndex++){
			policies.push(availablePolicies[pIndex].getPolicy());
		}
		//console.log(party + " " + policies);
		candidates.push(new Candidate("Test name # " + cIndex, getRandomLocation(), party, policies));
	}
}

function getRandomParty(){
	return availableParties[Math.floor(Math.random() * availableParties.length)];
}

function getRandomLocation(){
	return availableLocations[Math.floor(Math.random() * availableLocations.length)];
}<|endoftext|>


<commit_before>define(
  'ephox.echo.api.AriaGrid',

  [
    'ephox.echo.api.Styles',
    'ephox.epithet.Id',
    'ephox.scullion.Struct',
    'ephox.sugar.api.Attr',
    'ephox.sugar.api.Class',
    'ephox.sugar.api.Element',
    'ephox.sugar.api.Insert'
  ],

  function (Styles, Id, Struct, Attr, Class, Element, Insert) {
    var help = Struct.immutable('help', 'ids');

    var base = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'grid'
      });
    };

    var row = function (element) {
      Attr.set(element, 'role', 'row');
    };

    var cell = function (element, labelledby) {
      Attr.setAll(element, {
        'role': 'gridcell',
        'aria-labelledby': labelledby
      });
    };

    var createHelp = function (rows, cols, translations) {
      var gridHelp = Element.fromTag('div');
      Class.add(gridHelp, Styles.resolve('aria-help'));

      // TODO: snooker util.repeat instead of mutation
      var ids = [];
      for (var rowNum = 0; rowNum < rows; rowNum++) {
        // Temporary non-random number until we get it right
        var rowId = Id.generate('ephox-aria');
        var rowHelp = Element.fromTag('span');
        Attr.set(rowHelp, 'id', rowId);
        Class.add(rowHelp, Styles.resolve('aria-help'));
        Insert.append(rowHelp, Element.fromText(translations.row(rowNum + 1)));
        Insert.append(gridHelp, rowHelp);

        // TODO: snooker util.repeat instead of mutation
        ids[rowNum] = [];
        for (var colNum = 0; colNum < cols; colNum++) {
          // Temporary non-random number until we get it right
          var colId = Id.generate('ephox-aria');
          var cellHelp = Element.fromTag('span');
          Attr.set(cellHelp, 'id', colId);
          Class.add(cellHelp, Styles.resolve('aria-help'));
          Insert.append(cellHelp, Element.fromText(translations.col(colNum + 1)));
          Insert.append(gridHelp, cellHelp);

          ids[rowNum][colNum] = colId + ' ' + rowId;
        }
      }
      return help(gridHelp, ids);
    };

    return {
      base: base,
      row: row,
      cell: cell,
      createHelp: createHelp
    };
  }
);<commit_msg>Stop creating a quadratic number of span tags with the same content but different IDs<commit_after>define(
  'ephox.echo.api.AriaGrid',

  [
    'ephox.echo.api.Styles',
    'ephox.epithet.Id',
    'ephox.scullion.Struct',
    'ephox.sugar.api.Attr',
    'ephox.sugar.api.Class',
    'ephox.sugar.api.Element',
    'ephox.sugar.api.Insert'
  ],

  function (Styles, Id, Struct, Attr, Class, Element, Insert) {
    var help = Struct.immutable('help', 'ids');

    var base = function (element, label) {
      Attr.setAll(element, {
        'aria-label': label,
        'role': 'grid'
      });
    };

    var row = function (element) {
      Attr.set(element, 'role', 'row');
    };

    var cell = function (element, labelledby) {
      Attr.setAll(element, {
        'role': 'gridcell',
        'aria-labelledby': labelledby
      });
    };

    var createHelp = function (rows, cols, translations) {
      var gridHelp = Element.fromTag('div');
      Class.add(gridHelp, Styles.resolve('aria-help'));

      var colIds = [];
      // TODO: snooker util.repeat instead of mutation
      for (var colHelp = 0; colHelp < cols; colHelp++) {
        // Temporary non-random number until we get it right
        var colId = Id.generate('ephox-aria');
        var cellHelp = Element.fromTag('span');
        Attr.set(cellHelp, 'id', colId);
        Class.add(cellHelp, Styles.resolve('aria-help'));
        Insert.append(cellHelp, Element.fromText(translations.col(colHelp + 1)));
        Insert.append(gridHelp, cellHelp);

        colIds[colHelp] = colId;
      }

      // TODO: snooker util.repeat instead of mutation
      var ids = [];
      for (var rowNum = 0; rowNum < rows; rowNum++) {
        // Temporary non-random number until we get it right
        var rowId = Id.generate('ephox-aria');
        var rowHelp = Element.fromTag('span');
        Attr.set(rowHelp, 'id', rowId);
        Class.add(rowHelp, Styles.resolve('aria-help'));
        Insert.append(rowHelp, Element.fromText(translations.row(rowNum + 1)));
        Insert.append(gridHelp, rowHelp);

        ids[rowNum] = [];
        // TODO: snooker util.repeat instead of mutation
        for (var colNum = 0; colNum < cols; colNum++) {
          ids[rowNum][colNum] = colIds[colNum] + ' ' + rowId;
        }

      }
      return help(gridHelp, ids);
    };

    return {
      base: base,
      row: row,
      cell: cell,
      createHelp: createHelp
    };
  }
);<|endoftext|>


<commit_before>/*
 * Copyright 2015 Hewlett Packard Enterprise Development Company LP
 * (c) Copyright 2015 ThoughtWorks Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function () {
  'use strict';

  /**
   * @ngdoc controller
   * @name LaunchInstanceDetailsController
   * @description
   * The `LaunchInstanceDetailsController` controller provides functions for
   * configuring the details step of the Launch Instance Wizard.
   *
   */
  angular
    .module('horizon.dashboard.project.workflow.launch-instance')
    .controller('LaunchInstanceDetailsController', LaunchInstanceDetailsController);

  LaunchInstanceDetailsController.$inject = [
    '$scope',
    'horizon.framework.widgets.charts.donutChartSettings',
    'horizon.framework.widgets.charts.quotaChartDefaults'
  ];

  function LaunchInstanceDetailsController($scope,
    donutChartSettings,
    quotaChartDefaults
  ) {

    var ctrl = this;

    // Error text for invalid fields
    ctrl.instanceNameError = gettext('A name is required for your instance.');
    ctrl.instanceCountError = gettext(
      'Instance count is required and must be an integer of at least 1'
    );
    ctrl.maxInstanceCount = 1;

    /*
     * Donut chart
     */
    ctrl.chartSettings = donutChartSettings;
    ctrl.maxInstances = 1; // Must have default value > 0
    ctrl.totalInstancesUsed = 0;

    if ($scope.model.novaLimits && $scope.model.novaLimits.maxTotalInstances) {
      ctrl.maxInstances = $scope.model.novaLimits.maxTotalInstances;
    }

    if ($scope.model.novaLimits && $scope.model.novaLimits.totalInstancesUsed) {
      ctrl.totalInstancesUsed = $scope.model.novaLimits.totalInstancesUsed;
    }

    ctrl.instanceStats = {
      title: gettext('Total Instances'),
      maxLimit: ctrl.maxInstances,
      label: '100%',
      data: [
        {
          label: quotaChartDefaults.usageLabel,
          value: 1,
          colorClass: quotaChartDefaults.usageColorClass
        },
        {
          label: quotaChartDefaults.addedLabel,
          value: 1,
          colorClass: quotaChartDefaults.addedColorClass
        },
        {
          label: quotaChartDefaults.remainingLabel,
          value: 1,
          colorClass: quotaChartDefaults.remainingColorClass
        }
      ]
    };

    syncInstanceChartAndLimits();

    var specifiedInstancesWatcher = createWatcher(getInstanceCount, updateChart);
    var maxInstancesWatcher = createWatcher(getMaxInstances, resetMaxInstances);
    var instancesUsedWatcher = createWatcher(getTotalInstancesUsed, resetTotalInstancesUsed);

    // Explicitly remove watchers on desruction of this controller
    $scope.$on('$destroy', function() {
      specifiedInstancesWatcher();
      maxInstancesWatcher();
      instancesUsedWatcher();
    });

    ////////////////////

    function getMaxInstances() {
      return $scope.model.novaLimits.maxTotalInstances;
    }

    function resetMaxInstances(newMaxInstances) {
      ctrl.maxInstances = Math.max(1, newMaxInstances);
      syncInstanceChartAndLimits();
    }

    function getTotalInstancesUsed() {
      return $scope.model.novaLimits.totalInstancesUsed;
    }

    function resetTotalInstancesUsed() {
      ctrl.totalInstancesUsed = $scope.model.novaLimits.totalInstancesUsed;
      syncInstanceChartAndLimits();
    }

    function getInstanceCount() {
      return $scope.model.newInstanceSpec.instance_count;
    }

    function createWatcher(watchExpression, listener) {
      return $scope.$watch(
        watchExpression,
        function (newValue, oldValue) {
          if (newValue !== oldValue) {
            listener(newValue);
          }
        }
      );
    }

    function syncInstanceChartAndLimits() {
      updateChart();
      updateMaxInstanceCount();
    }

    function updateChart() {

      // Initialize instance_count to 1
      if ($scope.model.newInstanceSpec.instance_count <= 0) {
        $scope.model.newInstanceSpec.instance_count = 1;
      }

      var data = ctrl.instanceStats.data;
      var added = $scope.model.newInstanceSpec.instance_count || 1;
      var remaining = Math.max(0, ctrl.maxInstances - ctrl.totalInstancesUsed - added);

      ctrl.instanceStats.maxLimit = ctrl.maxInstances;
      data[0].value = ctrl.totalInstancesUsed;
      data[1].value = added;
      data[2].value = remaining;
      var quotaCalc = Math.round((ctrl.totalInstancesUsed + added) / ctrl.maxInstances * 100);
      ctrl.instanceStats.overMax = quotaCalc > 100 ? true : false;
      ctrl.instanceStats.label = quotaCalc + '%';
      ctrl.instanceStats = angular.extend({}, ctrl.instanceStats);
    }

    /*
     * Validation
     */

    // Update the maximum instance count based on nova limits
    function updateMaxInstanceCount() {
      ctrl.maxInstanceCount = ctrl.maxInstances - ctrl.totalInstancesUsed;

      var instanceCountText = gettext(
        'The instance count must not exceed your quota available of %(maxInstanceCount)s instances'
      );
      var instanceCountObj = { maxInstanceCount: ctrl.maxInstanceCount };
      ctrl.instanceCountMaxError = interpolate(instanceCountText, instanceCountObj, true);
    }

  }
})();
<commit_msg>Remove redundant conditional expression<commit_after>/*
 * Copyright 2015 Hewlett Packard Enterprise Development Company LP
 * (c) Copyright 2015 ThoughtWorks Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function () {
  'use strict';

  /**
   * @ngdoc controller
   * @name LaunchInstanceDetailsController
   * @description
   * The `LaunchInstanceDetailsController` controller provides functions for
   * configuring the details step of the Launch Instance Wizard.
   *
   */
  angular
    .module('horizon.dashboard.project.workflow.launch-instance')
    .controller('LaunchInstanceDetailsController', LaunchInstanceDetailsController);

  LaunchInstanceDetailsController.$inject = [
    '$scope',
    'horizon.framework.widgets.charts.donutChartSettings',
    'horizon.framework.widgets.charts.quotaChartDefaults'
  ];

  function LaunchInstanceDetailsController($scope,
    donutChartSettings,
    quotaChartDefaults
  ) {

    var ctrl = this;

    // Error text for invalid fields
    ctrl.instanceNameError = gettext('A name is required for your instance.');
    ctrl.instanceCountError = gettext(
      'Instance count is required and must be an integer of at least 1'
    );
    ctrl.maxInstanceCount = 1;

    /*
     * Donut chart
     */
    ctrl.chartSettings = donutChartSettings;
    ctrl.maxInstances = 1; // Must have default value > 0
    ctrl.totalInstancesUsed = 0;

    if ($scope.model.novaLimits && $scope.model.novaLimits.maxTotalInstances) {
      ctrl.maxInstances = $scope.model.novaLimits.maxTotalInstances;
    }

    if ($scope.model.novaLimits && $scope.model.novaLimits.totalInstancesUsed) {
      ctrl.totalInstancesUsed = $scope.model.novaLimits.totalInstancesUsed;
    }

    ctrl.instanceStats = {
      title: gettext('Total Instances'),
      maxLimit: ctrl.maxInstances,
      label: '100%',
      data: [
        {
          label: quotaChartDefaults.usageLabel,
          value: 1,
          colorClass: quotaChartDefaults.usageColorClass
        },
        {
          label: quotaChartDefaults.addedLabel,
          value: 1,
          colorClass: quotaChartDefaults.addedColorClass
        },
        {
          label: quotaChartDefaults.remainingLabel,
          value: 1,
          colorClass: quotaChartDefaults.remainingColorClass
        }
      ]
    };

    syncInstanceChartAndLimits();

    var specifiedInstancesWatcher = createWatcher(getInstanceCount, updateChart);
    var maxInstancesWatcher = createWatcher(getMaxInstances, resetMaxInstances);
    var instancesUsedWatcher = createWatcher(getTotalInstancesUsed, resetTotalInstancesUsed);

    // Explicitly remove watchers on desruction of this controller
    $scope.$on('$destroy', function() {
      specifiedInstancesWatcher();
      maxInstancesWatcher();
      instancesUsedWatcher();
    });

    ////////////////////

    function getMaxInstances() {
      return $scope.model.novaLimits.maxTotalInstances;
    }

    function resetMaxInstances(newMaxInstances) {
      ctrl.maxInstances = Math.max(1, newMaxInstances);
      syncInstanceChartAndLimits();
    }

    function getTotalInstancesUsed() {
      return $scope.model.novaLimits.totalInstancesUsed;
    }

    function resetTotalInstancesUsed() {
      ctrl.totalInstancesUsed = $scope.model.novaLimits.totalInstancesUsed;
      syncInstanceChartAndLimits();
    }

    function getInstanceCount() {
      return $scope.model.newInstanceSpec.instance_count;
    }

    function createWatcher(watchExpression, listener) {
      return $scope.$watch(
        watchExpression,
        function (newValue, oldValue) {
          if (newValue !== oldValue) {
            listener(newValue);
          }
        }
      );
    }

    function syncInstanceChartAndLimits() {
      updateChart();
      updateMaxInstanceCount();
    }

    function updateChart() {

      // Initialize instance_count to 1
      if ($scope.model.newInstanceSpec.instance_count <= 0) {
        $scope.model.newInstanceSpec.instance_count = 1;
      }

      var data = ctrl.instanceStats.data;
      var added = $scope.model.newInstanceSpec.instance_count || 1;
      var remaining = Math.max(0, ctrl.maxInstances - ctrl.totalInstancesUsed - added);

      ctrl.instanceStats.maxLimit = ctrl.maxInstances;
      data[0].value = ctrl.totalInstancesUsed;
      data[1].value = added;
      data[2].value = remaining;
      var quotaCalc = Math.round((ctrl.totalInstancesUsed + added) / ctrl.maxInstances * 100);
      ctrl.instanceStats.overMax = quotaCalc > 100;
      ctrl.instanceStats.label = quotaCalc + '%';
      ctrl.instanceStats = angular.extend({}, ctrl.instanceStats);
    }

    /*
     * Validation
     */

    // Update the maximum instance count based on nova limits
    function updateMaxInstanceCount() {
      ctrl.maxInstanceCount = ctrl.maxInstances - ctrl.totalInstancesUsed;

      var instanceCountText = gettext(
        'The instance count must not exceed your quota available of %(maxInstanceCount)s instances'
      );
      var instanceCountObj = { maxInstanceCount: ctrl.maxInstanceCount };
      ctrl.instanceCountMaxError = interpolate(instanceCountText, instanceCountObj, true);
    }

  }
})();
<|endoftext|>


<commit_before>var Discord = require("discord.js");
// var fs = require("fs");
var cron = require("node-cron");
var bot = new Discord.Client( {fetchAllMembers: true} );
var readyCount = 0;
// var watchlist = './watchlist.json';
const prefix = "~";
const friendList = {};

cron.schedule('*/25 * * * *', () => {
    console.log("Keeping SelfBot process alive");
});

bot.on("ready", () => {
    readyCount++;
    console.log("AFlaw is ready");
    console.log(`ID: ${bot.user.id}`);
    console.log(`Username: ${bot.user.username}`);
    console.log(bot.presences);
    console.log(bot.user.friends);
    checkFriendsStatuses(readyCount);
    // watchForFriendPresenceUpdate(readyCount);
});

process.on('SIGTERM', () => {
    console.log("AFlaw is exiting");
});

bot.on("message", msg => {
    if (msg.author.id != bot.user.id || msg.content.substring(0, 1) != prefix) return;

    let messageContent = msg.content.split(" ");
    let command = messageContent[0].slice(prefix.length);
    let fromBotChannel = msg.channel.id == process.env.BOT_TEST_ID;

    if (command === "watch") {
        // console.log("Watch command");
        // console.log(`Is someone mentioned: ${msg.mentions.users.size!=0}`);
        // console.log(messageContent[1]);
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (!fromBotChannel) msg.delete();
        watch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`Watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "unwatch") {
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (msg.channel.id != process.env.BOT_TEST_ID) msg.delete();
        unwatch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`No longer watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "testDM") {
        sendStatusMessage("This is a Test DM");
        // console.log(`Sending test message`);
    }
});

bot.on("presenceUpdate", (oldUser, newUser) => {
    try {
        //  if (oldUser.client.user.id in bot.user.friends.keys) return;
        var userObject = JSON.parse(process.env.WATCHLIST);
        if (userObject[oldUser.user.username.replace(/\s/g, '')]) {
            if ((oldUser.presence.status != "online") && (newUser.presence.status != "offline")) {
                 console.log(`presenceUpdate: ${oldUser.client.user.username}`);
                 sendStatusMessage(`${oldUser.user.username} is ${newUser.presence.status}`);
             }
        }
    } catch (error) {
        console.error(error);
    }
});

bot.login(process.env.USER_TOKEN).catch(err => console.error(err));

function watch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        userObject[user] = user;
        console.log(userObject);
        process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function unwatch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        delete userObject[user];
        console.log(userObject);
            process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function checkFriendsStatuses(count) {
    if (count > 1) return;
    let friendPresences = bot.presences;
    // console.log(friendPresences.keyArray().toString());
    friendPresences.keyArray().forEach((val, index) => {
        friendList[friendPresences.keyArray()[index]] = friendPresences.get(val)["status"];
    });
    console.log(bot.user.friends);
    console.log(friendPresences);
}

// function watchForFriendPresenceUpdate(count) {
//     if (count > 1) return;
//     while(true) {
//         // let friendPresences = bot.presences;
//         // let friends = bot.user.friends;
//         // let friendPresencesKeys = friendPresences.keys;
//         // let friendKeys = friends.keys;
//         // let guilds = bot.guilds;
//         for ()
//     }
// }

function sendStatusMessage(msg) {
     bot.channels.get(process.env.BOT_TEST_ID).sendMessage(msg)
    .then(message => {
        console.log(message.content);
         message.delete();
    })
    .catch(console.error);
}<commit_msg>let's make me invisible<commit_after>var Discord = require("discord.js");
// var fs = require("fs");
var cron = require("node-cron");
var bot = new Discord.Client( {fetchAllMembers: true} );
var readyCount = 0;
// var watchlist = './watchlist.json';
const prefix = "~";
const friendList = {};

cron.schedule('*/25 * * * *', () => {
    console.log("Keeping SelfBot process alive");
});

bot.on("ready", () => {
    readyCount++;
    console.log("AFlaw is ready");
    console.log(`ID: ${bot.user.id}`);
    console.log(`Username: ${bot.user.username}`);
    console.log(bot.presences);
    console.log(bot.user.friends);
    checkFriendsStatuses(readyCount);
    // watchForFriendPresenceUpdate(readyCount);
});

process.on('SIGTERM', () => {
    console.log("AFlaw is exiting");
});

bot.on("message", msg => {
    if (msg.author.id != bot.user.id || msg.content.substring(0, 1) != prefix) return;

    let messageContent = msg.content.split(" ");
    let command = messageContent[0].slice(prefix.length);
    let fromBotChannel = msg.channel.id == process.env.BOT_TEST_ID;

    if (command === "watch") {
        // console.log("Watch command");
        // console.log(`Is someone mentioned: ${msg.mentions.users.size!=0}`);
        // console.log(messageContent[1]);
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (!fromBotChannel) msg.delete();
        watch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`Watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "unwatch") {
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (msg.channel.id != process.env.BOT_TEST_ID) msg.delete();
        unwatch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`No longer watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "testDM") {
        sendStatusMessage("This is a Test DM");
        // console.log(`Sending test message`);
    }
});

bot.on("presenceUpdate", (oldUser, newUser) => {
    try {
        //  if (oldUser.client.user.id in bot.user.friends.keys) return;
        var userObject = JSON.parse(process.env.WATCHLIST);
        if (userObject[oldUser.user.username.replace(/\s/g, '')]) {
            if ((oldUser.presence.status != "online") && (newUser.presence.status != "offline")) {
                 console.log(`presenceUpdate: ${oldUser.client.user.username}`);
                 sendStatusMessage(`${oldUser.user.username} is ${newUser.presence.status}`);
             }
        }
    } catch (error) {
        console.error(error);
    }
});

bot.login(process.env.USER_TOKEN).then(() => bot.user.setStatus("invisible")).catch(err => console.error(err));

function watch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        userObject[user] = user;
        console.log(userObject);
        process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function unwatch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        delete userObject[user];
        console.log(userObject);
            process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function checkFriendsStatuses(count) {
    if (count > 1) return;
    let friendPresences = bot.presences;
    // console.log(friendPresences.keyArray().toString());
    friendPresences.keyArray().forEach((val, index) => {
        friendList[friendPresences.keyArray()[index]] = friendPresences.get(val)["status"];
    });
    console.log(bot.user.friends);
    console.log(friendPresences);
}

// function watchForFriendPresenceUpdate(count) {
//     if (count > 1) return;
//     while(true) {
//         // let friendPresences = bot.presences;
//         // let friends = bot.user.friends;
//         // let friendPresencesKeys = friendPresences.keys;
//         // let friendKeys = friends.keys;
//         // let guilds = bot.guilds;
//         for ()
//     }
// }

function sendStatusMessage(msg) {
     bot.channels.get(process.env.BOT_TEST_ID).sendMessage(msg)
    .then(message => {
        console.log(message.content);
         message.delete();
    })
    .catch(console.error);
}<|endoftext|>


<commit_before>exports.config = {
  allScriptsTimeout: 11000,

  specs: [
    '*.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://localhost:8000/app/',

  framework: 'jasmine',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000
  }
};
<commit_msg>removed jasmine-spec-reporter, does not work with jasmine < 2.0<commit_after>'use strict';

exports.config = {
    allScriptsTimeout: 11000,

    specs: [
        '*.js'
    ],

    capabilities: {
        'browserName': 'chrome'
    },

    baseUrl: 'http://localhost:8000/app/',

    framework: 'jasmine',

    jasmineNodeOpts: {
        defaultTimeoutInterval: 30000
    }
};
<|endoftext|>


<commit_before>/*!
 * jQuery Facebook Helper
 * http://github.com/ntotten/jquery-fb
 *
 * Copyright 2012, Nathan Totten
 * Apache License 2.0
 * https://github.com/ntotten/jquery-fb/blob/master/LICENSE.txt
 */

(function( $ ) {
  $.fn.fb = function(appId, options) {

    var settings = $.extend({
        appId      : appId,
        status     : true,
        cookie     : true,
        xfbml      : true,
        oauth      : true
    }, options);

  	window.fbInit = window.fbInit || false;
  	if (window.fbInit) {
  		 $(document).trigger('fb:initialized');
  		 FB.XFBML.parse();
  		 return;
  	}

  	// Aync Init
  	window.fbAsyncInit = function() {
  	  window.fbInit = true;
  	  $(document).trigger('fb:initializing');
  	  FB.init(settings);
	  $(document).trigger('fb:initialized');
  	};

  	// Append fb-root
  	var fbRoot = 'fb-root';
  	if (!document.getElementById(fbRoot)) {
  		var element = document.createElement('div');
  		element.id = fbRoot;
  		document.body.appendChild(element);
  	}

  	// Add Facebook Javascript SDK
  	var js, id = 'facebook-jssdk';
  	if (!document.getElementById(id)) {
		js = document.createElement('script');
		js.id = id;
		js.async = true;
		js.src = "//connect.facebook.net/en_US/all.js";
		document.getElementsByTagName('head')[0].appendChild(js);
  	}
  };
})( jQuery );
<commit_msg>Added check for FB.XFBML.parse() and fixed tab/spacing issues.<commit_after>/*!
 * jQuery Facebook Helper
 * http://github.com/ntotten/jquery-fb
 *
 * Copyright 2012, Nathan Totten
 * Apache License 2.0
 * https://github.com/ntotten/jquery-fb/blob/master/LICENSE.txt
 */

(function( $ ) {
	$.fn.fb = function(appId, options) {

		var settings = $.extend({
				appId      : appId,
				status     : true,
				cookie     : true,
				xfbml      : true,
				oauth      : true/
		}, options);

		window.fbInit = window.fbInit || false;
		if (window.fbInit) {
			$(document).trigger('fb:initialized');
			if (settings.xfbml) {
				FB.XFBML.parse();
			}
			return;
		}

		// Aync Init
		window.fbAsyncInit = function() {
			window.fbInit = true;
			$(document).trigger('fb:initializing');
			FB.init(settings);
			$(document).trigger('fb:initialized');
		};

		// Append fb-root
		var fbRoot = 'fb-root';
		if (!document.getElementById(fbRoot)) {
			var element = document.createElement('div');
			element.id = fbRoot;
			document.body.appendChild(element);
		}

		// Add Facebook Javascript SDK
		var js, id = 'facebook-jssdk';
		if (!document.getElementById(id)) {
			js = document.createElement('script');
			js.id = id;
			js.async = true;
			js.src = "//connect.facebook.net/en_US/all.js";
			document.getElementsByTagName('head')[0].appendChild(js);
		}
	};
})( jQuery );
<|endoftext|>


<commit_before>const path = require('path')
// const scrambler = require('./scrambler')
const rooms = require('./rooms')
const words = require('random-words');
// const cookieName = words({ exactly: 5, join: '-' })

function login(req, res) {
  res.sendFile(path.join(__dirname, '..', 'client', 'login.html'))
}

function authorize(req, res) {
  console.log(req.body)

  // do some checking

  res.cookie('email', req.body.email)
  res.redirect("/")
}

function is_logged_in(req, res, next) {
  const status = req.cookies.email ? true : false
  status ? next() : res.redirect("/login")
}

function logout(req, res) {
  res.clearCookie('email')
  res.redirect("/login")
}

exports.init = (app) => {

  // auth routes
  app.get("/login", login)
  app.post("/login", authorize)
  app.get("/logout", logout)

  // rooms
  app.get("/api/rooms/:roomId", is_logged_in, rooms.getRoomMessages)

  // main application
  app.get("/", is_logged_in, (req, res) => {
    res.sendFile(path.join(__dirname, '..', 'client', 'index.html'))
  })
}
<commit_msg>clear all cookies on logout:<commit_after>const path = require('path')
// const scrambler = require('./scrambler')
const rooms = require('./rooms')
const words = require('random-words');
// const cookieName = words({ exactly: 5, join: '-' })

function login(req, res) {
  res.sendFile(path.join(__dirname, '..', 'client', 'login.html'))
}

function authorize(req, res) {
  console.log(req.body)

  // do some checking

  res.cookie('email', req.body.email)
  res.redirect("/")
}

function is_logged_in(req, res, next) {
  const status = req.cookies.email ? true : false
  status ? next() : res.redirect("/login")
}

function logout(req, res) {
  ['email', 'io'].forEach(cookie => res.clearCookie(cookie))
  res.redirect("/login")
}

exports.init = (app) => {

  // auth routes
  app.get("/login", login)
  app.post("/login", authorize)
  app.get("/logout", logout)

  // rooms
  app.get("/api/rooms/:roomId", is_logged_in, rooms.getRoomMessages)

  // main application
  app.get("/", is_logged_in, (req, res) => {
    res.sendFile(path.join(__dirname, '..', 'client', 'index.html'))
  })
}
<|endoftext|>


<commit_before>exports.config = {
  allScriptsTimeout: 11000,

  specs: [
    '*.js'
  ],

  capabilities: {
    'browserName': 'firefox'
  },

  baseUrl: 'http://localhost:8000/app/',

  framework: 'jasmine2',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000
  }
};
<commit_msg>fix protractor tests<commit_after>exports.config = {
  allScriptsTimeout: 31000,

  specs: [
    '*.js'
  ],

  capabilities: {
    'browserName': 'firefox'
  },

  baseUrl: 'http://localhost:8000/app/',

  framework: 'jasmine2',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000
  }
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');

var HarakaConfig = require('./lib/HarakaConfig');

var harakaConfig = new HarakaConfig();

harakaConfig.build(function(err, harakaConfigDir){
    console.log(harakaConfigDir);

    var base = path.join(__dirname);
    var harakaPath = path.join(base, 'node_modules/Haraka/haraka.js');

    process.argv[1] = harakaPath;
    process.env.HARAKA = harakaConfigDir;
    require(harakaPath);
});

process.on('exit', function(code){
    console.log('exit code: ' + code);
});<commit_msg>draft: starting web and smtp servers<commit_after>'use strict';

var path = require('path');

var HarakaConfig = require('./lib/HarakaConfig');

var harakaConfig = new HarakaConfig();

harakaConfig.build(function(err, harakaConfigDir){

    var base = path.join(__dirname);
    var webServer = path.join(base, 'lib/web/index.js');

    // start web server
    require(webServer);

    var harakaPath = path.join(base, 'node_modules/Haraka/haraka.js');

    process.argv[1] = harakaPath;
    process.env.HARAKA = harakaConfigDir;

    //start SMTP Hakara server
    require(harakaPath);

});
<|endoftext|>


<commit_before>angular
  .module('splatApp', ['ui.bootstrap', 'ngAnimate', 'ngAria'])
  .controller('splatController', ['$scope', '$rootScope', '$timeout', '$locale', function splatCtrl($scope, $rootScope, $timeout, $translate, $locale, $uibModal, $log) {
    $scope.placeholder = ["PH Data", "More PH Data", "Hello"];
    $scope.dummy = $scope.placeholder[0];
    angular.module('splatApp').skills($scope);
    angular.module('splatApp').stats($scope, $translate);
    angular.module('splatApp').weapons($scope);
    angular.module('splatApp').subs($scope);
    angular.module('splatApp').specials($scope);
    angular.module('splatApp').gear($scope);

    angular.module('splatApp').clipboard($scope, $timeout);
    angular.module('splatApp').util($scope);

    $scope.loadout = new Loadout();
    $scope.status = {}

    $scope.screenshotMode = false;

    $scope.switchSet = function() {
      $scope.loadout.weapon = $scope.availableWeapons()[0];
    }

    $scope.availableWeapons = function() {
      return $scope.selectedSet.weapons.filter(filter_available)
    }

    $scope.selectedSet = $scope.weaponSets[0];
    $scope.loadout.weapon = $scope.availableWeapons()[0];
    $scope.loadout.head.equipped = $scope.hats[0];
    $scope.loadout.clothes.equipped = $scope.clothes[0];
    $scope.loadout.shoes.equipped = $scope.shoes[0];

    $scope.refreshStats = function() {
      Object.keys($scope.stats).forEach(function(currentKey) {
          $scope.stats[currentKey].calc($scope.loadout);
      });
    }

     $scope.$watch('loadout', function() {
       $scope.refreshStats();
       history.replaceState(undefined, undefined, "#" + $scope.encodeLoadout())
     },true);

    $scope.encodeLoadout = function() {
      return encode($scope.selectedSet.id,$scope.loadout)
    }

    $scope.loadCode = function(code) {
      var newLoadout = new Loadout();
      var results = decode(code)
      if(results) {
      $scope.selectedSet = $scope.getWeaponSetById(results.set)
      newLoadout.weapon = $scope.getWeaponById(results.set,results.weapon)
      newLoadout.head.equipped = $scope.getHatById(results.head.gear)
      newLoadout.clothes.equipped = $scope.getClothesById(results.clothes.gear)
      newLoadout.shoes.equipped = $scope.getShoesById(results.shoes.gear)
      newLoadout.head.main = $scope.getSkillById(results.head.main)
      for(var i=0; i<3; i++) {
        newLoadout.head.subs[i] = $scope.getSkillById(results.head.subs[i])
      }
      newLoadout.clothes.main = $scope.getSkillById(results.clothes.main)
      for(var i=0; i<3; i++) {
        newLoadout.clothes.subs[i] = $scope.getSkillById(results.clothes.subs[i])
      }
      newLoadout.shoes.main = $scope.getSkillById(results.shoes.main)
      for(var i=0; i<3; i++) {
        newLoadout.shoes.subs[i] = $scope.getSkillById(results.shoes.subs[i])
      }

      return newLoadout
    }
      return false;
    }

    $scope.encodedURL = function() {
      return window.location.protocol +"//"+ window.location.hostname + "#" + $scope.encodeLoadout()
    }

    $scope.randomizeBuild = function() {
      var randomized = new Loadout()
      $scope.selectedSet = randomFrom($scope.weaponSets)
      randomized.weapon = randomFrom($scope.availableWeapons())
      randomized.head.equipped = randomFrom($scope.hats)
      randomized.clothes.equipped = randomFrom($scope.clothes)
      randomized.shoes.equipped = randomFrom($scope.shoes)
      $scope.loadout = randomized
    }

    $scope.resetLoadout = function() {
      $scope.loadout.clearAbilities();
      $scope.selectedSet = $scope.weaponSets[0];
      $scope.loadout.weapon = $scope.availableWeapons()[0];
      $scope.loadout.head.equipped = $scope.hats[0];
      $scope.loadout.clothes.equipped = $scope.clothes[0];
      $scope.loadout.shoes.equipped = $scope.shoes[0];
    }

    if(window.location.hash) {
      var newLoadout = $scope.loadCode(window.location.hash.replace('#',''))
      if(newLoadout) {
        $scope.loadout = newLoadout
      }
    }

    $scope.languages = {
      'en': 'English',
      'ja': '日本語',
      'fr': 'Français'
    }
  }])
<commit_msg>Adjust encoded URL<commit_after>angular
  .module('splatApp', ['ui.bootstrap', 'ngAnimate', 'ngAria'])
  .controller('splatController', ['$scope', '$rootScope', '$timeout', '$locale', function splatCtrl($scope, $rootScope, $timeout, $translate, $locale, $uibModal, $log) {
    $scope.placeholder = ["PH Data", "More PH Data", "Hello"];
    $scope.dummy = $scope.placeholder[0];
    angular.module('splatApp').skills($scope);
    angular.module('splatApp').stats($scope, $translate);
    angular.module('splatApp').weapons($scope);
    angular.module('splatApp').subs($scope);
    angular.module('splatApp').specials($scope);
    angular.module('splatApp').gear($scope);

    angular.module('splatApp').clipboard($scope, $timeout);
    angular.module('splatApp').util($scope);

    $scope.loadout = new Loadout();
    $scope.status = {}

    $scope.screenshotMode = false;

    $scope.switchSet = function() {
      $scope.loadout.weapon = $scope.availableWeapons()[0];
    }

    $scope.availableWeapons = function() {
      return $scope.selectedSet.weapons.filter(filter_available)
    }

    $scope.selectedSet = $scope.weaponSets[0];
    $scope.loadout.weapon = $scope.availableWeapons()[0];
    $scope.loadout.head.equipped = $scope.hats[0];
    $scope.loadout.clothes.equipped = $scope.clothes[0];
    $scope.loadout.shoes.equipped = $scope.shoes[0];

    $scope.refreshStats = function() {
      Object.keys($scope.stats).forEach(function(currentKey) {
          $scope.stats[currentKey].calc($scope.loadout);
      });
    }

     $scope.$watch('loadout', function() {
       $scope.refreshStats();
       history.replaceState(undefined, undefined, "#" + $scope.encodeLoadout())
     },true);

    $scope.encodeLoadout = function() {
      return encode($scope.selectedSet.id,$scope.loadout)
    }

    $scope.loadCode = function(code) {
      var newLoadout = new Loadout();
      var results = decode(code)
      if(results) {
      $scope.selectedSet = $scope.getWeaponSetById(results.set)
      newLoadout.weapon = $scope.getWeaponById(results.set,results.weapon)
      newLoadout.head.equipped = $scope.getHatById(results.head.gear)
      newLoadout.clothes.equipped = $scope.getClothesById(results.clothes.gear)
      newLoadout.shoes.equipped = $scope.getShoesById(results.shoes.gear)
      newLoadout.head.main = $scope.getSkillById(results.head.main)
      for(var i=0; i<3; i++) {
        newLoadout.head.subs[i] = $scope.getSkillById(results.head.subs[i])
      }
      newLoadout.clothes.main = $scope.getSkillById(results.clothes.main)
      for(var i=0; i<3; i++) {
        newLoadout.clothes.subs[i] = $scope.getSkillById(results.clothes.subs[i])
      }
      newLoadout.shoes.main = $scope.getSkillById(results.shoes.main)
      for(var i=0; i<3; i++) {
        newLoadout.shoes.subs[i] = $scope.getSkillById(results.shoes.subs[i])
      }

      return newLoadout
    }
      return false;
    }

    $scope.encodedURL = function() {
      return window.location.protocol +"//"+ window.location.hostname + "/#" + $scope.encodeLoadout()
    }

    $scope.randomizeBuild = function() {
      var randomized = new Loadout()
      $scope.selectedSet = randomFrom($scope.weaponSets)
      randomized.weapon = randomFrom($scope.availableWeapons())
      randomized.head.equipped = randomFrom($scope.hats)
      randomized.clothes.equipped = randomFrom($scope.clothes)
      randomized.shoes.equipped = randomFrom($scope.shoes)
      $scope.loadout = randomized
    }

    $scope.resetLoadout = function() {
      $scope.loadout.clearAbilities();
      $scope.selectedSet = $scope.weaponSets[0];
      $scope.loadout.weapon = $scope.availableWeapons()[0];
      $scope.loadout.head.equipped = $scope.hats[0];
      $scope.loadout.clothes.equipped = $scope.clothes[0];
      $scope.loadout.shoes.equipped = $scope.shoes[0];
    }

    if(window.location.hash) {
      var newLoadout = $scope.loadCode(window.location.hash.replace('#',''))
      if(newLoadout) {
        $scope.loadout = newLoadout
      }
    }

    $scope.languages = {
      'en': 'English',
      'ja': '日本語',
      'fr': 'Français'
    }
  }])
<|endoftext|>


<commit_before>
function drawSliderByVal(slider) {
	var knob=slider.getElementsByTagName('img')[0];
	var p=(slider.val-slider.min)/(slider.max-slider.min);
	var x=(slider.scrollWidth-30)*p;
	knob.style.left=x+"px";
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function setSliderByClientX(slider, clientX) {
	var p=(clientX-slider.offsetLeft-15)/(slider.scrollWidth-30);
	slider.val=(slider.max-slider.min)*p + slider.min;
	if (slider.val>slider.max) slider.val=slider.max;
	if (slider.val<slider.min) slider.val=slider.min;

	drawSliderByVal(slider);
	slider.onchange(slider.val, slider.num);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderClick(e) {
	var el=sliderFromEvent(e);
	if (!el) return;

	setSliderByClientX(el, e.clientX);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderMouseMove(e) {
	var el=sliderFromEvent(e);
	if (!el) return;
	if (activeSlider<0) return;

	setSliderByClientX(el, e.clientX);
	stopEvent(e);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderFromEvent(e) {
	if (!e && window.event) e=window.event;
	if (!e) return false;
    if (!isLeftButton(e)) return false;

    var el;
	if (e.target) el=e.target;
	if (e.srcElement) el=e.srcElement;

	if (!el.id || !el.id.match(/slider\d+/)) el=el.parentNode;
	if (!el) return false;
	if (!el.id || !el.id.match(/slider\d+/)) return false;

	return el;
}

function isLeftButton(e) {
    return (((e.which) && (e.which == 1)) || ((e.button) && (e.button == 1)));
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function attachSliderEvents() {
	var divs=document.getElementsByTagName('div');
	var divNum;
	for(var i=0; i<divs.length; i++) {
		if (divNum=divs[i].id.match(/\bslider(\d+)\b/)) {
			divNum=parseInt(divNum[1]);
			divs[i].min=slider[divNum].min;
			divs[i].max=slider[divNum].max;
			divs[i].val=slider[divNum].val;
			divs[i].onchange=slider[divNum].onchange;
			divs[i].num=divNum;

			addAnEvent(divs[i], 'mousedown', function(e){
				sliderClick(e);
				var el=sliderFromEvent(e);
				if (!el) return;
				activeSlider=el.num;
				stopEvent(e);
			});
			addAnEvent(divs[i], 'mouseup', function(e){
				activeSlider=-1;
				stopEvent(e);
			});
		}
	}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function stopEvent(event) {
	if (event.preventDefault) {
		event.preventDefault();
		event.stopPropagation();
	} else {
		event.returnValue=false;
		event.cancelBubble=true;
	}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
addAnEvent(window, 'load', attachSliderEvents);
addAnEvent(document, 'mousemove', sliderMouseMove);
var activeSlider=-1;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
<commit_msg>modify test case to show SEL-280 has been fixed: assign directly to the event handler instead of doing an attachEvent<commit_after>
function drawSliderByVal(slider) {
	var knob=slider.getElementsByTagName('img')[0];
	var p=(slider.val-slider.min)/(slider.max-slider.min);
	var x=(slider.scrollWidth-30)*p;
	knob.style.left=x+"px";
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function setSliderByClientX(slider, clientX) {
	var p=(clientX-slider.offsetLeft-15)/(slider.scrollWidth-30);
	slider.val=(slider.max-slider.min)*p + slider.min;
	if (slider.val>slider.max) slider.val=slider.max;
	if (slider.val<slider.min) slider.val=slider.min;

	drawSliderByVal(slider);
	slider.onchange(slider.val, slider.num);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderClick(e) {
	var el=sliderFromEvent(e);
	if (!el) return;

	setSliderByClientX(el, e.clientX);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderMouseMove(e) {
	var el=sliderFromEvent(e);
	if (!el) return;
	if (activeSlider<0) return;

	setSliderByClientX(el, e.clientX);
	stopEvent(e);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderFromEvent(e) {
	if (!e && window.event) e=window.event;
	if (!e) return false;
    if (!isLeftButton(e)) return false;

    var el;
	if (e.target) el=e.target;
	if (e.srcElement) el=e.srcElement;

	if (!el.id || !el.id.match(/slider\d+/)) el=el.parentNode;
	if (!el) return false;
	if (!el.id || !el.id.match(/slider\d+/)) return false;

	return el;
}

function isLeftButton(e) {
    return (((e.which) && (e.which == 1)) || ((e.button) && (e.button == 1)));
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function attachSliderEvents() {
	var divs=document.getElementsByTagName('div');
	var divNum;
	for(var i=0; i<divs.length; i++) {
		if (divNum=divs[i].id.match(/\bslider(\d+)\b/)) {
			divNum=parseInt(divNum[1]);
			divs[i].min=slider[divNum].min;
			divs[i].max=slider[divNum].max;
			divs[i].val=slider[divNum].val;
			divs[i].onchange=slider[divNum].onchange;
			divs[i].num=divNum;
			addAnEvent(divs[i], 'mousedown', function(e){
				sliderClick(e);
				var el=sliderFromEvent(e);
				if (!el) return;
				activeSlider=el.num;
				stopEvent(e);
			});

                        // to prove that http://jira.openqa.org/browse/SEL-280 is in fact fixed, assign directly to onmouseup
                        // (instead of using the addAnEvent code below; this used to cause trouble because the global event var was not getting set)
                        	divs[i].onmouseup = function(e){

                        		if (e==null) e = event;	// only needed when we do direct assignment to onmouseup

				activeSlider=-1;
				stopEvent(e);
			};
			//addAnEvent(divs[i], 'mouseup', function(e){
			//	activeSlider=-1;
			//	stopEvent(e);
			//});

		}
	}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function stopEvent(event) {
	if (event.preventDefault) {
		event.preventDefault();
		event.stopPropagation();
	} else {
		event.returnValue=false;
		event.cancelBubble=true;
	}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
addAnEvent(window, 'load', attachSliderEvents);

addAnEvent(document, 'mousemove', sliderMouseMove);
//document.onmousemove = sliderMouseMove;

var activeSlider=-1;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
<|endoftext|>


<commit_before>app.directive('emoticonMenu', function ($rootScope, $filter, user, emoticons, bunkerApi) {
	return {
		templateUrl: '/assets/app/header/emoticonMenu.html',
		scope: {
			visible: '=ngShow'
		},
		link: function (scope) {
			scope.settings = user.settings;
			scope.saveSettings = user.saveSettings;
			scope.emoticonMenuLists = [];
			scope.emoticonCounts = bunkerApi.message.emoticonCounts();

			var emotesByAlpha = splitInHalf(emoticons.list);

			scope.$watch('settings.sortEmoticonsByPopularity', function (sortEmoticonsByPopularity, oldVal) {
				if (sortEmoticonsByPopularity == oldVal) return;

				if (!sortEmoticonsByPopularity) {
					scope.emoticonMenuLists = emotesByAlpha;
					return;
				}

				scope.emoticonCounts = bunkerApi.message.emoticonCounts();
			});

			scope.$watchCollection('emoticonCounts', function (emoteCounts, oldVal) {
				if (emoteCounts == oldVal) return;

				console.count('emoticonCounts watch');
				var emoteCountsHash = _.indexBy(emoteCounts, 'name');

				_.each(emoticons.list, function (emoticon) {
					if (emoteCountsHash[emoticon.name]) {
						emoticon.$count = emoteCountsHash[emoticon.name].count;
					}
				});

				var orderedList = _(emoticons.list).sortBy('$count').reverse().value();
				scope.emoticonMenuLists = splitInHalf(orderedList);
			});

			scope.appendEmoticonToChat = function (emoticonFileName) {
				var emoticonName = ':' + $filter('emoticonName')(emoticonFileName) + ':';
				$rootScope.$broadcast('inputText', emoticonName);

				// Close window
				if (typeof scope.visible !== 'undefined') {
					scope.visible = false;
				}
			};
		}
	};

	function splitInHalf(list) {
		return [
			_.initial(list, Math.floor(list.length / 2)),
			_.rest(list, Math.ceil(list.length / 2))
		];
	}
});

app.filter('toArray', function () {
	return function (object) {
		if (_.isArray(object)) return object;
		return _.values(object);
	}
});
<commit_msg>reload emote count on emote window open<commit_after>app.directive('emoticonMenu', function ($rootScope, $filter, user, emoticons, bunkerApi) {
	return {
		templateUrl: '/assets/app/header/emoticonMenu.html',
		scope: {
			visible: '=ngShow'
		},
		link: function (scope) {
			scope.settings = user.settings;
			scope.saveSettings = user.saveSettings;
			scope.emoticonMenuLists = [];
			scope.emoticonCounts = bunkerApi.message.emoticonCounts();

			var emotesByAlpha = splitInHalf(emoticons.list);

			scope.$watch('settings.sortEmoticonsByPopularity', function (sortEmoticonsByPopularity, oldVal) {
				if (sortEmoticonsByPopularity == oldVal) return;

				if (!sortEmoticonsByPopularity) {
					scope.emoticonMenuLists = emotesByAlpha;
					return;
				}

				scope.emoticonCounts = bunkerApi.message.emoticonCounts();
			});

			scope.$watch('visible', function (visible, oldVal) {
				if (!visible || !scope.settings.sortEmoticonsByPopularity || visible == oldVal) return;
				console.log('yay')
				scope.emoticonCounts = bunkerApi.message.emoticonCounts();
			});

			scope.$watchCollection('emoticonCounts', function (emoteCounts, oldVal) {
				if (emoteCounts == oldVal) return;

				console.count('emoticonCounts watch');
				var emoteCountsHash = _.indexBy(emoteCounts, 'name');

				_.each(emoticons.list, function (emoticon) {
					if (emoteCountsHash[emoticon.name]) {
						emoticon.$count = emoteCountsHash[emoticon.name].count;
					}
				});

				var orderedList = _(emoticons.list).sortBy('$count').reverse().value();
				scope.emoticonMenuLists = splitInHalf(orderedList);
			});

			scope.appendEmoticonToChat = function (emoticonFileName) {
				var emoticonName = ':' + $filter('emoticonName')(emoticonFileName) + ':';
				$rootScope.$broadcast('inputText', emoticonName);

				// Close window
				if (typeof scope.visible !== 'undefined') {
					scope.visible = false;
				}
			};
		}
	};

	function splitInHalf(list) {
		return [
			_.initial(list, Math.floor(list.length / 2)),
			_.rest(list, Math.ceil(list.length / 2))
		];
	}
});

app.filter('toArray', function () {
	return function (object) {
		if (_.isArray(object)) return object;
		return _.values(object);
	}
});
<|endoftext|>