<commit_before>'use strict'
var Web3 = require('web3')
var EventManager = require('../eventManager')
var EthJSVM = require('ethereumjs-vm')
var ethUtil = require('ethereumjs-util')
var StateManager = require('ethereumjs-vm/dist/stateManager')
var Web3VMProvider = require('../web3Provider/web3VmProvider')

var rlp = ethUtil.rlp

var injectedProvider

var web3
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
  injectedProvider = window.web3.currentProvider
  web3 = new Web3(injectedProvider)
} else {
  web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}

var blankWeb3 = new Web3()

/*
  extend vm state manager and instanciate VM
*/

class StateManagerCommonStorageDump extends StateManager {
  constructor (arg) {
    super(arg)
    this.keyHashes = {}
  }

  putContractStorage (address, key, value, cb) {
    this.keyHashes[ethUtil.sha3(key).toString('hex')] = ethUtil.bufferToHex(key)
    super.putContractStorage(address, key, value, cb)
  }

  dumpStorage (address, cb) {
    var self = this
    this._getStorageTrie(address, function (err, trie) {
      if (err) {
        return cb(err)
      }
      var storage = {}
      var stream = trie.createReadStream()
      stream.on('data', function (val) {
        var value = rlp.decode(val.value)
        storage['0x' + val.key.toString('hex')] = {
          key: self.keyHashes[val.key.toString('hex')],
          value: '0x' + value.toString('hex')
        }
      })
      stream.on('end', function () {
        cb(storage)
      })
    })
  }
}

var stateManager = new StateManagerCommonStorageDump({})
var vm = new EthJSVM({
  enableHomestead: true,
  activatePrecompiles: true
})

// FIXME: move state manager in EthJSVM ctr
vm.stateManager = stateManager
vm.blockchain = stateManager.blockchain
vm.trie = stateManager.trie
vm.stateManager.checkpoint()

var web3VM = new Web3VMProvider()
web3VM.setVM(vm)

var mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'

/*
  trigger contextChanged, web3EndpointChanged
*/
function ExecutionContext () {
  var self = this
  this.event = new EventManager()

  var executionContext = null

  this.blockGasLimitDefault = 4300000
  this.blockGasLimit = this.blockGasLimitDefault
  this.customNetWorks = {}

  this.init = function (config) {
    if (config.get('settings/always-use-vm')) {
      executionContext = 'vm'
    } else {
      executionContext = injectedProvider ? 'injected' : 'vm'
    }
  }

  this.getProvider = function () {
    return executionContext
  }

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return this.isVM() ? web3VM : web3
  }

  this.detectNetwork = function (callback) {
    if (this.isVM()) {
      callback(null, { id: '-', name: 'VM' })
    } else {
      this.web3().version.getNetwork((err, id) => {
        var name = null
        if (err) name = 'Unknown'
        // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
        else if (id === '1') name = 'Main'
        else if (id === '2') name = 'Morden (deprecated)'
        else if (id === '3') name = 'Ropsten'
        else if (id === '4') name = 'Rinkeby'
        else if (id === '42') name = 'Kovan'
        else name = 'Custom'

        if (id === '1') {
          this.web3().eth.getBlock(0, (error, block) => {
            if (error) console.log('cant query first block')
            if (block && block.hash !== mainNetGenesisHash) name = 'Custom'
            callback(err, { id, name })
          })
        } else {
          callback(err, { id, name })
        }
      })
    }
  }

  this.removeProvider = function (name) {
    delete this.customNetWorks[name]
    self.event.trigger('removeProvider', [name])
  }

  this.addProvider = function (network) {
    this.customNetWorks[network.name] = network
    self.event.trigger('addProvider', [network])
  }

  this.internalWeb3 = function () {
    return web3
  }

  this.blankWeb3 = function () {
    return blankWeb3
  }

  this.vm = function () {
    return vm
  }

  this.setContext = function (context, endPointUrl, confirmCb, infoCb) {
    executionContext = context
    this.executionContextChange(context, endPointUrl, confirmCb, infoCb)
  }

  this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) {
    if (!cb) cb = () => {}

    if (context === 'vm') {
      executionContext = context
      vm.stateManager.revert(function () {
        vm.stateManager.checkpoint()
      })
      self.event.trigger('contextChanged', ['vm'])
      return cb()
    }

    if (context === 'injected') {
      if (injectedProvider === undefined) {
        var alertMsg = 'No injected Web3 provider found. '
        alertMsg += 'Make sure your provider (e.g. MetaMask) is active and running '
        alertMsg += '(when recently activated you may have to reload the page).'
        infoCb(alertMsg)
        return cb()
      } else {
        executionContext = context
        web3.setProvider(injectedProvider)
        self._updateBlockGasLimit()
        self.event.trigger('contextChanged', ['injected'])
        return cb()
      }
    }

    if (context === 'web3') {
      confirmCb(cb)
    }

    if (this.customNetWorks[context]) {
      var provider = this.customNetWorks[context]
      setProviderFromEndpoint(provider.url, provider.name, () => { cb() })
    }
  }

  this.currentblockGasLimit = function () {
    return this.blockGasLimit
  }

  this.stopListenOnLastBlock = function () {
    if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId)
    this.listenOnLastBlockId = null
  }

  this._updateBlockGasLimit = function () {
    if (this.getProvider() !== 'vm') {
      web3.eth.getBlock('latest', (err, block) => {
        if (!err) {
          // we can't use the blockGasLimit cause the next blocks could have a lower limit : https://github.com/ethereum/remix/issues/506
          this.blockGasLimit = (block && block.gasLimit) ? Math.floor(block.gasLimit - (5 * block.gasLimit) / 1024) : this.blockGasLimitDefault
        } else {
          this.blockGasLimit = this.blockGasLimitDefault
        }
      })
    }
  }

  this.listenOnLastBlock = function () {
    this.listenOnLastBlockId = setInterval(() => {
      this._updateBlockGasLimit()
    }, 15000)
  }

  // TODO: not used here anymore and needs to be moved
  function setProviderFromEndpoint (endpoint, context, cb) {
    var oldProvider = web3.currentProvider

    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
    if (web3.isConnected()) {
      executionContext = context
      self._updateBlockGasLimit()
      self.event.trigger('contextChanged', ['web3'])
      self.event.trigger('web3EndpointChanged')
      cb()
    } else {
      web3.setProvider(oldProvider)
      var alertMsg = 'Not possible to connect to the Web3 provider. '
      alertMsg += 'Make sure the provider is running and a connection is open (via IPC or RPC).'
      cb(alertMsg)
    }
  }
  this.setProviderFromEndpoint = setProviderFromEndpoint

  this.txDetailsLink = function (network, hash) {
    if (transactionDetailsLinks[network]) {
      return transactionDetailsLinks[network] + hash
    }
  }
}

var transactionDetailsLinks = {
  'Main': 'https://www.etherscan.io/tx/',
  'Rinkeby': 'https://rinkeby.etherscan.io/tx/',
  'Ropsten': 'https://ropsten.etherscan.io/tx/',
  'Kovan': 'https://kovan.etherscan.io/tx/'
}

module.exports = new ExecutionContext()
<commit_msg>test before adding/removing<commit_after>'use strict'
var Web3 = require('web3')
var EventManager = require('../eventManager')
var EthJSVM = require('ethereumjs-vm')
var ethUtil = require('ethereumjs-util')
var StateManager = require('ethereumjs-vm/dist/stateManager')
var Web3VMProvider = require('../web3Provider/web3VmProvider')

var rlp = ethUtil.rlp

var injectedProvider

var web3
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
  injectedProvider = window.web3.currentProvider
  web3 = new Web3(injectedProvider)
} else {
  web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}

var blankWeb3 = new Web3()

/*
  extend vm state manager and instanciate VM
*/

class StateManagerCommonStorageDump extends StateManager {
  constructor (arg) {
    super(arg)
    this.keyHashes = {}
  }

  putContractStorage (address, key, value, cb) {
    this.keyHashes[ethUtil.sha3(key).toString('hex')] = ethUtil.bufferToHex(key)
    super.putContractStorage(address, key, value, cb)
  }

  dumpStorage (address, cb) {
    var self = this
    this._getStorageTrie(address, function (err, trie) {
      if (err) {
        return cb(err)
      }
      var storage = {}
      var stream = trie.createReadStream()
      stream.on('data', function (val) {
        var value = rlp.decode(val.value)
        storage['0x' + val.key.toString('hex')] = {
          key: self.keyHashes[val.key.toString('hex')],
          value: '0x' + value.toString('hex')
        }
      })
      stream.on('end', function () {
        cb(storage)
      })
    })
  }
}

var stateManager = new StateManagerCommonStorageDump({})
var vm = new EthJSVM({
  enableHomestead: true,
  activatePrecompiles: true
})

// FIXME: move state manager in EthJSVM ctr
vm.stateManager = stateManager
vm.blockchain = stateManager.blockchain
vm.trie = stateManager.trie
vm.stateManager.checkpoint()

var web3VM = new Web3VMProvider()
web3VM.setVM(vm)

var mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'

/*
  trigger contextChanged, web3EndpointChanged
*/
function ExecutionContext () {
  var self = this
  this.event = new EventManager()

  var executionContext = null

  this.blockGasLimitDefault = 4300000
  this.blockGasLimit = this.blockGasLimitDefault
  this.customNetWorks = {}

  this.init = function (config) {
    if (config.get('settings/always-use-vm')) {
      executionContext = 'vm'
    } else {
      executionContext = injectedProvider ? 'injected' : 'vm'
    }
  }

  this.getProvider = function () {
    return executionContext
  }

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return this.isVM() ? web3VM : web3
  }

  this.detectNetwork = function (callback) {
    if (this.isVM()) {
      callback(null, { id: '-', name: 'VM' })
    } else {
      this.web3().version.getNetwork((err, id) => {
        var name = null
        if (err) name = 'Unknown'
        // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
        else if (id === '1') name = 'Main'
        else if (id === '2') name = 'Morden (deprecated)'
        else if (id === '3') name = 'Ropsten'
        else if (id === '4') name = 'Rinkeby'
        else if (id === '42') name = 'Kovan'
        else name = 'Custom'

        if (id === '1') {
          this.web3().eth.getBlock(0, (error, block) => {
            if (error) console.log('cant query first block')
            if (block && block.hash !== mainNetGenesisHash) name = 'Custom'
            callback(err, { id, name })
          })
        } else {
          callback(err, { id, name })
        }
      })
    }
  }

  this.removeProvider = function (name) {
    if (name && this.customNetWorks[name]) {
      delete this.customNetWorks[name]
      self.event.trigger('removeProvider', [name])
    }
  }

  this.addProvider = function (network) {
    if (network && network.name && network.url) {
      this.customNetWorks[network.name] = network
      self.event.trigger('addProvider', [network])
    }
  }

  this.internalWeb3 = function () {
    return web3
  }

  this.blankWeb3 = function () {
    return blankWeb3
  }

  this.vm = function () {
    return vm
  }

  this.setContext = function (context, endPointUrl, confirmCb, infoCb) {
    executionContext = context
    this.executionContextChange(context, endPointUrl, confirmCb, infoCb)
  }

  this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) {
    if (!cb) cb = () => {}

    if (context === 'vm') {
      executionContext = context
      vm.stateManager.revert(function () {
        vm.stateManager.checkpoint()
      })
      self.event.trigger('contextChanged', ['vm'])
      return cb()
    }

    if (context === 'injected') {
      if (injectedProvider === undefined) {
        var alertMsg = 'No injected Web3 provider found. '
        alertMsg += 'Make sure your provider (e.g. MetaMask) is active and running '
        alertMsg += '(when recently activated you may have to reload the page).'
        infoCb(alertMsg)
        return cb()
      } else {
        executionContext = context
        web3.setProvider(injectedProvider)
        self._updateBlockGasLimit()
        self.event.trigger('contextChanged', ['injected'])
        return cb()
      }
    }

    if (context === 'web3') {
      confirmCb(cb)
    }

    if (this.customNetWorks[context]) {
      var provider = this.customNetWorks[context]
      setProviderFromEndpoint(provider.url, provider.name, () => { cb() })
    }
  }

  this.currentblockGasLimit = function () {
    return this.blockGasLimit
  }

  this.stopListenOnLastBlock = function () {
    if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId)
    this.listenOnLastBlockId = null
  }

  this._updateBlockGasLimit = function () {
    if (this.getProvider() !== 'vm') {
      web3.eth.getBlock('latest', (err, block) => {
        if (!err) {
          // we can't use the blockGasLimit cause the next blocks could have a lower limit : https://github.com/ethereum/remix/issues/506
          this.blockGasLimit = (block && block.gasLimit) ? Math.floor(block.gasLimit - (5 * block.gasLimit) / 1024) : this.blockGasLimitDefault
        } else {
          this.blockGasLimit = this.blockGasLimitDefault
        }
      })
    }
  }

  this.listenOnLastBlock = function () {
    this.listenOnLastBlockId = setInterval(() => {
      this._updateBlockGasLimit()
    }, 15000)
  }

  // TODO: not used here anymore and needs to be moved
  function setProviderFromEndpoint (endpoint, context, cb) {
    var oldProvider = web3.currentProvider

    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
    if (web3.isConnected()) {
      executionContext = context
      self._updateBlockGasLimit()
      self.event.trigger('contextChanged', ['web3'])
      self.event.trigger('web3EndpointChanged')
      cb()
    } else {
      web3.setProvider(oldProvider)
      var alertMsg = 'Not possible to connect to the Web3 provider. '
      alertMsg += 'Make sure the provider is running and a connection is open (via IPC or RPC).'
      cb(alertMsg)
    }
  }
  this.setProviderFromEndpoint = setProviderFromEndpoint

  this.txDetailsLink = function (network, hash) {
    if (transactionDetailsLinks[network]) {
      return transactionDetailsLinks[network] + hash
    }
  }
}

var transactionDetailsLinks = {
  'Main': 'https://www.etherscan.io/tx/',
  'Rinkeby': 'https://rinkeby.etherscan.io/tx/',
  'Ropsten': 'https://ropsten.etherscan.io/tx/',
  'Kovan': 'https://kovan.etherscan.io/tx/'
}

module.exports = new ExecutionContext()
<|endoftext|>


<commit_before>"use strict";
var every = require('schedule').every;
class Officer {
    constructor(name, title) {
        this.name = name;
        this.title = title;
    }
}
class OfficerData {
    constructor(title, people) {
        this.title = title;
        this.people = people;
    }
}
class OfficerList {
    constructor(bus) {
        this.rotateList = () => {
            this.currentList++;
            if (this.currentList >= this.lists.length) {
                this.currentList = 0;
            }
        };
        this.updateWidgets = () => {
            //console.log('Updating officers list');
            this.bus.post({
                event: 'widgetUpdate',
                messageType: 'officers:update',
                messageData: this.lists[this.currentList]
            });
        };
        this.currentList = -1;
        this.lists = new Array();
        this.lists.push(new OfficerData('Administrative Officers', [
            { name: "Renard Rose", title: "President" },
            { name: "Bucky Swider", title: "Vice President" },
            { name: "Jamie Viall", title: "Secretary" },
            { name: "Paul Stanish", title: "Treasurer" },
            { name: "John Lynch", title: "Financial Secretary" },
        ]));
        this.lists.push(new OfficerData('Fire Officers', [
            { name: "Chris Schwartz", title: "Chief" },
            { name: "Renard Rose", title: "Deputy Chief" },
            { name: "Tim Tygh", title: "Assistant Chief" },
            { name: "Scott Yoder", title: "Batallion Chief" },
            { name: "Bucky Swider", title: "Captain" },
            { name: "Jamie Viall", title: "Lieutenant" },
            { name: "Chris Hummel", title: "Lieutenant 1" },
            { name: "Shaun Maher", title: "Lieutenant 2" },
            { name: "Pat Dicicco", title: "Safety Officer" },
            { name: "Mike Gaffney", title: "Chief Engineer" },
            { name: "Scott Rotenbury", title: "Fire Police Captain" }
        ]));
        this.lists.push(new OfficerData('Trustees', [
            { name: "Shel Klein", title: "Chairman" },
            { name: "Pat Dicicco", title: "" },
            { name: "Tim Tygh", title: "" },
            { name: "Shaun  Maher", title: "" },
            { name: "John Lynch", title: "" },
            { name: "Scott Yoder", title: "" },
            { name: "Chris Breish", title: "" },
        ]));
        var instance = this;
        bus.subscribe({ event: 'userConnected' }, instance.updateWidgets);
        //console.log('Setting officer update schedule');
        every('15s').do(function() {
            //console.log('Officer update schedule triggered');
            instance.rotateList();
            instance.updateWidgets();
        });
        //console.log('Done setting officer update schedule');
        this.bus = bus;
    }
}
exports.OfficerList = OfficerList;
//# sourceMappingURL=officers.js.map<commit_msg>Updated fire officers list<commit_after>"use strict";
var every = require('schedule').every;
class Officer {
    constructor(name, title) {
        this.name = name;
        this.title = title;
    }
}
class OfficerData {
    constructor(title, people) {
        this.title = title;
        this.people = people;
    }
}
class OfficerList {
    constructor(bus) {
        this.rotateList = () => {
            this.currentList++;
            if (this.currentList >= this.lists.length) {
                this.currentList = 0;
            }
        };
        this.updateWidgets = () => {
            //console.log('Updating officers list');
            this.bus.post({
                event: 'widgetUpdate',
                messageType: 'officers:update',
                messageData: this.lists[this.currentList]
            });
        };
        this.currentList = -1;
        this.lists = new Array();
        this.lists.push(new OfficerData('Administrative Officers', [
            { name: "Renard Rose", title: "President" },
            { name: "Bucky Swider", title: "Vice President" },
            { name: "Jamie Viall", title: "Secretary" },
            { name: "Paul Stanish", title: "Treasurer" },
        ]));
        this.lists.push(new OfficerData('Fire Officers', [
            { name: "Chris Schwartz", title: "Chief" },
            { name: "Renard Rose", title: "Deputy Chief" },
            { name: "Tim Tygh", title: "Assistant Chief" },
            { name: "Scott Yoder", title: "Assitant Chief 1" },
            { name: "Bucky Swider", title: "Battalion Chief" },
            { name: "Jamie Viall", title: "Captain" },
            { name: "Chris Hummel", title: "Captain 1" },
            { name: "Chris Breish", title: "Lieutenant" },
            { name: "Shaun Maher", title: "Lieutenant 1" },
            { name: "Dave Cox", title: "Lieutenant 2" },
            { name: "Pat Dicicco", title: "Safety Officer" },
            { name: "Mike Gaffney", title: "Chief Engineer" },
            { name: "Scott Rotenbury", title: "Fire Police Captain" }
        ]));
        this.lists.push(new OfficerData('Trustees', [
            { name: "Shel Klein", title: "Chairman" },
            { name: "Pat Dicicco", title: "" },
            { name: "Tim Tygh", title: "" },
            { name: "Shaun  Maher", title: "" },
            { name: "John Lynch", title: "" },
            { name: "Scott Yoder", title: "" },
            { name: "Chris Breish", title: "" },
        ]));
        var instance = this;
        bus.subscribe({ event: 'userConnected' }, instance.updateWidgets);
        //console.log('Setting officer update schedule');
        every('15s').do(function() {
            //console.log('Officer update schedule triggered');
            instance.rotateList();
            instance.updateWidgets();
        });
        //console.log('Done setting officer update schedule');
        this.bus = bus;
    }
}
exports.OfficerList = OfficerList;
//# sourceMappingURL=officers.js.map<|endoftext|>


<commit_before>/**
 * Created by kmjungersen on 9/1/15.
 */

$(function () {

    $("#main-page").onepage_scroll({
        sectionContainer: "section",     // sectionContainer accepts any kind of selector in case you don't want to use section
        easing: "ease",                  // Easing options accepts the CSS3 easing animation such "ease", "linear", "ease-in",
                                         // "ease-out", "ease-in-out", or even cubic bezier value such as "cubic-bezier(0.175, 0.885, 0.420, 1.310)"
        animationTime: 1000,             // AnimationTime let you define how long each section takes to animate
        pagination: true,                // You can either show or hide the pagination. Toggle true for show, false for hide.
        updateURL: false,                // Toggle this true if you want the URL to be updated automatically when the user scroll to each page.
        beforeMove: function (index) {
            var activePanel = $('.active');

            activePanel.addClass('flyIn-init');
            activePanel.removeClass('flyIn-animate');
        },  // This option accepts a callback function. The function will be called before the page moves.
        afterMove: function (index) {
            $('.active').addClass('flyIn-animate');
        },   // This option accepts a callback function. The function will be called after the page moves.
        loop: false,                     // You can have the page loop back to the top/bottom when the user navigates at up/down on the first/last page.
        keyboard: true,                  // You can activate the keyboard controls
        responsiveFallback: false,        // You can fallback to normal page scroll by defining the width of the browser in which
        // you want the responsive fallback to be triggered. For example, set this to 600 and whenever
        // the browser's width is less than 600, the fallback will kick in.
        direction: "vertical"            // You can now define the direction of the One Page Scroll animation. Options available are "vertical" and "horizontal". The default value is "vertical".
    });

    $(".flyIn-section").addClass("flyIn-init");
    $("section.active").addClass("flyIn-animate");
    videojs.options.flash.swf = "video-js/video-js.swf";

    function prepareTooltips() {

        var paginationTabs = $(".onepage-pagination").find("a");

        $.each(paginationTabs, function (i, e) {

            var element = $(e);
            var index = element.attr("data-index");

            var tooltipData = panelInfo[index].tooltip;

            element.addClass("tooltipped");
            element.attr("data-position", "left");
            element.attr("data-tooltip", tooltipData);
        });

        $(".tooltipped").tooltip({
            delay: 0
        });
    }

    var panelInfo = {
        "1": {
            tooltip: "Hello"
        },
        "2": {
            tooltip: "Work"
        },
        "3": {
            tooltip: "Play"
        },
        "4": {
            tooltip: "School"
        },
        "5": {
            tooltip: "Github"
        },
        "6": {
            tooltip: "Contact"
        }
    };

    prepareTooltips();

    function stickyFooter(footerElement) {

        var self = this;
        self.element = $(footerElement);
        self.viewWindow = $(window);

        placeFooter(self);

        self.viewWindow.resize(function () {
            placeFooter(self)
        });

        function placeFooter(self) {
            var windowHeight = self.viewWindow.height();
            var elementHeight = self.element.height();

            var difference = windowHeight - elementHeight;

            element.css("top", difference);
        }
    }

    var footerElement = $(".page-footer");
    stickyFooter(footerElement);
});<commit_msg>removed tooltip functionality, and added the click-down functionality<commit_after>/**
 * Created by kmjungersen on 9/1/15.
 */

$(function () {

    var scroller = $("#main-page");

    scroller.onepage_scroll({
        sectionContainer: "section",     // sectionContainer accepts any kind of selector in case you don't want to use section
        easing: "ease",                  // Easing options accepts the CSS3 easing animation such "ease", "linear", "ease-in",
                                         // "ease-out", "ease-in-out", or even cubic bezier value such as "cubic-bezier(0.175, 0.885, 0.420, 1.310)"
        animationTime: 1000,             // AnimationTime let you define how long each section takes to animate
        pagination: true,                // You can either show or hide the pagination. Toggle true for show, false for hide.
        updateURL: false,                // Toggle this true if you want the URL to be updated automatically when the user scroll to each page.
        beforeMove: function (index) {
            var activePanel = $('.active');

            activePanel.addClass('flyIn-init');
            activePanel.removeClass('flyIn-animate');
        },  // This option accepts a callback function. The function will be called before the page moves.
        afterMove: function (index) {
            $('.active').addClass('flyIn-animate');
        },   // This option accepts a callback function. The function will be called after the page moves.
        loop: false,                     // You can have the page loop back to the top/bottom when the user navigates at up/down on the first/last page.
        keyboard: true,                  // You can activate the keyboard controls
        responsiveFallback: false,        // You can fallback to normal page scroll by defining the width of the browser in which
        // you want the responsive fallback to be triggered. For example, set this to 600 and whenever
        // the browser's width is less than 600, the fallback will kick in.
        direction: "vertical"            // You can now define the direction of the One Page Scroll animation. Options available are "vertical" and "horizontal". The default value is "vertical".
    });

    var clickableArea = $(".click-down");
    clickableArea.click(function() {
        console.log("foo");
       scroller.moveDown();
    });

    $(".flyIn-section").addClass("flyIn-init");
    $("section.active").addClass("flyIn-animate");
    videojs.options.flash.swf = "video-js/video-js.swf";

    function stickyFooter(footerElement) {

        var self = this;
        self.element = $(footerElement);
        self.viewWindow = $(window);

        placeFooter(self);

        self.viewWindow.resize(function () {
            placeFooter(self)
        });

        function placeFooter(self) {
            var windowHeight = self.viewWindow.height();
            var elementHeight = self.element.height();

            var difference = windowHeight - elementHeight;

            element.css("top", difference);
        }
    }

    var footerElement = $(".page-footer");
    stickyFooter(footerElement);
});<|endoftext|>


<commit_before>var gulp = require('gulp');
var jshint = require('gulp-jshint');

//
// See https://github.com/tfennelly/jenkins-js-builder
//
var builder = require('jenkins-js-builder');

//
// Bundle the page init script.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/page-init.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .inDir('src/main/webapp/jsbundles');

//
// Bundle the Install Wizard.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/pluginSetupWizard.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .withExternalModuleMapping('bootstrap', 'core-assets/bootstrap:bootstrap3', {addDefaultCSS: true})
    .withExternalModuleMapping('handlebars', 'core-assets/handlebars:handlebars3')
    .less('src/main/less/pluginSetupWizard.less')
    .inDir('src/main/webapp/jsbundles');

//
// Bundle the Config Tab Bar.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/config-tabbar.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .less('src/main/js/config-tabbar.less')
    .inDir('src/main/webapp/jsbundles');

//
// Bundle the Config Scrollspy.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/config-scrollspy.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .less('src/main/js/config-scrollspy.less')
    .inDir('src/main/webapp/jsbundles');

builder.bundle('src/main/js/add-item.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .less('src/main/js/add-item.less')
    .inDir('src/main/webapp/jsbundles');

//
// JSHint, a JavaScript Code Quality Tool
//
gulp.task('lint', function() {
    return gulp.src('./src/main/js/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});
<commit_msg>[JENKINS-34438] The build will fail if there are JSHint errors<commit_after>var gulp = require('gulp');
var jshint = require('gulp-jshint');

//
// See https://github.com/tfennelly/jenkins-js-builder
//
var builder = require('jenkins-js-builder');

//
// Bundle the page init script.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/page-init.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .inDir('src/main/webapp/jsbundles');

//
// Bundle the Install Wizard.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/pluginSetupWizard.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .withExternalModuleMapping('bootstrap', 'core-assets/bootstrap:bootstrap3', {addDefaultCSS: true})
    .withExternalModuleMapping('handlebars', 'core-assets/handlebars:handlebars3')
    .less('src/main/less/pluginSetupWizard.less')
    .inDir('src/main/webapp/jsbundles');

//
// Bundle the Config Tab Bar.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/config-tabbar.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .less('src/main/js/config-tabbar.less')
    .inDir('src/main/webapp/jsbundles');

//
// Bundle the Config Scrollspy.
// See https://github.com/jenkinsci/js-builder#bundling
//
builder.bundle('src/main/js/config-scrollspy.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .less('src/main/js/config-scrollspy.less')
    .inDir('src/main/webapp/jsbundles');

builder.bundle('src/main/js/add-item.js')
    .withExternalModuleMapping('jquery-detached', 'core-assets/jquery-detached:jquery2')
    .less('src/main/js/add-item.less')
    .inDir('src/main/webapp/jsbundles');

//
// JSHint, a JavaScript Code Quality Tool
//
gulp.task('lint', function() {
    return gulp.src('./src/main/js/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(jshint.reporter('fail'));
});
<|endoftext|>


<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename, 'info');

const Hook = require('./Hook.js');

const sem = require('../sensor/SensorEventManager.js').getInstance();

const rclient = require('../util/redis_manager.js').getRedisClient()

const Promise = require('bluebird');

const IntelTool = require('../net2/IntelTool');
const intelTool = new IntelTool();

const sl = require('../sensor/SensorLoader.js');

const urlhash = require("../util/UrlHash.js");

const URL_SET_TO_BE_PROCESSED = "url_set_to_be_processed";

const ITEMS_PER_FETCH = 100;
const QUEUE_SIZE_PAUSE = 2000;
const QUEUE_SIZE_RESUME = 1000;
const MAX_URL_LENGTH = 2048;

const MONITOR_QUEUE_SIZE_INTERVAL = 10 * 1000; // 10 seconds;

const CommonKeys = require('../net2/CommonKeys.js');

const _ = require('lodash');
const LRU = require('lru-cache');

class DestURLFoundHook extends Hook {

  constructor() {
    super();

    this.config.intelExpireTime = 2 * 24 * 3600; // two days
    this.pendingIPs = {};
    this.triggerCache = new LRU({
      max: 1000,
      maxAge: 1000 * 60 * 5
    });
  }

  appendURL(info) {
    return rclient.zaddAsync(URL_SET_TO_BE_PROCESSED, 0, JSON.stringify(info));
  }

  isFirewalla(host) {
    let patterns = [/\.encipher\.io$/,
      /^encipher\.io$/,
      /^firewalla\.com$/,
      /\.firewalla\.com$/];

    return patterns.filter(p => host.match(p)).length > 0;
  }

  getSubURLWithHashes(url) {
    const hashes = urlhash.canonicalizeAndHashExpressions(url);
    return hashes;
  }

  async alreadyEnriched(subURL) {
    const intel = await intelTool.getURLIntel(subURL);
    return intel != null;
  }

  async processURL(url, options) {
    options = options || {};

    const skipReadLocalCache = options.skipReadLocalCache;

    const subURLHashes = this.getSubURLWithHashes(url);

    const urlsNeedCheck = [];

    // find out if any url or sub urls requires validation
    for(const subURLHash of subURLHashes) {
      if(subURLHash.constructor.name !== 'Array' ||
      subURLHash.length !== 3) {
        continue;
      }

      const url = subURLHash[0];

      const safe = await this.isUrlSafe(url);

      if(safe) {
        continue;
      }

      if(!skipReadLocalCache) {
        const existing = await this.alreadyEnriched(url);
        if(existing) {
          continue;
        }
      }

      urlsNeedCheck.push(subURLHash);
    }

    if(urlsNeedCheck.length > 0) {
      let results = await intelTool.checkURLIntelFromCloud(urlsNeedCheck);

      if(!results) {
         return;
      }

      // only focus on intels
      results = results.filter((result) => result.c === 'intel');

      const safeURLs = urlsNeedCheck.filter((urlNeedCheck) => {
        const matchedResults = results.filter((result) => result.hash && urlNeedCheck[2] && result.hash === urlNeedCheck[2]);
        // if this url matches no result from cloud, consider as safe urls
        return _.isEmpty(matchedResults);
      }).map((urlNeedCheck) => urlNeedCheck[0]);

      for(const safeURL of safeURLs) {
        await this.markAsSafe(safeURL);
      }

      if(!_.isEmpty(results)) {
        await this.storeIntels(urlsNeedCheck, results);
      }
    }
  }

  async _storeIntel(url, result) {
    const normalized = this.normalizeIntelResult(url, result);
    if(normalized) {
      await intelTool.addURLIntel(url, normalized, this.config.intelExpireTime);
    }
  }

  normalizeIntelResult(url, result) {
    if(!result) {
      return null;
    }

    const copy = JSON.parse(JSON.stringify(result));
    copy.url = url;
    if(copy.c) {
      copy.category = copy.c;
      delete copy.c;
    }

    if("flowid" in copy) delete copy.flowid;
    if("ip" in copy) delete copy.ip;
    if("ts" in copy) delete copy.ts;

    return copy;
  }

  findURLByHash(hash, urlsWithHash) {
    for(const urlWithHash of urlsWithHash) {
      if(urlWithHash && urlWithHash.length === 3 && urlWithHash[2] === hash) {
        return urlWithHash[0];
      }
    }

    return null;
  }

  async storeIntels(urlsNeedCheck, results) {
    for(const result of results) {
      const hash = result && result.hash;
      if(!hash) {
        continue;
      }

      const url = this.findURLByHash(hash, urlsNeedCheck);
      if(!url) {
        continue;
      }

      await this._storeIntel(url, result);
    }
  }

  async markAsSafe(subURL) {
    await rclient.zaddAsync(CommonKeys.intel.safe_urls, new Date() / 1000, subURL);
    await intelTool.removeURLIntel(subURL);
  }

  async isUrlSafe(subURL) {
    const score = await rclient.zscoreAsync(CommonKeys.intel.safe_urls, subURL);
    return score !== null;
  }

  // urlObj is an object of mac and url
  getValidUrlObjs(urlObjStrings) {
    return urlObjStrings.map((urlObj) => {
      try {
        return JSON.parse(urlObj);
      } catch(err) {
        return null;
      }
    }).filter((urlObj) => urlObj !== null && urlObj.mac && urlObj.url);
  }

  shouldCheckForIntel(urlObj = {}) {
    const {mac, url} = urlObj;
    const cachePlugin = sl.getSensor("IntelLocalCachePlugin");

    if (!cachePlugin || !cachePlugin.isWorking()) {
      return true;
    }

    const subURLHashes = this.getSubURLWithHashes(url);
    return subURLHashes.some((hash) => {
      if(_.isEmpty(hash) || hash.length !== 3) {
        return false;
      }
      return cachePlugin.checkUrl(hash[0]);
    });
  }

  async job() {
    log.debug("Checking if any urls pending for intel analysis...")

    try {
      const urlObjStrings = await rclient.zrangeAsync(URL_SET_TO_BE_PROCESSED, 0, ITEMS_PER_FETCH);

      if(urlObjStrings.length > 0) {

        // format is valid
        const validUrlObjs = this.getValidUrlObjs(urlObjStrings);

        // hit bloomfilter
        const matchedUrlObjs = validUrlObjs.filter((urlObj) => this.shouldCheckForIntel(urlObj));

        const matchedMacs = {};

        for(const urlObj of matchedUrlObjs) {
          const {url, mac} = urlObj;

          try {
            await this.processURL(url);
            const intel = await intelTool.getURLIntel(url);
            if(intel.category === 'intel') {
              matchedMacs[mac] = 1;
            }
          } catch(err) {
            log.error(`Got error when handling url ${url}, err: ${err}`);
          }
        }

        for(const mac of Object.keys(matchedMacs)) {
          this.shouldTriggerDetectionImmediately(mac);
        }

        const args = [URL_SET_TO_BE_PROCESSED];
        args.push.apply(args, urlObjStrings);

        if(args.length > 1) {
          await rclient.zremAsync(args);
        }

        log.debug(urlObjStrings.length + "URLs are analyzed with intels");

      } else {
        // log.info("No IP Addresses are pending for intels");
      }
    } catch(err) {
      log.error("Got error when handling new URL, err:", err)
    }

    // there might be a performance improvement here, instead of querying redis for every second
    // use block-based redis command (e.g. brpop) may be better
    // but it seems brpop doesn't support batch
    setTimeout(() => {
      this.job(); // sleep for only 500 mill-seconds
    }, 1000);
  }

  shouldTriggerDetectionImmediately(mac) {
    if(this.triggerCache.get(mac) !== undefined) {
      // skip if duplicate in 5 minutes
      return;
    }

    this.triggerCache.set(mac, 1);

    log.info("[Delay 15s] Triggering FW_DETECT_REQUEST on mac", mac);
    // trigger firemon detect immediately to detect the malware activity sooner
    setTimeout(() => {
      sem.sendEventToFireMon({
        type: 'FW_DETECT_REQUEST',
        mac
      });
    }, 15 * 1000); // a HARD CODE number to wait for flow:conn is recorded. Because usually http log is faster than conn log
  }

  run() {
    sem.on('DestURLFound', (event) => {
      const {url, mac} = event;
      if (!url || url.length > MAX_URL_LENGTH)
        return;
      this.appendURL({mac, url});
    });

    sem.on('DestURL', (event) => {
      if (!event.url || event.url.length > MAX_URL_LENGTH)
        return;
      const skipReadLocalCache = event.skipReadLocalCache;
      this.processURL(event.url, {skipReadLocalCache});
    })

    this.job();

    setInterval(() => {
      this.monitorQueue()
    }, MONITOR_QUEUE_SIZE_INTERVAL)
  }

  async monitorQueue() {
    let count = await rclient.zcountAsync(URL_SET_TO_BE_PROCESSED, "-inf", "+inf")
    if(count > QUEUE_SIZE_PAUSE) {
      this.paused = true;
    }
    if(count < QUEUE_SIZE_RESUME) {
      this.paused = false;
    }
  }
}

module.exports = DestURLFoundHook;
<commit_msg>fix null reference<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

const log = require('../net2/logger.js')(__filename, 'info');

const Hook = require('./Hook.js');

const sem = require('../sensor/SensorEventManager.js').getInstance();

const rclient = require('../util/redis_manager.js').getRedisClient()

const Promise = require('bluebird');

const IntelTool = require('../net2/IntelTool');
const intelTool = new IntelTool();

const sl = require('../sensor/SensorLoader.js');

const urlhash = require("../util/UrlHash.js");

const URL_SET_TO_BE_PROCESSED = "url_set_to_be_processed";

const ITEMS_PER_FETCH = 100;
const QUEUE_SIZE_PAUSE = 2000;
const QUEUE_SIZE_RESUME = 1000;
const MAX_URL_LENGTH = 2048;

const MONITOR_QUEUE_SIZE_INTERVAL = 10 * 1000; // 10 seconds;

const CommonKeys = require('../net2/CommonKeys.js');

const _ = require('lodash');
const LRU = require('lru-cache');

class DestURLFoundHook extends Hook {

  constructor() {
    super();

    this.config.intelExpireTime = 2 * 24 * 3600; // two days
    this.pendingIPs = {};
    this.triggerCache = new LRU({
      max: 1000,
      maxAge: 1000 * 60 * 5
    });
  }

  appendURL(info) {
    return rclient.zaddAsync(URL_SET_TO_BE_PROCESSED, 0, JSON.stringify(info));
  }

  isFirewalla(host) {
    let patterns = [/\.encipher\.io$/,
      /^encipher\.io$/,
      /^firewalla\.com$/,
      /\.firewalla\.com$/];

    return patterns.filter(p => host.match(p)).length > 0;
  }

  getSubURLWithHashes(url) {
    const hashes = urlhash.canonicalizeAndHashExpressions(url);
    return hashes;
  }

  async alreadyEnriched(subURL) {
    const intel = await intelTool.getURLIntel(subURL);
    return intel != null;
  }

  async processURL(url, options) {
    options = options || {};

    const skipReadLocalCache = options.skipReadLocalCache;

    const subURLHashes = this.getSubURLWithHashes(url);

    const urlsNeedCheck = [];

    // find out if any url or sub urls requires validation
    for(const subURLHash of subURLHashes) {
      if(subURLHash.constructor.name !== 'Array' ||
      subURLHash.length !== 3) {
        continue;
      }

      const url = subURLHash[0];

      const safe = await this.isUrlSafe(url);

      if(safe) {
        continue;
      }

      if(!skipReadLocalCache) {
        const existing = await this.alreadyEnriched(url);
        if(existing) {
          continue;
        }
      }

      urlsNeedCheck.push(subURLHash);
    }

    if(urlsNeedCheck.length > 0) {
      let results = await intelTool.checkURLIntelFromCloud(urlsNeedCheck);

      if(!results) {
         return;
      }

      // only focus on intels
      results = results.filter((result) => result.c === 'intel');

      const safeURLs = urlsNeedCheck.filter((urlNeedCheck) => {
        const matchedResults = results.filter((result) => result.hash && urlNeedCheck[2] && result.hash === urlNeedCheck[2]);
        // if this url matches no result from cloud, consider as safe urls
        return _.isEmpty(matchedResults);
      }).map((urlNeedCheck) => urlNeedCheck[0]);

      for(const safeURL of safeURLs) {
        await this.markAsSafe(safeURL);
      }

      if(!_.isEmpty(results)) {
        await this.storeIntels(urlsNeedCheck, results);
      }
    }
  }

  async _storeIntel(url, result) {
    const normalized = this.normalizeIntelResult(url, result);
    if(normalized) {
      await intelTool.addURLIntel(url, normalized, this.config.intelExpireTime);
    }
  }

  normalizeIntelResult(url, result) {
    if(!result) {
      return null;
    }

    const copy = JSON.parse(JSON.stringify(result));
    copy.url = url;
    if(copy.c) {
      copy.category = copy.c;
      delete copy.c;
    }

    if("flowid" in copy) delete copy.flowid;
    if("ip" in copy) delete copy.ip;
    if("ts" in copy) delete copy.ts;

    return copy;
  }

  findURLByHash(hash, urlsWithHash) {
    for(const urlWithHash of urlsWithHash) {
      if(urlWithHash && urlWithHash.length === 3 && urlWithHash[2] === hash) {
        return urlWithHash[0];
      }
    }

    return null;
  }

  async storeIntels(urlsNeedCheck, results) {
    for(const result of results) {
      const hash = result && result.hash;
      if(!hash) {
        continue;
      }

      const url = this.findURLByHash(hash, urlsNeedCheck);
      if(!url) {
        continue;
      }

      await this._storeIntel(url, result);
    }
  }

  async markAsSafe(subURL) {
    await rclient.zaddAsync(CommonKeys.intel.safe_urls, new Date() / 1000, subURL);
    await intelTool.removeURLIntel(subURL);
  }

  async isUrlSafe(subURL) {
    const score = await rclient.zscoreAsync(CommonKeys.intel.safe_urls, subURL);
    return score !== null;
  }

  // urlObj is an object of mac and url
  getValidUrlObjs(urlObjStrings) {
    return urlObjStrings.map((urlObj) => {
      try {
        return JSON.parse(urlObj);
      } catch(err) {
        return null;
      }
    }).filter((urlObj) => urlObj !== null && urlObj.mac && urlObj.url);
  }

  shouldCheckForIntel(urlObj = {}) {
    const {mac, url} = urlObj;
    const cachePlugin = sl.getSensor("IntelLocalCachePlugin");

    if (!cachePlugin || !cachePlugin.isWorking()) {
      return true;
    }

    const subURLHashes = this.getSubURLWithHashes(url);
    return subURLHashes.some((hash) => {
      if(_.isEmpty(hash) || hash.length !== 3) {
        return false;
      }
      return cachePlugin.checkUrl(hash[0]);
    });
  }

  async job() {
    log.debug("Checking if any urls pending for intel analysis...")

    try {
      const urlObjStrings = await rclient.zrangeAsync(URL_SET_TO_BE_PROCESSED, 0, ITEMS_PER_FETCH);

      if(urlObjStrings.length > 0) {

        // format is valid
        const validUrlObjs = this.getValidUrlObjs(urlObjStrings);

        // hit bloomfilter
        const matchedUrlObjs = validUrlObjs.filter((urlObj) => this.shouldCheckForIntel(urlObj));

        const matchedMacs = {};

        for(const urlObj of matchedUrlObjs) {
          const {url, mac} = urlObj;

          try {
            await this.processURL(url);
            const intel = await intelTool.getURLIntel(url);
            if (intel && intel.category === 'intel') {
              matchedMacs[mac] = 1;
            }
          } catch(err) {
            log.error(`Got error when handling url ${url}, err:`, err);
          }
        }

        for(const mac of Object.keys(matchedMacs)) {
          this.shouldTriggerDetectionImmediately(mac);
        }

        const args = [URL_SET_TO_BE_PROCESSED];
        args.push.apply(args, urlObjStrings);

        if(args.length > 1) {
          await rclient.zremAsync(args);
        }

        log.debug(urlObjStrings.length + "URLs are analyzed with intels");

      } else {
        // log.info("No IP Addresses are pending for intels");
      }
    } catch(err) {
      log.error("Got error when handling new URL, err:", err)
    }

    // there might be a performance improvement here, instead of querying redis for every second
    // use block-based redis command (e.g. brpop) may be better
    // but it seems brpop doesn't support batch
    setTimeout(() => {
      this.job(); // sleep for only 500 mill-seconds
    }, 1000);
  }

  shouldTriggerDetectionImmediately(mac) {
    if(this.triggerCache.get(mac) !== undefined) {
      // skip if duplicate in 5 minutes
      return;
    }

    this.triggerCache.set(mac, 1);

    log.info("[Delay 15s] Triggering FW_DETECT_REQUEST on mac", mac);
    // trigger firemon detect immediately to detect the malware activity sooner
    setTimeout(() => {
      sem.sendEventToFireMon({
        type: 'FW_DETECT_REQUEST',
        mac
      });
    }, 15 * 1000); // a HARD CODE number to wait for flow:conn is recorded. Because usually http log is faster than conn log
  }

  run() {
    sem.on('DestURLFound', (event) => {
      const {url, mac} = event;
      if (!url || url.length > MAX_URL_LENGTH)
        return;
      this.appendURL({mac, url});
    });

    sem.on('DestURL', (event) => {
      if (!event.url || event.url.length > MAX_URL_LENGTH)
        return;
      const skipReadLocalCache = event.skipReadLocalCache;
      this.processURL(event.url, {skipReadLocalCache});
    })

    this.job();

    setInterval(() => {
      this.monitorQueue()
    }, MONITOR_QUEUE_SIZE_INTERVAL)
  }

  async monitorQueue() {
    let count = await rclient.zcountAsync(URL_SET_TO_BE_PROCESSED, "-inf", "+inf")
    if(count > QUEUE_SIZE_PAUSE) {
      this.paused = true;
    }
    if(count < QUEUE_SIZE_RESUME) {
      this.paused = false;
    }
  }
}

module.exports = DestURLFoundHook;
<|endoftext|>


<commit_before>//Global Variable - Declare variables to be accessed on any function

 //1: Game needs player, cpu, hp, attack value, scores for players and cpu
var player;
var cpu;

var attackStrength;
var playerScore;
var cpuScore;

 //2: Create an array or object for characters? Refer to Cobweb activity...
var characters = [{

	name: "Spiderman";
	hp: 1500,
	strengthAttack: 75
},
{	name: "Wolverine";
	hp: 3000,
	strengthAttack: 150
},
{	name: "Oscar"
	hp: 500,
	strengthAttack: 300
},
{
	name: "Big Bird"
	hp: 5000,
	strengthAttack: 20
}];

// Start Game
fightNow();
$('#characters').on('click', '.character', pickPlayerandCpu);
$('#btnAttackRestart').click(attackRestart);

// Setting function before the fight
function fightNow() {

    //Set values. Refer to calculator assignment.
    player = undefined;
    cpu = undefined;
    attackStrength = 0;
    playerScore = 0;
    cpuScore = 0

    //Loop - Add HP and Name variable to characters
    for(var i=0;i<characters.length;i++){

        //Replace fig by object name value
        $('#' + i +' > figcaption:first-child').text(characters[i].name);
        //Replace fig by object hp value
        $('#'+ i +' > figcaption:last-child').text(characters[i].hp);

        //^^Ask Cameron or Charlie/Angie^^
        console.log("why is # working but not #characters .character");

        //Messages and Buttons
            $('#message').html("Pick a character");
            $('#msgBattle').html("");
            $('#msgCharacters').html("Available characters");

            $('#btnAttackRestart').html("Attack");
            $('#btnAttackRestart').hide();      //switches from Attack and Restart btn

    }
}

// Pick a character

function selectCharacter() {

    console.log ("start");

    if (player === undefined) {

        player = parseInt($(this).attr('id')); // convert to integer & add
        $('#chosenPlayer').prepend($(this));   //div goes behind selected character
        playerScore = characters[player].hp;
        attackStrength = characters[player].attackStrength;
        $('#message').html("Pick enemy to fight");
        $('#msgCharacters').html("Available Enemies");

    }else if (cpu === undefined){

        cpu = parseInt($(this).attr('id'));
        cpuScore = characters[cpu].hp;
        $('#cpu').prepend($(this));
        $('#characters').children().prop("disabled", true);
        $('#btnAttackRestart').show();
        $('#btnAttackRestart').attr("disabled", false);
        $('#message').html("ATTACK");
        if ($('#characters').children().length === 0) {
            $('#msgCharacters').html("No enemies left.");
        }
    }
}
// Player clicks 'btnAttack' to reduce HP of CPU.

function attackRestart() {
    if($('#btnAttackRestart').html() === "Restart") {
        restart();
    }else if ($('#btnAttackRestart').html() === "Attack") {
        attack();
    }
}
// PLayer attacks and CPU attacks back
function attack() {

    cpuScore -= attackStrength;
    playerScore -= characters[cpu].attackStrength;

    $('#'+ player +' > figcaption:last').text(playerScore);
    $('#'+ cpu +' > figcaption:last').text(cpuScore);

    $('#msgBattle').html(""+"You attacked "+characters[cpu].name+" for "+characters[player].attackStrength+" damage."+""+"
"
                        + "" + characters[cpu].name + " attacked you back for " +characters[cpu].attackStrength + " damage."+"");
}

//Conditions for defeating first enemy, winning by defeating all three, losing, and tie

//Results

// Play/Pause Song //
<commit_msg>conditions for win/lose<commit_after>//Global Variable - Declare variables to be accessed on any function

 //1: Game needs player, cpu, hp, attack value, scores for players and cpu
var player;
var cpu;

var attackStrength;
var playerScore;
var cpuScore;

 //2: Create an array or object for characters? Refer to Cobweb activity...
var characters = [{

	name: "Spiderman";
	hp: 1500,
	strengthAttack: 75
},
{	name: "Wolverine";
	hp: 3000,
	strengthAttack: 150
},
{	name: "Oscar"
	hp: 500,
	strengthAttack: 300
},
{
	name: "Big Bird"
	hp: 5000,
	strengthAttack: 20
}];

// Start Game
fightNow();
$('#characters').on('click', '.character', pickPlayerandCpu);
$('#btnAttackRestart').click(attackRestart);

// Setting function before the fight
function fightNow() {

    //Set values. Refer to calculator assignment.
    player = undefined;
    cpu = undefined;
    attackStrength = 0;
    playerScore = 0;
    cpuScore = 0

    //Loop - Add HP and Name variable to characters
    for(var i=0;i<characters.length;i++){

        //Replace fig by object name value
        $('#' + i +' > figcaption:first-child').text(characters[i].name);
        //Replace fig by object hp value
        $('#'+ i +' > figcaption:last-child').text(characters[i].hp);

        //^^Ask Cameron or Charlie/Angie^^
        console.log("why is # working but not #characters .character");

        //Messages and Buttons
            $('#message').html("Pick a character");
            $('#msgBattle').html("");
            $('#msgCharacters').html("Available characters");

            $('#btnAttackRestart').html("Attack");
            $('#btnAttackRestart').hide();      //switches from Attack and Restart btn

    }
}

// Pick a character

function selectCharacter() {

    console.log ("start");

    if (player === undefined) {

        player = parseInt($(this).attr('id')); // convert to integer & add
        $('#chosenPlayer').prepend($(this));   //div goes behind selected character
        playerScore = characters[player].hp;
        attackStrength = characters[player].attackStrength;
        $('#message').html("Pick enemy to fight");
        $('#msgCharacters').html("Available Enemies");

    }else if (cpu === undefined){

        cpu = parseInt($(this).attr('id'));
        cpuScore = characters[cpu].hp;
        $('#cpu').prepend($(this));
        $('#characters').children().prop("disabled", true);
        $('#btnAttackRestart').show();
        $('#btnAttackRestart').attr("disabled", false);
        $('#message').html("ATTACK");
        if ($('#characters').children().length === 0) {
            $('#msgCharacters').html("No enemies left.");
        }
    }
}
// Player clicks 'btnAttack' to reduce HP of CPU.

function attackRestart() {
    if($('#btnAttackRestart').html() === "Restart") {
        restart();
    }else if ($('#btnAttackRestart').html() === "Attack") {
        attack();
    }
}
// PLayer attacks and CPU attacks back
function attack() {

    cpuScore -= attackStrength;
    playerScore -= characters[cpu].attackStrength;

    $('#'+ player +' > figcaption:last').text(playerScore);
    $('#'+ cpu +' > figcaption:last').text(cpuScore);

    $('#msgBattle').html(""+"You attacked "+characters[cpu].name+" for "+characters[player].attackStrength+" damage."+""+"
"
                        + "" + characters[cpu].name + " attacked you back for " +characters[cpu].attackStrength + " damage."+"");
}

//Conditions for defeating first enemy, winning by defeating all three, losing, and tie

//Results

// Play/Pause Song //
$(document).ready(function() {

$(".themeButton").on("click", function(){
                audioElement.play();
            });

            $(".pauseButton").on("click", function(){
                audioElement.pause();
            });

 var audioElement = document.createElement('audio');
            audioElement.setAttribute('src', 'assets/8bit-sesamestreet.mp3');

            // Theme Button
            $(".themeButton").on("click", function(){
                audioElement.play();
            });

            $(".pauseButton").on("click", function(){
                audioElement.pause();
            });
});
<|endoftext|>


<commit_before>{"apiVersion":"1.0","swaggerVersion":"1.2","apis":[{"path":"/default/actors","description":"Operations related to actors","apiDeclaration":{"apiVersion":"1.0","swaggerVersion":"1.2","basePath":"/","resourcePath":"/rest/actors","produces":["application/json; charset=utf8"],"apis":[{"path":"/rest/actors","description":"getActors","operations":[{"method":"GET","summary":"Loads the actors","notes":"Loads the actor list, including the actor information an his most popular shows/movies. It can be full loaded, or paginated.","type":"ResponseEntity«AndroidResponse»","nickname":"getActors","produces":["application/json; charset=utf8"],"parameters":[{"name":"page","description":"The page that will be retrieved, starting from 1","defaultValue":"","required":false,"type":"integer","format":"int32","paramType":"query","allowMultiple":false}],"responseMessages":[{"code":200,"message":"The request was successful, and the body contains the response","responseModel":"ResponseEntity«AndroidResponse»"},{"code":403,"message":"Forbidden"},{"code":400,"message":"The request is invalid. The page value probably is out of the valid range","responseModel":"Void"},{"code":401,"message":"Unauthorized"},{"code":404,"message":"Not Found"}],"deprecated":"false"}]}],"models":{"ResponseEntity«AndroidResponse»":{"id":"ResponseEntity«AndroidResponse»","description":"","extends":"","properties":{"statusCode":{"type":"string","enum":["100","101","102","103","200","201","202","203","204","205","206","207","208","226","300","301","302","302","303","304","305","307","308","400","401","402","403","404","405","406","407","408","409","410","411","412","413","414","415","416","417","418","419","420","421","422","423","424","426","428","429","431","500","501","502","503","504","505","506","507","508","509","510","511"]},"body":{"$ref":"AndroidResponse"},"headers":{"$ref":"HttpHeaders"}}},"Actor":{"id":"Actor","description":"","required":["identifier","description","adult","top","popularity","name","location"],"extends":"","properties":{"identifier":{"type":"integer","format":"int32","description":"Identifier of the actor"},"description":{"type":"string","description":"The description field of the actor"},"adult":{"type":"boolean","description":"If the actor is an adult"},"top":{"type":"boolean","description":"Whether the actor is top"},"popularity":{"type":"number","format":"double","description":"The popularity value of th eactor"},"name":{"type":"string","description":"The name of the actor"},"location":{"type":"string","description":"The location of the actor"}}},"AndroidResponse":{"id":"AndroidResponse","description":"","extends":"","properties":{"totalElements":{"type":"integer","format":"int32","description":"The total number of actors in the system"},"data":{"type":"array","description":"The list of the requested actors","items":{"$ref":"Actor"}}}}}}}],"info":{"title":"default Title","description":"Api Description","termsOfServiceUrl":"Api terms of service","contact":"Contact Email","license":"Licence Type","licenseUrl":"License URL"}}<commit_msg>git error - removed actorsSchema<commit_after><|endoftext|>


<commit_before>/**************************************************************************************
* Portefeuille.js
*
* This theme requires some customization.
* Enter your social media URLs in social-config.json so they appear on the nav bar.
***************************************************************************************/

var portefeuille = {
	items: [],
	tags: [],
	strip_cdata: function(str) {
		return str.replace("<![CDATA[", "").replace("]]>", "");
	},
	format: function(str) {
		return (str.charAt(0).toUpperCase() + str.slice(1)).replace("-", " ");
	}
};

$.getJSON($('#social-config').attr("src"), function(config) {
	console.log("Success", config);
	$.each(config, function(key, value) {
		$(".share").append(''+portefeuille.format(key)+'');
	});
});

$.ajax({
	type: "GET",
	url: "/rss",
	dataType: "xml",
	success: function(xml) {
 		$(xml).find('item').each(function(index, value) {
 			portefeuille.items.push({
 				title: $(value).find('title').text(),
				description: $(value).find('description').text(),
				link: $(value).find('link').text(),
				categories: {
					rawXML: $(value).find('category'),
					tags: []
				},
				nav_item: false
 			});

 		});

 		$.each(portefeuille.items, function(index, item) {
 			$.each(item.categories.rawXML, function(index, value) {
 				item.categories.tags.push($(value).text().replace(" ", "-"));
 			});
 			$.each(item.categories.tags, function(index, value) {
 				if ($.inArray(value, portefeuille.tags) === -1) portefeuille.tags.push(value);
 				if (value === "nav-item") item.nav_item = true;
 			});

 			item.gallery_div = $('div[data-id="'+item.link.replace(window.location.origin, '')+'"]');

 			if (item.nav_item) {
 				$('.main-nav ul').append('

'+item.title+'

');
 			}
 			else {
 				$.each(item.categories.tags, function(index, value) {
 					item.gallery_div.addClass(value);
 				});
 			}
 		});

 		$.each(portefeuille.tags, function(i, value){
		    if (value !== "nav-item") $('#filters').append('<button type="button" data-filter=".'+value+'">'+portefeuille.format(value)+'</button>')
		});

 		//console.log(portefeuille);
	}
});

// Hides the filter buttons from the other pages
if (window.location.pathname !== "/") {
    $('#filters').addClass('hidden');
};

// Init isotope
var $container = $('.isotope').isotope({
    itemSelector: '.item',
    layoutMode: 'fitRows'
  });

// filter functions
var filterFns = {};

// bind filter button click
$('#filters').on( 'click', 'button', function() {
	var filterValue = $( this ).attr('data-filter');
	// use filterFn if matches value
	filterValue = filterFns[ filterValue ] || filterValue;
	$container.isotope({ filter: filterValue });
});

// change is-checked class on buttons
$('.button-group').each( function( i, buttonGroup ) {
	var $buttonGroup = $( buttonGroup );
	$buttonGroup.on( 'click', 'button', function() {
	  $buttonGroup.find('.is-checked').removeClass('is-checked');
	  $( this ).addClass('is-checked');
	});
});
<commit_msg>Added resume link option<commit_after>/**************************************************************************************
* Portefeuille.js
*
* This theme requires some customization.
* Enter your social media URLs in social-config.json so they appear on the nav bar.
***************************************************************************************/

var portefeuille = {
	items: [],
	tags: [],
	strip_cdata: function(str) {
		return str.replace("<![CDATA[", "").replace("]]>", "");
	},
	format: function(str) {
		return (str.charAt(0).toUpperCase() + str.slice(1)).replace("-", " ");
	}
};

$.getJSON($('#social-config').attr("src"), function(config) {
	console.log("Success", config);
	$.each(config, function(key, value) {
		if (key !== "resume") $(".share").append(''+portefeuille.format(key)+'');
		if (key === "resume") $('.main-nav ul').append('

résumé

');
	});

});

$.ajax({
	type: "GET",
	url: "/rss",
	dataType: "xml",
	success: function(xml) {
 		$(xml).find('item').each(function(index, value) {
 			portefeuille.items.push({
 				title: $(value).find('title').text(),
				description: $(value).find('description').text(),
				link: $(value).find('link').text(),
				categories: {
					rawXML: $(value).find('category'),
					tags: []
				},
				nav_item: false
 			});

 		});

 		$.each(portefeuille.items, function(index, item) {
 			$.each(item.categories.rawXML, function(index, value) {
 				item.categories.tags.push($(value).text().replace(" ", "-"));
 			});
 			$.each(item.categories.tags, function(index, value) {
 				if ($.inArray(value, portefeuille.tags) === -1) portefeuille.tags.push(value);
 				if (value === "nav-item") item.nav_item = true;
 			});

 			item.gallery_div = $('div[data-id="'+item.link.replace(window.location.origin, '')+'"]');

 			if (item.nav_item) {
 				$('.main-nav ul').append('

'+item.title+'

');
 			}
 			else {
 				$.each(item.categories.tags, function(index, value) {
 					item.gallery_div.addClass(value);
 				});
 			}
 		});

 		$.each(portefeuille.tags, function(i, value){
		    if (value !== "nav-item") $('#filters').append('<button type="button" data-filter=".'+value+'">'+portefeuille.format(value)+'</button>')
		});

 		//console.log(portefeuille);
	}
});

// Hides the filter buttons from the other pages
if (window.location.pathname !== "/") {
    $('#filters').addClass('hidden');
};

// Init isotope
var $container = $('.isotope').isotope({
    itemSelector: '.item',
    layoutMode: 'fitRows'
  });

// filter functions
var filterFns = {};

// bind filter button click
$('#filters').on( 'click', 'button', function() {
	var filterValue = $( this ).attr('data-filter');
	// use filterFn if matches value
	filterValue = filterFns[ filterValue ] || filterValue;
	$container.isotope({ filter: filterValue });
});

// change is-checked class on buttons
$('.button-group').each( function( i, buttonGroup ) {
	var $buttonGroup = $( buttonGroup );
	$buttonGroup.on( 'click', 'button', function() {
	  $buttonGroup.find('.is-checked').removeClass('is-checked');
	  $( this ).addClass('is-checked');
	});
});
<|endoftext|>


<commit_before>/* Mock api/backend.js */
function mockBackend() {
    return {
        endpoints:  {
            features: {
                getAll: function () {}
            },
            client: {
                getAll: function () {}
            },
            productArea: {
                getAll: function () {}
            }
        }
    };
}

/* Mock response api/backend.js endpoints */
function mockResponse(payload, status=200) {
    return {
        body() {
            return {
                data() {
                    return payload;
                }
            };
        },

        statusCode() {
            return status;
        }
    };
}

function mockState() {
    return {
        features: [
            {
                title: 'Mock1',
                client: '/api/client/1/',
                product_area: '/api/productarea/1/'
            },
            {
                title: 'Mock2',
                client: '/api/client/2/',
                product_area: '/api/productarea/2/'
            },
            {
                title: 'Mock3',
                client: '/api/client/3/',
                product_area: '/api/productarea/3/'
            }
        ],
        clients: [
            {
                name: 'Client A',
                url: '/api/client/1/'
            },
            {
                name: 'Client B',
                url: '/api/client/2/'
            },
            {
                name: 'Client C',
                url: '/api/client/3/'
            }
        ],
        productAreas: [
            {
                name: 'Sales',
                url: '/api/productarea/1/'
            },
            {
                name: 'Marketing',
                url: '/api/productarea/2/'
            },
            {
                name: 'Widgets',
                url: '/api/productarea/3/'
            }
        ]
    };
}

export {mockBackend, mockResponse, mockState};
<commit_msg>Add headers to mockResponse<commit_after>/* Mock api/backend.js */
function mockBackend() {
    return {
        endpoints:  {
            features: {
                getAll: function () {}
            },
            client: {
                getAll: function () {}
            },
            productArea: {
                getAll: function () {}
            }
        }
    };
}

/* Mock response api/backend.js endpoints */
function mockResponse(payload, status=200, headers={}) {
    return {
        body() {
            return {
                data() {
                    return payload;
                }
            };
        },

        statusCode() {
            return status;
        },

        headers() {
            return headers;
        }
    };
}

function mockState() {
    return {
        features: [
            {
                title: 'Mock1',
                client: '/api/client/1/',
                product_area: '/api/productarea/1/'
            },
            {
                title: 'Mock2',
                client: '/api/client/2/',
                product_area: '/api/productarea/2/'
            },
            {
                title: 'Mock3',
                client: '/api/client/3/',
                product_area: '/api/productarea/3/'
            }
        ],
        clients: [
            {
                name: 'Client A',
                url: '/api/client/1/'
            },
            {
                name: 'Client B',
                url: '/api/client/2/'
            },
            {
                name: 'Client C',
                url: '/api/client/3/'
            }
        ],
        productAreas: [
            {
                name: 'Sales',
                url: '/api/productarea/1/'
            },
            {
                name: 'Marketing',
                url: '/api/productarea/2/'
            },
            {
                name: 'Widgets',
                url: '/api/productarea/3/'
            }
        ]
    };
}

export {mockBackend, mockResponse, mockState};
<|endoftext|>


<commit_before>function Shuffle(pContainer) {
    var container = null;

    var canvas = null;
    var border = 0;
    var context = null;
    var bgColor = null;

    var self = this;
    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    var alphaHash = {};
    var base_dir = 'images/';
    var fileextension = '.png';
    var i = 0;

    var getImages = function() {
        var letter = alphabet[i];
        if (i === alphabet.length || typeof(letter) === 'undefined') {
            return;
        }

        var dir = base_dir + letter + '/';
        alphaHash[letter] = [];

        $.ajax({
            //This will retrieve the contents of the folder
            //if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //List all .png file names in the page
                console.log(data);
                $(data).find('a:contains(' + fileextension + ')').each(function () {
                    var filename = this.href.replace(window.location.href, '').replace('http://', '');
                    var img = $("")[0];
                    alphaHash[letter].push(img);
                    $(container).append(img);
                });

                getImages(alphabet[++i]);
            }
        });
    };

    var getRandomInt = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    var getRandomImage = function(letter) {
        if (!alphaHash || !alphaHash[letter] ||
            alphaHash[letter].length === 0)
        {
            console.err('Fail to get images for letter: ', letter);
            return;
        }

        if (!context) {
            console.err('No context for canvas');
            return;
        }

        // pick random image from available
        var letterImages = alphaHash[letter];
        var index = getRandomInt(0, letterImages.length - 1)
        var img = letterImages[index];

        if (!img) {
            console.err('Images array overflow');
        }

        return img;
    };

    var drawLetter = function(letter) {
        var image = getRandomImage(letter);

        // if we have a set border, substrack its width/height
        // from canvas area
        var wlimit = canvas.width - border;
        wlimit = wlimit > 0 ? wlimit: 0;

        var hlimit = canvas.height - border;
        hlimit = hlimit > 0 ? hlimit: 0;

        var widthStart = getRandomInt(0, wlimit);
        var heightStart = getRandomInt(0, hlimit);
        var dstWidth = 0;
        var dstHeight = 0;

        var operation = getRandomInt(0, 1);
        if (operation === 0) {
            var scaleFactor = getRandomInt(1, 5);
            dstWidth = image.width / scaleFactor;
            dstHeight = image.height / scaleFactor;
        } else {
            var scaleFactor = getRandomInt(1, 2);
            dstWidth = image.width * scaleFactor;
            dstHeight = image.height * scaleFactor;
        }

        if (widthStart + dstWidth > canvas.width) {
            widthStart -= Math.abs((widthStart + dstWidth) - canvas.width);
        }

        if (heightStart + dstHeight > canvas.height) {
            heightStart -= Math.abs((heightStart + dstHeight) - canvas.height);
        }

        context.drawImage(image, widthStart, heightStart, dstWidth, dstHeight);
    };

    var registerListener = function() {
        $('body').keypress(function (ev) {
            var sign = String.fromCharCode(ev.which);
            if (alphabet.indexOf(sign) !== -1) {
                console.log(sign);
                drawLetter(sign);
            }
        });
    };

    function init() {
        container = $(pContainer);
        canvas = $('<canvas></canvas>')[0];
        context = canvas.getContext('2d');

        // resize to full screen
        console.log('shuffle(w: %d, h: %d)', container.width(), container.height());
        self.resize(container.width(), container.height(), 100);
        container.append(canvas);
        self.setBackground('white');

        registerListener();
        getImages();
    };

    this.getHash = function() {
        return alphaHash;
    };

    this.resize = function(w, h, borderSize) {
        console.log('canvas (w: %d, h: %d)', w, h);
        canvas.width = w;
        canvas.height = h;
        if (borderSize) {
            border = borderSize;
        }
    };

    this.clear = function() {
        context.beginPath();
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = bgColor;
        context.fill();
    };

    this.saveImage = function() {
        var data = canvas.toDataURL('image/png');
        var capture = data.replace(/^data:image\/[^;]*/, 'data:application/octet-stream;');
        return capture;
   };

    this.setBackground = function(color) {
        bgColor = color;
        self.clear();
    }

    init();
};
<commit_msg>* Decrease probability for scaleUp<commit_after>function Shuffle(pContainer) {
    var container = null;

    var canvas = null;
    var border = 0;
    var context = null;
    var bgColor = null;

    var self = this;
    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    var alphaHash = {};
    var base_dir = 'images/';
    var fileextension = '.png';
    var i = 0;

    var getImages = function() {
        var letter = alphabet[i];
        if (i === alphabet.length || typeof(letter) === 'undefined') {
            return;
        }

        var dir = base_dir + letter + '/';
        alphaHash[letter] = [];

        $.ajax({
            //This will retrieve the contents of the folder
            //if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //List all .png file names in the page
                console.log(data);
                $(data).find('a:contains(' + fileextension + ')').each(function () {
                    var filename = this.href.replace(window.location.href, '').replace('http://', '');
                    var img = $("")[0];
                    alphaHash[letter].push(img);
                    $(container).append(img);
                });

                getImages(alphabet[++i]);
            }
        });
    };

    var getRandomInt = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    var getRandomImage = function(letter) {
        if (!alphaHash || !alphaHash[letter] ||
            alphaHash[letter].length === 0)
        {
            console.err('Fail to get images for letter: ', letter);
            return;
        }

        if (!context) {
            console.err('No context for canvas');
            return;
        }

        // pick random image from available
        var letterImages = alphaHash[letter];
        var index = getRandomInt(0, letterImages.length - 1)
        var img = letterImages[index];

        if (!img) {
            console.err('Images array overflow');
        }

        return img;
    };

    var drawLetter = function(letter) {
        var image = getRandomImage(letter);

        // if we have a set border, substrack its width/height
        // from canvas area
        var wlimit = canvas.width - border;
        wlimit = wlimit > 0 ? wlimit: 0;

        var hlimit = canvas.height - border;
        hlimit = hlimit > 0 ? hlimit: 0;

        var widthStart = getRandomInt(0, wlimit);
        var heightStart = getRandomInt(0, hlimit);
        var dstWidth = 0;
        var dstHeight = 0;

        var operation = getRandomInt(0, 4);
        if (operation === 0) {
            var scaleFactor = getRandomInt(1, 2);
            dstWidth = image.width * scaleFactor;
            dstHeight = image.height * scaleFactor;
        } else {
            var scaleFactor = getRandomInt(1, 5);
            dstWidth = image.width / scaleFactor;
            dstHeight = image.height / scaleFactor;
        }

        if (widthStart + dstWidth > canvas.width) {
            widthStart -= Math.abs((widthStart + dstWidth) - canvas.width);
        }

        if (heightStart + dstHeight > canvas.height) {
            heightStart -= Math.abs((heightStart + dstHeight) - canvas.height);
        }

        context.drawImage(image, widthStart, heightStart, dstWidth, dstHeight);
    };

    var registerListener = function() {
        $('body').keypress(function (ev) {
            var sign = String.fromCharCode(ev.which);
            if (alphabet.indexOf(sign) !== -1) {
                console.log(sign);
                drawLetter(sign);
            }
        });
    };

    function init() {
        container = $(pContainer);
        canvas = $('<canvas></canvas>')[0];
        context = canvas.getContext('2d');

        // resize to full screen
        console.log('shuffle(w: %d, h: %d)', container.width(), container.height());
        self.resize(container.width(), container.height(), 100);
        container.append(canvas);
        self.setBackground('white');

        registerListener();
        getImages();
    };

    this.getHash = function() {
        return alphaHash;
    };

    this.resize = function(w, h, borderSize) {
        console.log('canvas (w: %d, h: %d)', w, h);
        canvas.width = w;
        canvas.height = h;
        if (borderSize) {
            border = borderSize;
        }
    };

    this.clear = function() {
        context.beginPath();
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = bgColor;
        context.fill();
    };

    this.saveImage = function() {
        var data = canvas.toDataURL('image/png');
        var capture = data.replace(/^data:image\/[^;]*/, 'data:application/octet-stream;');
        return capture;
   };

    this.setBackground = function(color) {
        bgColor = color;
        self.clear();
    }

    init();
};
<|endoftext|>


<commit_before>// SMTP in plugin for PEPS
// All rights reserved
// (c) MLstate, 2015
//
// Contains code from https://github.com/jplock/haraka-http-forward
// Copyright (c) 2013 Justin Plock
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

var request = require('request');
var host, domain;

exports.register = function () {
    var config = this.config.get('/etc/peps/smtpin.ini');
    if (config.main.host) {
        // TODO: IPv6
        var match = /^([^: ]+)(?::(\d+))?$/.exec(config.main.host);
        if (match) {
            host = config.main.host;
            request('http://' + host + '/domain',
                function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        domain = check_domain(host);
                    } else { throw new Error('could not get domain from ' + host); }
                }
            );
        }
    } else { throw new Error('configuration file missing') }
};

// // enable mail body parsing
// exports.hook_data = function (next, connection) {
//     connection.transaction.parse_body = 1;
//     return next();
// };

exports.hook_data_post = function (next, connection) {
    var transaction = connection.transaction;
    // TODO: check that recipients (transaction.rcpt_to) domain name?
    var options = {
        'uri': host,
        'headers': {
            'Content-Type': 'text/plain; charset=utf-8'
        },
        'method': 'post',
        'timeout': 1000,
        'pool': false,
        'jar': false
    };

    var forward = request.post(options);
    forward.on('error', function (err) {
        connection.logerror('Unable to connect to ' + host);
        return next(err);
    });
    forward.on('end', function () {
        connection.logdebug('end event');
        return next();
    });

    var pipe_options = {'dot_stuffing': true, 'ending_dot': true};
    transaction.message_stream.pipe(forward, pipe_options);
};
<commit_msg>Fix smtpin plugin<commit_after>// SMTP in plugin for PEPS
// All rights reserved
// (c) MLstate, 2015
//
// Contains code from https://github.com/jplock/haraka-http-forward
// Copyright (c) 2013 Justin Plock
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

var request = require('request');
var host, domain;

exports.register = function () {
    var config = this.config.get('/etc/peps/smtpin.ini');
    if (config.main.host) {
        // TODO: IPv6
        var match = /^([^: ]+)(?::(\d+))?$/.exec(config.main.host);
        if (match) {
            host = config.main.host;
            request('http://' + host + '/domain',
                function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        domain = body;
                    } else { throw new Error('could not get domain from ' + host); }
                }
            );
        }
    } else { throw new Error('configuration file missing') }
};

// // enable mail body parsing
// exports.hook_data = function (next, connection) {
//     connection.transaction.parse_body = 1;
//     return next();
// };

exports.hook_data_post = function (next, connection) {
    var transaction = connection.transaction;
    // TODO: check that recipients (transaction.rcpt_to) domain name?
    var options = {
        'uri': 'http://' + host,
        'headers': {
            'Content-Type': 'text/plain; charset=utf-8'
        },
        'method': 'post',
        'timeout': 1000,
        'pool': false,
        'jar': false
    };

    var forward = request.post(options);
    forward.on('error', function (err) {
        connection.logerror('Unable to connect to ' + host);
        return next(err);
    });
    forward.on('end', function () {
        connection.logdebug('end event');
        return next();
    });

    var pipe_options = {'dot_stuffing': true, 'ending_dot': true};
    transaction.message_stream.pipe(forward, pipe_options);
};
<|endoftext|>


<commit_before>'use strict';

var element    = require('../valid-html-element')
  , randomUniq = require('time-uuid');

module.exports = function () {
	if (element(this).id) return this.id;
	return (this.id = this.nodeName.toLowerCase() + '-' + randomUniq());
};
<commit_msg>Support name string in `getId` method<commit_after>'use strict';

var generateId = require('../../html-document/generate-id')
  , element    = require('../valid-html-element');

module.exports = function (name) {
	var id;
	if (element(this).id) return this.id;
	if (name != null) id = generateId(name);
	else id = this.nodeName.toLowerCase() + '-' + generateId();
	return (this.id = id);
};
<|endoftext|>


<commit_before>exports.init = function(io){

	//number of players
	var currentPlayers = 0;

	//new connection is initiated
	io.sockets.on('connection', function (socket){

		var timer = require('../models/countdownTimer.js');
		var s = require('../models/scores.js');
		var http = require('http');
		var mr = require('../routes/dbRoutes.js');

		++ currentPlayers; //increase number of players
		//let everyone know about players
		socket.emit('players', {number: currentPlayers});
		socket.broadcast.emit('players', {number: currentPlayers});

		//Game Details
		var category;
		var totalScore = 0;
		var playerName = "";
		var gameOver = false;
		var remainingTime;
		var duration;

		//1. get player name
		socket.on('newPlayer', function(data){
			playerName = data.playerName;
			console.log("Player Name: "+data.playerName);
		});

		//2. select category
		socket.on('selectCategory', function(data){
			category = data.category;
			console.log("Category: "+category.name);
		});

		//3. start game
		//start timer
		socket.on('startGame', function(){
			duration = 300000; //5 minutes for each round
			timer.startTimer(duration);
			//countdown timer
			countdown();
			//first card:
			var i=0;
			socket.emit('cardDisplay', {'category': category, 'index': i});
		});
		//next cards
		socket.on('cardStatus', function(data){
			var i = data.index;
			if (remainingTime<duration && i<category.cards.length-1){
				//next card
				i++;
				socket.emit('cardDisplay', {'category': category, 'index': i});
			}
			else{
				//reached end of all cards
				gameOver = true;
			}
		});
		//score tracker
		socket.on('scoreStatus', function(data){
			totalScore=data.totalScore;
			console.log("Total Score on server side: "+totalScore);
		})
		function countdown(){
			remainingTime = timer.getTime();
			//send time info to client
			socket.emit('timeRemaining', {'min': timer.parseTime(remainingTime)[0], 'sec': timer.parseTime(remainingTime)[1]});
			if(remainingTime>duration){gameOver=true;}
			if(gameOver==false){setTimeout(countdown, 1000);}
			else if(gameOver==true){endGame();}
		}

		//4. game over: called by timer
		//send player name, score, remaining time, number of correct/ wrong, time reamining
		//broadcast that to all players and stop all sessions
		socket.on('endGame', function(){
			gameOver = true;
			endGame();
		})

		function endGame(){
			//number of correct/ wrong
			numRight = totalScore/s.scoreSuccess;
			numWrong = category.cards.length - numRight;
			//pass all game details to client for views
			socket.emit('gameOver', {'playerName': playerName, 'totalScore': totalScore, 'numRight': numRight, 'numWrong': numWrong, 'category': category,  'remainingTime': remainingTime});
			socket.broadcast.emit('gameOver', {'playerName': playerName, 'totalScore': totalScore, 'numRight': numRight, 'numWrong': numWrong, 'category': category,  'remainingTime': remainingTime});
		}

		socket.on('disconnect', function(){
			--currentPlayers;
			socket.broadcast.emit('players', { number: currentPlayers});
		});
	})
}<commit_msg>TO clear session data in openshift<commit_after>var timer = require('../models/countdownTimer.js');
var s = require('../models/scores.js');
var http = require('http');
var mr = require('../routes/dbRoutes.js');

exports.init = function(io){

	//number of players
	var currentPlayers = 0;

	//new connection is initiated
	io.sockets.on('connection', function (socket){
		++ currentPlayers; //increase number of players
		//let everyone know about players
		socket.emit('players', {number: currentPlayers});
		socket.broadcast.emit('players', {number: currentPlayers});

		//Game Details
		var category;
		var totalScore = 0;
		var playerName = "";
		var gameOver = false;
		var remainingTime;
		var duration;

		//1. get player name
		socket.on('newPlayer', function(data){
			playerName = data.playerName;
			console.log("Player Name: "+data.playerName);
		});

		//2. select category
		socket.on('selectCategory', function(data){
			category = data.category;
			console.log("Category: "+category.name);
		});

		//3. start game
		//start timer
		socket.on('startGame', function(){
			duration = 300000; //5 minutes for each round
			timer.startTimer(duration);
			//countdown timer
			countdown();
			//first card:
			var i=0;
			socket.emit('cardDisplay', {'category': category, 'index': i});
		});
		//next cards
		socket.on('cardStatus', function(data){
			var i = data.index;
			if (remainingTime<duration && i<category.cards.length-1){
				//next card
				i++;
				socket.emit('cardDisplay', {'category': category, 'index': i});
			}
			else{
				//reached end of all cards
				gameOver = true;
			}
		});
		//score tracker
		socket.on('scoreStatus', function(data){
			totalScore=data.totalScore;
			console.log("Total Score on server side: "+totalScore);
		})
		function countdown(){
			remainingTime = timer.getTime();
			//send time info to client
			socket.emit('timeRemaining', {'min': timer.parseTime(remainingTime)[0], 'sec': timer.parseTime(remainingTime)[1]});
			if(remainingTime>duration){gameOver=true;}
			if(gameOver==false){setTimeout(countdown, 1000);}
			else if(gameOver==true){endGame();}
		}

		//4. game over: called by timer
		//send player name, score, remaining time, number of correct/ wrong, time reamining
		//broadcast that to all players and stop all sessions
		socket.on('endGame', function(){
			gameOver = true;
			endGame();
		})

		function endGame(){
			//number of correct/ wrong
			numRight = totalScore/s.scoreSuccess;
			numWrong = category.cards.length - numRight;
			//pass all game details to client for views
			socket.emit('gameOver', {'playerName': playerName, 'totalScore': totalScore, 'numRight': numRight, 'numWrong': numWrong, 'category': category,  'remainingTime': remainingTime});
			socket.broadcast.emit('gameOver', {'playerName': playerName, 'totalScore': totalScore, 'numRight': numRight, 'numWrong': numWrong, 'category': category,  'remainingTime': remainingTime});
		}

		socket.on('disconnect', function(){
			--currentPlayers;
			socket.broadcast.emit('players', { number: currentPlayers});
		});
	})
}<|endoftext|>


<commit_before>(function() {

  var SimDispatcher = function() {
    this.fluxDispatcher = new Flux.Dispatcher();
  };

  SimDispatcher.prototype.registerStore = function(store) {
    store.$$$dispatcherToken = this.fluxDispatcher.register(function(payload) {
      if (store[payload.action]) store[payload.action].apply(store, payload.args);
    });
    return store;
  };

  SimDispatcher.prototype.unregisterStore = function(store) {
    this.fluxDispatcher.unregister(store.$$$dispatcherToken);
    delete store.$$$dispatcherToken;
    return store;
  };

  // unlike Facebook's dispatcher, the first argument is action and after that
  // we can pass in any number of arguments
  //
  // Original: dispatcher.dispatch({ type: 'ACTION_TYPE', data: {whatever:data} })
  //      New: dispatcher.dispatch('ACTION_TYPE', arg1, arg2, ...)
  SimDispatcher.prototype.dispatch = function(action) {
    return this.fluxDispatcher.dispatch({
      action: action,
      args: Array.prototype.slice.call(arguments, 1)
    });
  };

  // waitFor takes a list of stores instead of tokens
  SimDispatcher.prototype.waitFor = function (stores) {
    var tokens = [];
    for (var i=0; i<stores.length; i++) {
      tokens.push(stores[i].$$$dispatcherToken);
    }
    return this.fluxDispatcher.waitFor(tokens);
  };

  // todo: use prototypical inheritance instead
  SimDispatcher.prototype.isDispatching=function() {
    return this.fluxDispatcher.isDispatching();
  };

  window.simflux = {
    version: 'pre-beta',
    Dispatcher: SimDispatcher
  };

})();<commit_msg>rename SimDispatcher-->SimfluxDispatcher<commit_after>(function() {

  var SimfluxDispatcher = function() {
    this.fluxDispatcher = new Flux.Dispatcher();
  };

  SimfluxDispatcher.prototype.registerStore = function(store) {
    store.$$$dispatcherToken = this.fluxDispatcher.register(function(payload) {
      if (store[payload.action]) store[payload.action].apply(store, payload.args);
    });
    return store;
  };

  SimfluxDispatcher.prototype.unregisterStore = function(store) {
    this.fluxDispatcher.unregister(store.$$$dispatcherToken);
    delete store.$$$dispatcherToken;
    return store;
  };

  // unlike Facebook's dispatcher, the first argument is action and after that
  // we can pass in any number of arguments
  //
  // Original: dispatcher.dispatch({ type: 'ACTION_TYPE', data: {whatever:data} })
  //      New: dispatcher.dispatch('ACTION_TYPE', arg1, arg2, ...)
  SimfluxDispatcher.prototype.dispatch = function(action) {
    return this.fluxDispatcher.dispatch({
      action: action,
      args: Array.prototype.slice.call(arguments, 1)
    });
  };

  // waitFor takes a list of stores instead of tokens
  SimfluxDispatcher.prototype.waitFor = function (stores) {
    var tokens = [];
    for (var i=0; i<stores.length; i++) {
      tokens.push(stores[i].$$$dispatcherToken);
    }
    return this.fluxDispatcher.waitFor(tokens);
  };

  // todo: use prototypical inheritance instead
  SimfluxDispatcher.prototype.isDispatching=function() {
    return this.fluxDispatcher.isDispatching();
  };

  window.simflux = {
    version: 'pre-beta',
    Dispatcher: SimfluxDispatcher
  };

})();<|endoftext|>