<commit_before>var Class = require('../../utils/Class');
var BaseSound = require('../BaseSound');
//  Phaser.Sound.WebAudioSound
// TODO support webkitAudioContext implementation differences
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
var WebAudioSound = new Class({
    Extends: BaseSound,
    initialize: function WebAudioSound(manager, key, config) {
        if (config === void 0) { config = {}; }
        /**
         * [description]
         *
         * @property {AudioBuffer} audioBuffer
         */
        this.audioBuffer = manager.game.cache.audio.get(key);
        if (!this.audioBuffer) {
            console.error('No audio loaded in cache with key: \'' + key + '\'!');
            return;
        }
        /**
         * [description]
         *
         * @property {AudioBufferSourceNode} source
         */
        this.source = null;
        /**
         * [description]
         *
         * @property {GainNode} muteNode
         */
        this.muteNode = manager.context.createGain();
        /**
         * [description]
         *
         * @property {GainNode} volumeNode
         */
        this.volumeNode = manager.context.createGain();
        /**
         * The time the previous playback started at based on
         * BaseAudioContext.currentTime value.
         *
         * @property {number} startTime
         */
        this.startTime = 0;
        /**
         * Relative time when sound was paused.
         * Corresponds to the seek value at the time when pause() method was called on this sound.
         *
         * @property {number} pausedTime
         */
        this.pausedTime = 0;
        this.muteNode.connect(this.volumeNode);
        this.volumeNode.connect(manager.destination);
        BaseSound.call(this, manager, key, config);
        this.duration = this.audioBuffer.duration;
        this.totalDuration = this.audioBuffer.duration;
    },
    play: function (markerName, config) {
        if (!BaseSound.prototype.play.call(this, markerName, config)) {
            return null;
        }
        this.stopAndRemoveBufferSource();
        // TODO include config offset and marker start
        var offset = this.currentMarker ? this.currentMarker.start : 0;
        var duration = this.duration;
        this.createAndStartBufferSource(offset, duration);
        this.startTime = this.manager.context.currentTime;
        this.pausedTime = 0;
        return this;
    },
    pause: function () {
        if (!BaseSound.prototype.pause.call(this)) {
            return false;
        }
        this.stopAndRemoveBufferSource();
        this.pausedTime = this.manager.context.currentTime - this.startTime;
        return true;
    },
    resume: function () {
        if (!BaseSound.prototype.resume.call(this)) {
            return false;
        }
        var offset = this.pausedTime; // TODO include marker start time
        var duration = this.duration - this.pausedTime;
        this.createAndStartBufferSource(offset, duration);
        this.startTime = this.manager.context.currentTime - this.pausedTime;
        this.pausedTime = 0;
        return true;
    },
    stop: function () {
        if (!BaseSound.prototype.stop.call(this)) {
            return false;
        }
        this.stopAndRemoveBufferSource();
        this.startTime = 0;
        this.pausedTime = 0;
        return true;
    },
    /**
     * Used internally to do what the name says.
     *
     * @private
     * @param {number} offset
     * @param {number} duration
     */
    // TODO add when param
    createAndStartBufferSource: function (offset, duration) {
        this.source = this.manager.context.createBufferSource();
        this.source.buffer = this.audioBuffer;
        this.source.connect(this.muteNode);
        this.applyConfig();
        // TODO add onended event handler to reset sound state
        this.source.start(0, offset, duration);
    },
    /**
     * Used internally to do what the name says.
     *
     * @private
     */
    stopAndRemoveBufferSource: function () {
        if (this.source) {
            this.source.stop();
            this.source = null;
        }
    },
    update: function () {
    },
    destroy: function () {
    }
});
/**
 * Mute setting.
 * @property {boolean} mute
 */
Object.defineProperty(WebAudioSound.prototype, 'mute', {
    get: function () {
        return this.muteNode.gain.value === 0;
    },
    set: function (value) {
        this.currentConfig.mute = value;
        this.muteNode.gain.setValueAtTime(value ? 0 : 1, 0);
    }
});
/**
 * Volume setting.
 * @property {number} volume
 */
Object.defineProperty(WebAudioSound.prototype, 'volume', {
    get: function () {
        return this.volumeNode.gain.value;
    },
    set: function (value) {
        this.currentConfig.volume = value;
        this.volumeNode.gain.setValueAtTime(value, 0);
    }
});
/**
 * Playback rate.
 * @property {number} rate
 */
Object.defineProperty(WebAudioSound.prototype, 'rate', {
    get: function () {
        return this.currentConfig.rate;
    },
    set: function (value) {
        this.currentConfig.rate = value;
        if (this.source) {
            this.source.playbackRate.setValueAtTime(value * this.manager.rate, 0);
        }
    }
});
/**
 * Detuning of sound.
 * @property {number} detune
 */
Object.defineProperty(WebAudioSound.prototype, 'detune', {
    get: function () {
        return this.currentConfig.detune;
    },
    set: function (value) {
        this.currentConfig.detune = value;
        if (this.source && this.source.detune) {
            this.source.detune.setValueAtTime(Math.max(-1200, Math.min(value + this.manager.detune, 1200)), 0);
        }
    }
});
module.exports = WebAudioSound;
<commit_msg>Taking into account marker start time on resuming sound<commit_after>var Class = require('../../utils/Class');
var BaseSound = require('../BaseSound');
//  Phaser.Sound.WebAudioSound
// TODO support webkitAudioContext implementation differences
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
var WebAudioSound = new Class({
    Extends: BaseSound,
    initialize: function WebAudioSound(manager, key, config) {
        if (config === void 0) { config = {}; }
        /**
         * [description]
         *
         * @property {AudioBuffer} audioBuffer
         */
        this.audioBuffer = manager.game.cache.audio.get(key);
        if (!this.audioBuffer) {
            console.error('No audio loaded in cache with key: \'' + key + '\'!');
            return;
        }
        /**
         * [description]
         *
         * @property {AudioBufferSourceNode} source
         */
        this.source = null;
        /**
         * [description]
         *
         * @property {GainNode} muteNode
         */
        this.muteNode = manager.context.createGain();
        /**
         * [description]
         *
         * @property {GainNode} volumeNode
         */
        this.volumeNode = manager.context.createGain();
        /**
         * The time the previous playback started at based on
         * BaseAudioContext.currentTime value.
         *
         * @property {number} startTime
         */
        this.startTime = 0;
        /**
         * Relative time when sound was paused.
         * Corresponds to the seek value at the time when pause() method was called on this sound.
         *
         * @property {number} pausedTime
         */
        this.pausedTime = 0;
        this.muteNode.connect(this.volumeNode);
        this.volumeNode.connect(manager.destination);
        BaseSound.call(this, manager, key, config);
        this.duration = this.audioBuffer.duration;
        this.totalDuration = this.audioBuffer.duration;
    },
    play: function (markerName, config) {
        if (!BaseSound.prototype.play.call(this, markerName, config)) {
            return null;
        }
        this.stopAndRemoveBufferSource();
        // TODO include config offset and marker start
        var offset = this.currentMarker ? this.currentMarker.start : 0;
        var duration = this.duration;
        this.createAndStartBufferSource(offset, duration);
        this.startTime = this.manager.context.currentTime;
        this.pausedTime = 0;
        return this;
    },
    pause: function () {
        if (!BaseSound.prototype.pause.call(this)) {
            return false;
        }
        this.stopAndRemoveBufferSource();
        this.pausedTime = this.manager.context.currentTime - this.startTime;
        return true;
    },
    resume: function () {
        if (!BaseSound.prototype.resume.call(this)) {
            return false;
        }
        var offset = (this.currentMarker ? this.currentMarker.start : 0) + this.pausedTime;
        var duration = this.duration - this.pausedTime;
        this.createAndStartBufferSource(offset, duration);
        this.startTime = this.manager.context.currentTime - this.pausedTime;
        this.pausedTime = 0;
        return true;
    },
    stop: function () {
        if (!BaseSound.prototype.stop.call(this)) {
            return false;
        }
        this.stopAndRemoveBufferSource();
        this.startTime = 0;
        this.pausedTime = 0;
        return true;
    },
    /**
     * Used internally to do what the name says.
     *
     * @private
     * @param {number} offset
     * @param {number} duration
     */
    // TODO add when param
    createAndStartBufferSource: function (offset, duration) {
        this.source = this.manager.context.createBufferSource();
        this.source.buffer = this.audioBuffer;
        this.source.connect(this.muteNode);
        this.applyConfig();
        // TODO add onended event handler to reset sound state
        this.source.start(0, offset, duration);
    },
    /**
     * Used internally to do what the name says.
     *
     * @private
     */
    stopAndRemoveBufferSource: function () {
        if (this.source) {
            this.source.stop();
            this.source = null;
        }
    },
    update: function () {
    },
    destroy: function () {
    }
});
/**
 * Mute setting.
 * @property {boolean} mute
 */
Object.defineProperty(WebAudioSound.prototype, 'mute', {
    get: function () {
        return this.muteNode.gain.value === 0;
    },
    set: function (value) {
        this.currentConfig.mute = value;
        this.muteNode.gain.setValueAtTime(value ? 0 : 1, 0);
    }
});
/**
 * Volume setting.
 * @property {number} volume
 */
Object.defineProperty(WebAudioSound.prototype, 'volume', {
    get: function () {
        return this.volumeNode.gain.value;
    },
    set: function (value) {
        this.currentConfig.volume = value;
        this.volumeNode.gain.setValueAtTime(value, 0);
    }
});
/**
 * Playback rate.
 * @property {number} rate
 */
Object.defineProperty(WebAudioSound.prototype, 'rate', {
    get: function () {
        return this.currentConfig.rate;
    },
    set: function (value) {
        this.currentConfig.rate = value;
        if (this.source) {
            this.source.playbackRate.setValueAtTime(value * this.manager.rate, 0);
        }
    }
});
/**
 * Detuning of sound.
 * @property {number} detune
 */
Object.defineProperty(WebAudioSound.prototype, 'detune', {
    get: function () {
        return this.currentConfig.detune;
    },
    set: function (value) {
        this.currentConfig.detune = value;
        if (this.source && this.source.detune) {
            this.source.detune.setValueAtTime(Math.max(-1200, Math.min(value + this.manager.detune, 1200)), 0);
        }
    }
});
module.exports = WebAudioSound;
<|endoftext|>


<commit_before>const React = require("react");
const sendEvent = require("../../browser-send-event.js");

exports.ShareButton = class ShareButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      display: false
    };
  }

  render() {
    let panel = null;
    if (this.state.display) {
      panel =  <ShareButtonPanel
        clipUrl={this.props.clipUrl}
        closePanel={this.onPanelClose.bind(this)} shot={this.props.shot}
        staticLink={this.props.staticLink}
        renderExtensionNotification={this.props.renderExtensionNotification}
        isOwner={this.props.isOwner}
        sendRichCopy={this.props.sendRichCopy}
        isExtInstalled={this.props.isExtInstalled}
      />;
    }
    return

      <button className="button primary" id="toggle-share" onClick={ this.onClick.bind(this) }>
        Share
      </button>
      {panel}

;
  }

  onClick() {
    let show = ! this.state.display;
    this.setState({display: show});
    if (show) {
      sendEvent(
        this.props.isOwner ? "start-share-owner" : "start-share-non-owner",
        "navbar");
    } else {
      sendEvent("cancel-share");
    }
  }

  onPanelClose() {
    this.setState({display: false});
  }

};

class ShareButtonPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {copyText: "Copy"};
    this.clickMaybeClose = this.clickMaybeClose.bind(this);
    this.keyMaybeClose = this.keyMaybeClose.bind(this);
  }

  onClickShareButton(whichButton) {
    sendEvent(
      this.props.isOwner ? "share-owner" : "share-non-owner",
      whichButton);
  }

  onClickCopyButton(e) {
    let target = e.target;
    target.previousSibling.select();
    document.execCommand("copy");
    this.setState({copyText: "Copied"});
    setTimeout(() => {
      this.setState({copyText: "Copy"});
    }, 1000);
    sendEvent("share", "copy");
  }

  onClickInputField(e) {
    e.target.select();
    sendEvent("share", "focus-url");
  }

  onClickRichCopy(event) {
    event.preventDefault();
    this.props.sendRichCopy();
    sendEvent("share", "rich-copy");
    return false;
  }

  render() {
    let className = "share-panel default-color-scheme";
    if (this.props.renderExtensionNotification) {
      className += " share-panel-with-notification";
    }
    return

        {this.props.isExtInstalled ?

           : null}

Get a shareable link to this shot:

        <input className="copy-shot-link-input"
          value={ this.props.shot.viewUrl }
          onClick={ this.onClickInputField.bind(this) }
          onChange={ function () {} /* react gives a warning otherwise */ } />
        <button
          className="button secondary copy-toggle"
          onClick={ this.onClickCopyButton.bind(this) }>
          { this.state.copyText }
        </button>

        This shot is only visible to you until you share the link.

;
  }

  componentDidMount() {
    document.addEventListener("click", this.clickMaybeClose, false);
    document.addEventListener("keyup", this.keyMaybeClose, false);
  }

  componentWillUnmount() {
    document.removeEventListener("click", this.clickMaybeClose, false);
    document.removeEventListener("keyup", this.keyMaybeClose, false);
  }

  clickMaybeClose(event) {
    if (! this.isPanel(event.target)) {
      this.props.closePanel();
    }
  }

  keyMaybeClose(event) {
    if ((event.key || event.code) == "Escape") {
      this.props.closePanel();
    }
  }

  /* Returns true if the element is part of the share panel */
  isPanel(el) {
    while (el) {
      if (el.id == "share-buttons-panel") {
        return true;
      }
      el = el.parentNode;
    }
    return false;
  }

}
<commit_msg>Fix #2034, close the share panel after clicking on an item<commit_after>const React = require("react");
const sendEvent = require("../../browser-send-event.js");

exports.ShareButton = class ShareButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      display: false
    };
  }

  render() {
    let panel = null;
    if (this.state.display) {
      panel =  <ShareButtonPanel
        clipUrl={this.props.clipUrl}
        closePanel={this.onPanelClose.bind(this)} shot={this.props.shot}
        staticLink={this.props.staticLink}
        renderExtensionNotification={this.props.renderExtensionNotification}
        isOwner={this.props.isOwner}
        sendRichCopy={this.props.sendRichCopy}
        isExtInstalled={this.props.isExtInstalled}
      />;
    }
    return

      <button className="button primary" id="toggle-share" onClick={ this.onClick.bind(this) }>
        Share
      </button>
      {panel}

;
  }

  onClick() {
    let show = ! this.state.display;
    this.setState({display: show});
    if (show) {
      sendEvent(
        this.props.isOwner ? "start-share-owner" : "start-share-non-owner",
        "navbar");
    } else {
      sendEvent("cancel-share");
    }
  }

  onPanelClose() {
    this.setState({display: false});
  }

};

class ShareButtonPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {copyText: "Copy"};
    this.clickMaybeClose = this.clickMaybeClose.bind(this);
    this.keyMaybeClose = this.keyMaybeClose.bind(this);
  }

  onClickShareButton(whichButton) {
    sendEvent(
      this.props.isOwner ? "share-owner" : "share-non-owner",
      whichButton);
    this.props.closePanel();
  }

  onClickCopyButton(e) {
    let target = e.target;
    target.previousSibling.select();
    document.execCommand("copy");
    this.setState({copyText: "Copied"});
    setTimeout(() => {
      this.setState({copyText: "Copy"});
    }, 1000);
    sendEvent("share", "copy");
  }

  onClickInputField(e) {
    e.target.select();
    sendEvent("share", "focus-url");
  }

  onClickRichCopy(event) {
    event.preventDefault();
    this.props.sendRichCopy();
    sendEvent("share", "rich-copy");
    this.props.closePanel();
    return false;
  }

  render() {
    let className = "share-panel default-color-scheme";
    if (this.props.renderExtensionNotification) {
      className += " share-panel-with-notification";
    }
    return

        {this.props.isExtInstalled ?

           : null}

Get a shareable link to this shot:

        <input className="copy-shot-link-input"
          value={ this.props.shot.viewUrl }
          onClick={ this.onClickInputField.bind(this) }
          onChange={ function () {} /* react gives a warning otherwise */ } />
        <button
          className="button secondary copy-toggle"
          onClick={ this.onClickCopyButton.bind(this) }>
          { this.state.copyText }
        </button>

        This shot is only visible to you until you share the link.

;
  }

  componentDidMount() {
    document.addEventListener("click", this.clickMaybeClose, false);
    document.addEventListener("keyup", this.keyMaybeClose, false);
  }

  componentWillUnmount() {
    document.removeEventListener("click", this.clickMaybeClose, false);
    document.removeEventListener("keyup", this.keyMaybeClose, false);
  }

  clickMaybeClose(event) {
    if (! this.isPanel(event.target)) {
      this.props.closePanel();
    }
  }

  keyMaybeClose(event) {
    if ((event.key || event.code) == "Escape") {
      this.props.closePanel();
    }
  }

  /* Returns true if the element is part of the share panel */
  isPanel(el) {
    while (el) {
      if (el.id == "share-buttons-panel") {
        return true;
      }
      el = el.parentNode;
    }
    return false;
  }

}
<|endoftext|>


<commit_before>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */

'use strict'

/**
 * HttpServerAgent - wraping createServer to add instrumentation
 *
 */

var http = require('http')
var https = require('https')

module.exports = function httpServerAgent () {
  var SpmAgent = require('spm-agent')
  var Agent = SpmAgent.Agent
  var config = SpmAgent.Config
  var logger = SpmAgent.Logger
  var Measured = require('measured')
  var stats = Measured.createCollection()
  var histogram = new Measured.Histogram()
  var timer = new Measured.Timer()
  var resSize = 0
  var reqSize = 0

  var hAgent = new Agent(
  {
    start: function (agent) {
      this._agent = agent
      resSize = 0
      reqSize = 0
      function monitorHttp (req, res) {
        try {
          req._stopwatch = timer.start()
          var endOfConnectionHandler = function () {
            var duration = req._stopwatch.end()
            stats.meter('requests').mark()
            // until backend is changed to float, we need to stay with in value in ms
            histogram.update(Math.round (duration), new Date().getTime())
            if (res.getHeader)
              resSize += ((res.getHeader('Content-Length') || 0) * 1)
            if (req.headers)
              reqSize += (req.headers ['content-length'] || 0) * 1
            if (res.statusCode >= 300) {
              stats.meter('errRate').mark()
              if (res.statusCode < 400) {
                stats.meter('3xxRate').mark()
              } else if (res.statusCode < 500) {
                stats.meter('4xxRate').mark()
              } else if (res.statusCode >= 500) {
                stats.meter('5xxRate').mark()
              }
            }
            res.removeListener('finish', endOfConnectionHandler)
            res.removeListener('close', endOfConnectionHandler)
          }
          res.on('finish', endOfConnectionHandler)
          res.on('close', endOfConnectionHandler)
        } catch (ex) {
          logger.error(ex)
        }
      }
      patchHttpServer(monitorHttp)
      patchHttpsServer(monitorHttp)
      var timerId = setInterval(function () {
        var httpStats = stats.toJSON()
        var responseTimes = histogram.toJSON()
        var now = new Date().getTime()

        var metricValue = [
          httpStats ['requests'] ? httpStats ['requests'].count : 0,                    // http.requestCount (int)
          httpStats ['errRate'] ? httpStats ['errRate'].count : 0,                      // http.errorCount (int)
          httpStats ['3xxRate'] ? httpStats ['3xxRate'].count : 0,                      // http.3xx (int)
          httpStats ['4xxRate'] ? httpStats ['4xxRate'].count : 0,                      // http.4xx (int)
          httpStats ['5xxRate'] ? httpStats ['5xxRate'].count : 0,                      // http.5xx (int)
          reqSize,
          resSize,
          responseTimes.min,
          responseTimes.max,
          responseTimes.sum
        ]
        if (metricValue[0] > 0 || metricValue[1] > 0)
          agent.addMetrics({ts: now, name: 'http', value: metricValue })

        stats = Measured.createCollection()
        histogram.reset()
        timer = new Measured.Timer()
        reqSize = 0
        resSize = 0
      }, config.collectionInterval)
      if (timerId.unref)
        timerId.unref()
    }
  })
  return hAgent
}

var origHttpCreateServer = http.createServer
var origHttpsCreateServer = https.createServer
function patchHttpServer (monitorReqHandler) {
  http.createServer = function (original) {
    var server = null
    if (original) {
      server = origHttpCreateServer(original)
    } else {
      server = origHttpCreateServer()
    }
    server.on('request', monitorReqHandler)
    return server
  }
}
function patchHttpsServer (monitorReqHandler) {
  https.createServer = function (original) {
    var server = null
    if (original) {
      server = origHttpCreateServer(original)
    } else {
      server = origHttpCreateServer()
    }
    server.on('request', monitorReqHandler)
    return server
  }
}
function unpatchHttpServer () {
  http.createServer = origHttpCreateServer
}

function unpatchHttpsServer () {
  https.createServer = origHttpsCreateServer
}

module.exports.unpatchHttpServer = unpatchHttpServer
module.exports.unpatchHttpsServer = unpatchHttpsServer
<commit_msg>standard code formatting<commit_after>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */

'use strict'

/**
 * HttpServerAgent - wraping createServer to add instrumentation
 *
 */

var http = require('http')
var https = require('https')

module.exports = function httpServerAgent () {
  var SpmAgent = require('spm-agent')
  var Agent = SpmAgent.Agent
  var config = SpmAgent.Config
  var logger = SpmAgent.Logger
  var Measured = require('measured')
  var stats = Measured.createCollection()
  var histogram = new Measured.Histogram()
  var timer = new Measured.Timer()
  var resSize = 0
  var reqSize = 0

  var hAgent = new Agent(
  {
    start: function (agent) {
      this._agent = agent
      resSize = 0
      reqSize = 0
      function monitorHttp (req, res) {
        try {
          req._stopwatch = timer.start()
          var endOfConnectionHandler = function () {
            var duration = req._stopwatch.end()
            stats.meter('requests').mark()
            // until backend is changed to float, we need to stay with in value in ms
            histogram.update(Math.round(duration), new Date().getTime())
            if (res.getHeader)
              resSize += ((res.getHeader('Content-Length') || 0) * 1)
            if (req.headers)
              reqSize += (req.headers ['content-length'] || 0) * 1
            if (res.statusCode >= 300) {
              stats.meter('errRate').mark()
              if (res.statusCode < 400) {
                stats.meter('3xxRate').mark()
              } else if (res.statusCode < 500) {
                stats.meter('4xxRate').mark()
              } else if (res.statusCode >= 500) {
                stats.meter('5xxRate').mark()
              }
            }
            res.removeListener('finish', endOfConnectionHandler)
            res.removeListener('close', endOfConnectionHandler)
          }
          res.on('finish', endOfConnectionHandler)
          res.on('close', endOfConnectionHandler)
        } catch (ex) {
          logger.error(ex)
        }
      }
      patchHttpServer(monitorHttp)
      patchHttpsServer(monitorHttp)
      var timerId = setInterval(function () {
        var httpStats = stats.toJSON()
        var responseTimes = histogram.toJSON()
        var now = new Date().getTime()
        var metricValue = [
          httpStats ['requests'] ? httpStats ['requests'].count : 0,                    // http.requestCount (int)
          httpStats ['errRate'] ? httpStats ['errRate'].count : 0,                      // http.errorCount (int)
          httpStats ['3xxRate'] ? httpStats ['3xxRate'].count : 0,                      // http.3xx (int)
          httpStats ['4xxRate'] ? httpStats ['4xxRate'].count : 0,                      // http.4xx (int)
          httpStats ['5xxRate'] ? httpStats ['5xxRate'].count : 0,                      // http.5xx (int)
          reqSize,
          resSize,
          responseTimes.min,
          responseTimes.max,
          responseTimes.sum
        ]
        if (metricValue[0] > 0 || metricValue[1] > 0)
          agent.addMetrics({ts: now, name: 'http', value: metricValue })
        stats = Measured.createCollection()
        histogram.reset()
        timer = new Measured.Timer()
        reqSize = 0
        resSize = 0
      }, config.collectionInterval)
      if (timerId.unref)
        timerId.unref()
    }
  })
  return hAgent
}

var origHttpCreateServer = http.createServer
var origHttpsCreateServer = https.createServer
function patchHttpServer (monitorReqHandler) {
  http.createServer = function (original) {
    var server = null
    if (original) {
      server = origHttpCreateServer(original)
    } else {
      server = origHttpCreateServer()
    }
    server.on('request', monitorReqHandler)
    return server
  }
}
function patchHttpsServer (monitorReqHandler) {
  https.createServer = function (original) {
    var server = null
    if (original) {
      server = origHttpCreateServer(original)
    } else {
      server = origHttpCreateServer()
    }
    server.on('request', monitorReqHandler)
    return server
  }
}
function unpatchHttpServer () {
  http.createServer = origHttpCreateServer
}

function unpatchHttpsServer () {
  https.createServer = origHttpsCreateServer
}

module.exports.unpatchHttpServer = unpatchHttpServer
module.exports.unpatchHttpsServer = unpatchHttpsServer
<|endoftext|>


<commit_before>
var debug = false;

$(document).ready(function() {

    $('head').append('<link rel="stylesheet" href="../d3tree.css" type="text/css" />');
    includes([
        'lodash.js',
        '../d3/d3.js',
        '../prooftree.js',
    ],
    function() {

        PT.handleKeyboard();
        setupTextareaResizing();
        resetCoq();
        separateCode();
        makeCodeInteractive();

    });

});

// note the


<commit_before>/*
   Copyright 2011 Google Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

var IntentController = new (function() {

  var intent;

  var setText = function(obj, text) {
    obj.appendChild(document.createTextNode(text));
  };

  this.setIntent = function(i) {
    intent = i;
  }

  this.getIntent = function() {
    return intent;
  }

  this.renderActionContainer = function (action, root) {
    var header = document.createElement("h2");
    setText(header, action.key);
    var collection = document.createElement("ul");

    root.appendChild(header);
    root.appendChild(collection);

    return collection;
  };

  this.renderActions = function(actions, intent, root) {
    root = root || document.getElementById("actions");
    var action;
    for(var i = 0; action = actions[i]; i++) {
      var actionElement = renderAction(action, intent);
      root.appendChild(actionElement);
    }
  };

  var launch = function(intent, disposition) {
    return function(e) {
      if(!!e.preventDefault)
        e.preventDefault();
      else
        e.returnValue = false;

      var intentStr = window.btoa(unescape(encodeURIComponent(JSON.stringify(intent)))).replace(/=/g, "_");

      var href = (e.srcElement || e.target).href;
      if(!!intent._callback == false) {
        // There is no callback so remove any reference to the intent.
        localStorage.removeItem(intent._id);
      }

      if(disposition == "inline") {
        var iframe = document.getElementById("inline");
        iframe.contentWindow.name = intentStr;
        iframe.src= href;
        iframe.style.display = "block";
      }
      else {
        window.name = "";
        window.open(href, intentStr);
      }

      return false;
    };
  };

  var renderAction = function(action, intent) {
    var actionElement = document.createElement("li");
    var actionLink = document.createElement("a");
    var icon = document.createElement("img");
    var domain = document.createElement("span");

    icon.src = action.icon;
    icon.style.float = "left";

    actionLink.href = action.url;
    actionLink.target = "_blank";
    setText(actionLink, action.title);
    attachEventListener(actionLink, "click", launch(intent, action.disposition), false);
    setText(domain, action.domain || "Unknown domain");

    actionElement.style.clear = "both";
    actionElement.style.listStyle = "none";
    actionElement.appendChild(icon);
    actionElement.appendChild(actionLink);
    actionElement.appendChild(domain);

    return actionElement;
  };
})();
<commit_msg>Fixes #147 - remove the click handler for list.html<commit_after>/*
   Copyright 2011 Google Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

var IntentController = new (function() {

  var intent;

  var setText = function(obj, text) {
    obj.appendChild(document.createTextNode(text));
  };

  this.setIntent = function(i) {
    intent = i;
  }

  this.getIntent = function() {
    return intent;
  }

  this.renderActionContainer = function (action, root) {
    var header = document.createElement("h2");
    setText(header, action.key);
    var collection = document.createElement("ul");

    root.appendChild(header);
    root.appendChild(collection);

    return collection;
  };

  this.renderActions = function(actions, intent, root) {
    root = root || document.getElementById("actions");
    var action;
    for(var i = 0; action = actions[i]; i++) {
      var actionElement = renderAction(action, intent);
      root.appendChild(actionElement);
    }
  };

  var launch = function(intent, disposition) {
    return function(e) {
      if(!!e.preventDefault)
        e.preventDefault();
      else
        e.returnValue = false;

      var intentStr = window.btoa(unescape(encodeURIComponent(JSON.stringify(intent)))).replace(/=/g, "_");

      var href = (e.srcElement || e.target).href;
      if(!!intent && !!intent._callback == false) {
        // There is no callback so remove any reference to the intent.
        localStorage.removeItem(intent._id);
      }

      if(disposition == "inline") {
        var iframe = document.getElementById("inline");
        iframe.contentWindow.name = intentStr;
        iframe.src= href;
        iframe.style.display = "block";
      }
      else {
        window.name = "";
        window.open(href, intentStr);
      }

      return false;
    };
  };

  var renderAction = function(action, intent) {
    var actionElement = document.createElement("li");
    var actionLink = document.createElement("a");
    var icon = document.createElement("img");
    var domain = document.createElement("span");

    icon.src = action.icon;
    icon.style.float = "left";

    actionLink.href = action.url;
    actionLink.target = "_blank";
    setText(actionLink, action.title);

    if(!!intent)
      attachEventListener(actionLink, "click", launch(intent, action.disposition), false);

    setText(domain, action.domain || "Unknown domain");

    actionElement.style.clear = "both";
    actionElement.style.listStyle = "none";
    actionElement.appendChild(icon);
    actionElement.appendChild(actionLink);
    actionElement.appendChild(domain);

    return actionElement;
  };
})();
<|endoftext|>


<commit_before>Object.init = function() {};
Object.result = function() {};
Object.step = function() {};
Object.next = function() {};
Object.value;
Object.done;
var transducers = {};
transducers = {};
transducers.reduced = function() {};
transducers.isReduced = function() {};
transducers.comp = function() {};
transducers.complement = function() {};
transducers.map = function() {};
transducers.filter = function() {};
transducers.remove = function() {};
transducers.keep = function() {};
transducers.keepIndexed = function() {};
transducers.cat = function() {};
transducers.mapcat = function() {};
transducers.transduce = function() {};
transducers.reduce = function() {};
transducers.take = function() {};
transducers.takeWhile = function() {};
transducers.takeNth = function() {};
transducers.drop = function() {};
transducers.dropWhile = function() {};
transducers.partitionBy = function() {};
transducers.partitionAll = function() {};
transducers.into = function() {};
transducers.completing = function() {};
transducers.toFn = function() {};
transducers.wrap = function() {};
transducers.first = function() {};
transducers.ensureReduced = function() {};
transducers.unreduced = function() {};

<commit_msg>fix amd externs<commit_after>Object.init = function() {};
Object.result = function() {};
Object.step = function() {};
Object.next = function() {};
Object.value;
Object.done;
var define = function() {};
var transducers = {};
transducers.reduced = function() {};
transducers.isReduced = function() {};
transducers.comp = function() {};
transducers.complement = function() {};
transducers.map = function() {};
transducers.filter = function() {};
transducers.remove = function() {};
transducers.keep = function() {};
transducers.keepIndexed = function() {};
transducers.cat = function() {};
transducers.mapcat = function() {};
transducers.transduce = function() {};
transducers.reduce = function() {};
transducers.take = function() {};
transducers.takeWhile = function() {};
transducers.takeNth = function() {};
transducers.drop = function() {};
transducers.dropWhile = function() {};
transducers.partitionBy = function() {};
transducers.partitionAll = function() {};
transducers.into = function() {};
transducers.completing = function() {};
transducers.toFn = function() {};
transducers.wrap = function() {};
transducers.first = function() {};
transducers.ensureReduced = function() {};
transducers.unreduced = function() {};

<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

const data = [
  { x: 100, y: 200, z: 200 },
  { x: 120, y: 100, z: 260 },
  { x: 170, y: 300, z: 400 },
  { x: 140, y: 250, z: 280 },
  { x: 150, y: 400, z: 500 },
  { x: 110, y: 280, z: 200 },
];

export default class Example extends PureComponent {
  static demoUrl = 'https://codesandbox.io/s/simple-line-chart-kec3v';

  render() {
    return (
      <ResponsiveContainer width="100%" height="100%">
        <ScatterChart
          width={400}
          height={400}
          margin={{
            top: 20,
            right: 20,
            bottom: 20,
            left: 20,
          }}
        >
          <CartesianGrid />
          <XAxis type="number" dataKey="x" name="stature" unit="cm" />
          <YAxis type="number" dataKey="y" name="weight" unit="kg" />
          <Tooltip cursor={{ strokeDasharray: '3 3' }} />
          <Scatter name="A school" data={data} fill="#8884d8" />
        </ScatterChart>
      </ResponsiveContainer>
    );
  }
}
<commit_msg>Fix SimpleScatterChart Codesandbox link<commit_after>import React, { PureComponent } from 'react';
import { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

const data = [
  { x: 100, y: 200, z: 200 },
  { x: 120, y: 100, z: 260 },
  { x: 170, y: 300, z: 400 },
  { x: 140, y: 250, z: 280 },
  { x: 150, y: 400, z: 500 },
  { x: 110, y: 280, z: 200 },
];

export default class Example extends PureComponent {
  static demoUrl = 'https://codesandbox.io/s/simple-scatter-chart-vj65m';

  render() {
    return (
      <ResponsiveContainer width="100%" height="100%">
        <ScatterChart
          width={400}
          height={400}
          margin={{
            top: 20,
            right: 20,
            bottom: 20,
            left: 20,
          }}
        >
          <CartesianGrid />
          <XAxis type="number" dataKey="x" name="stature" unit="cm" />
          <YAxis type="number" dataKey="y" name="weight" unit="kg" />
          <Tooltip cursor={{ strokeDasharray: '3 3' }} />
          <Scatter name="A school" data={data} fill="#8884d8" />
        </ScatterChart>
      </ResponsiveContainer>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * @file Client logic for the ethtaint web interface.
 * @module web/client
 */

(() => {
  'use strict'

  // Constants
  const portIo = 7403

  $(() => {
    // State
    let tracing = false

    // Connect to server
    const socket = io.connect('http://localhost:' + portIo)

    // Counts
    let tainted = 0
    let traced = 0
    let txs = 0

    // Elements
    const taintedEl = document.getElementById('Tainted')
    const tracedEl = document.getElementById('Traced')
    const txsEl = document.getElementById('Txs')
    const listEl = document.getElementById('TaintedList')
    const sourceEl = document.getElementById('Source')
    const traceEl = document.getElementById('Trace')
    const stopEl = document.getElementById('Stop')

    // Stopped
    function stopped () {
      sourceEl.disabled = false
      traceEl.disabled = false
      stopEl.disabled = true
    }

    // Started
    function started () {
      sourceEl.disabled = true
      traceEl.disabled = true
      stopEl.disabled = false
    }

    // Click Trace
    traceEl.onclick = function startTrace () {
      tracing = true
      started()
      taintedEl.innerText = '1'
      tracedEl.innerText = ''
      txsEl.innerText = ''
      $(listEl).empty()
      const sourceHex = sourceEl.value
      const sourceHexLower = sourceHex.toLowerCase()
      $('
' +
        sourceHexLower + '
')
        .appendTo(listEl)
      socket.emit('trace', sourceHex)
    }

    // Click Stop
    stopEl.onclick = function stopTrace () {
      socket.emit('stop')
      tracing = false
      stopped()
    }

    // Found tainted address
    socket.on('taint', address => {
      tainted++
      taintedEl.innerText = tainted.toString()
      $('
' +
        address + '
')
        .appendTo(listEl)
    })

    // Traced address
    socket.on('tracedAddress', address => {
      traced++
      tracedEl.innerText = traced.toString()
      console.log('Traced ' + address)
      const item = document.getElementById(address)
      if (item) {
        item.className = 'traced'
      }
    })

    // Processed transaction
    socket.on('processedTransaction', () => {
      txs++
      txsEl.innerText = txs.toString()
    })

    // Trace complete
    socket.on('done', () => {
      tracing = false
      stopped()
    })

    // Trace error
    socket.on('fail', message => {
      console.log('Trace error: ' + message)
      stopped()
    })
  })
})()
<commit_msg>Reset counts on new trace in web/client<commit_after>/**
 * @file Client logic for the ethtaint web interface.
 * @module web/client
 */

(() => {
  'use strict'

  // Constants
  const portIo = 7403

  $(() => {
    // State
    let tracing = false

    // Connect to server
    const socket = io.connect('http://localhost:' + portIo)

    // Counts
    let tainted = 0
    let traced = 0
    let txs = 0

    // Elements
    const taintedEl = document.getElementById('Tainted')
    const tracedEl = document.getElementById('Traced')
    const txsEl = document.getElementById('Txs')
    const listEl = document.getElementById('TaintedList')
    const sourceEl = document.getElementById('Source')
    const traceEl = document.getElementById('Trace')
    const stopEl = document.getElementById('Stop')

    // Stopped
    function stopped () {
      sourceEl.disabled = false
      traceEl.disabled = false
      stopEl.disabled = true
    }

    // Started
    function started () {
      sourceEl.disabled = true
      traceEl.disabled = true
      stopEl.disabled = false
    }

    // Click Trace
    traceEl.onclick = function startTrace () {
      tracing = true
      started()
      tainted = 1
      traced = 0
      txs = 0
      taintedEl.innerText = '1'
      tracedEl.innerText = ''
      txsEl.innerText = ''
      $(listEl).empty()
      const sourceHex = sourceEl.value
      const sourceHexLower = sourceHex.toLowerCase()
      $('
' +
        sourceHexLower + '
')
        .appendTo(listEl)
      socket.emit('trace', sourceHex)
    }

    // Click Stop
    stopEl.onclick = function stopTrace () {
      socket.emit('stop')
      tracing = false
      stopped()
    }

    // Found tainted address
    socket.on('taint', address => {
      tainted++
      taintedEl.innerText = tainted.toString()
      $('
' +
        address + '
')
        .appendTo(listEl)
    })

    // Traced address
    socket.on('tracedAddress', address => {
      traced++
      tracedEl.innerText = traced.toString()
      console.log('Traced ' + address)
      const item = document.getElementById(address)
      if (item) {
        item.className = 'traced'
      }
    })

    // Processed transaction
    socket.on('processedTransaction', () => {
      txs++
      txsEl.innerText = txs.toString()
    })

    // Trace complete
    socket.on('done', () => {
      tracing = false
      stopped()
    })

    // Trace error
    socket.on('fail', message => {
      console.log('Trace error: ' + message)
      stopped()
    })
  })
})()
<|endoftext|>


<commit_before>// @flow weak
/*
Description:
  This file is a wrapper for DeviceHive client and device connector logic.
*/

const config = require('config'); // Get configuration file
const async = require('async');
const mongo = require('./lib/mongo');
var hive = null;
var seneca = require('seneca')(); // Create seneca bus connection
var mongodb = new mongo(config.device_config.mongo, function(err, res) {
    if (err) console.log(err);
    //console.log('MONGO STARTED')
});
/*
Here we initialize the device/client object which register the app as a device
and opens channels for device and client connections. As e result we are given
"HiveConnections" object which we use to:
  1) Create client connections to the other service on seneca bus by using the config file.
  2) Subscribe the connector device for the according commands used by the other services
      and direct them to the corresponding seneca bus patterns using again config file.
  3) Subscribe the connector device for native commands for managing subscriptions dedicated to
      other services.
*/
var Device = require('./device.js')(function(err, HiveConnections) {
    hive = HiveConnections;
    seneca.use('./busPlugin', HiveConnections)
        .ready(function(err) {
            if (err) console.log(err)
            seneca.listen();
            async.each(config.device_config.seneca_clients, createClients, function(err, res) {
                if (err) console.log(err)
            });
            async.each(config.device_config.sub_for_comands, subscribeForCommands, function(err, res) {
                if (err) console.log(err)
            });
            subscribeForNative(['connector/subscribe', 'connector/unsubscribe', 'connector/showSubs'], function(err, res) {
                if (err) console.log(err);
                //console.log(res);
            });
            initialNotificationSub(function(err, res) {
                if (err) console.log(err);
                console.log(res);
            });
        });
});

function subscribeAndUpdate(args, callback) {
    hive.client.subscribe(
        function(err, subscription) {
            if (err) callback(err);
            //console.log(subscription);
            mongodb.updateSub({
                Device: args.Device,
                notification: args.notification,
                subID: args.subID,
                subService: args.subService
            }, {
                subID: subscription.id
            }, function(err, res) {
                if (err) callback(err);
            })
            //console.log("SUBSCRIBE DONE")
            subscription.message(function(deviceIds, options) {
                //console.log(options)
                async.each(config.device_config.services_and_sub_paths,
                    function(service, callback) {
                        if (service.service == args.subService) {
                            options.parameters.Device = deviceIds;
                            //console.log(options);
                            seneca.act(service.sub_path, options.parameters, function(err, res) {
                                if (err) callback(err);
                                callback(null);
                            });
                        } else {
                            callback(null);
                        }
                    },
                    function(err, res) {
                        if (err) console.log(err);
                    });
            });
            callback(null);

        }, {
            subscription: {
                deviceIds: args.Device,
                names: args.notification,
                onMessage: args.notification
            }
        }
    );
}

function initialNotificationSub(callback) {
    mongodb.showSubs(function(err, res) {
        if (err) console.error(err)
        else if (res.length == 0)
            callback(null, 'Subscription database is empty! :)');
        else {
            async.each(res, subscribeAndUpdate, function(err, res) {
                if (err) console.log(err);
            })
        }
    });
}

function subscribeForNative(commands, callback) {
    var subcmd = hive.device.subscribe(function(err, res) {
        if (err) callback(err, null);
        console.log('DEVICE SUBSCRIBES TO MASAGES ' + JSON.stringify(res));
        callback(null, res);
    }, {
        names: commands
    });
    subcmd.message(function(cmd) {
        if (cmd.command == 'connector/subscribe') {
            //console.log("DATABASE SUBSCRIBEEE! \n" + JSON.stringify(cmd));
            if (cmd.parameters.hasOwnProperty('deviceID') == true &&
                cmd.parameters.hasOwnProperty('notification') == true &&
                cmd.parameters.hasOwnProperty('service') == true) {
                //console.log("properties are present!")
                addClientSub(cmd, function(err, res) {
                    if (err) cmd.update(err);
                    cmd.update({
                        "command": 'connector/subscribe',
                        "status": "OK",
                        "result": "Subscribe Done!"
                    });
                })
            } else {
                cmd.update({
                    "command": 'connector/subscribe',
                    "status": "ERROR",
                    "result": "Missing deviceID , notification or service argument!"
                })
            }
        } else if (cmd.command == 'connector/showSubs') {
            mongodb.showSubs(function(err, res) {
                if (err)
                    cmd.update({
                        "command": 'connector/showSubs',
                        "status": "Error",
                        "result": "Error!"
                    });
                else {
                    cmd.update({
                        "command": 'connector/showSubs',
                        "status": "OK",
                        "result": res
                    });
                }
            });
        } else {
            //console.log("DATABASE SUBSCRIBEEE! \n" + JSON.stringify(cmd));
            if (cmd.parameters.hasOwnProperty('deviceID') == true &&
                cmd.parameters.hasOwnProperty('service') == true) {
                //console.log("properties are present!")
                removeClientSub(cmd, function(err, res) {
                    if (err) cmd.update(err);
                    cmd.update({
                        "command": 'connector/unsubscribe',
                        "status": "OK",
                        "result": "Unsubscribe Done!"
                    });
                })
            } else {
                cmd.update({
                    "command": 'connector/unsubscribe',
                    "status": "ERROR",
                    "result": "Missing deviceID and service arguments!"
                })
            }
        }
    })
};

function removeClientSub(cmd, callback) {
    async.waterfall([
        async.apply(mongodb.findSub, {
            Device: cmd.parameters.deviceID,
            subService: cmd.parameters.service
        }),
        unsubscribe,
        mongodb.removeSub,
    ], function(err, res) {
        if (err)
            callback({
                "command": 'connector/unsubscribe',
                "status": "ERROR",
                "result": "Can't unsubscribe for device!"
            })
        else {
            callback(null);
        }
    })
}

function unsubscribe(args, callback) {
    //console.log(args);
    hive.client.unsubscribe(args.subID,
        function(err, res) {
            //console.log('UNSUBSCRIBING!');
            //console.log(res)
            if (err) callback(err)
            else callback(null, args)
        })
}

function addClientSub(cmd, callback) {
    //console.log("MAKE CLIENT SUB")
    hive.client.subscribe(
        function(err, subscription) {
            if (err)
                callback({
                    "command": 'connector/subscribe',
                    "status": "ERROR",
                    "result": "Can't subscribe for device!"
                })
            callback(null)
            //console.log(subscription);
            mongodb.addSub({
                Device: cmd.parameters.deviceID,
                notification: cmd.parameters.notification,
                subID: subscription.id,
                subService: cmd.parameters.service
            }, function(err, res) {
                if (err) console.log(err);
            })
            //console.log("SUBSCRIBE DONE")
            subscription.message(function(deviceIds, options) {
                //console.log(options)
                async.each(config.device_config.services_and_sub_paths,
                    function(service, callback) {
                        if (service.service == cmd.parameters.service) {
                            options.parameters.Device = deviceIds;
                            //console.log(options);
                            seneca.act(service.sub_path, options.parameters, function(err, res) {
                                if (err) callback(err);
                                callback(null);
                            });
                        } else {
                            callback(null);
                        }
                    },
                    function(err, res) {
                        if (err) console.log(err);
                    });
            });

        }, {
            subscription: {
                deviceIds: cmd.parameters.deviceID,
                names: cmd.parameters.notification,
                onMessage: cmd.parameters.notification
            }
        }
    );
};

function subscribeForCommands(command, callback) {
    var subcmd = hive.device.subscribe(function(err, res) {
        if (err) callback(err, null);
        console.log('DEVICE SUBSCRIBES TO MASAGES ' + JSON.stringify(res));
        callback(null, res);
    }, {
        names: [command.hive]
    });
    subcmd.message(function(cmd) {
        if (cmd.command == command.hive) {
            //console.log('COMMAND IN CONNECTOR! \n ' + cmd)
            seneca.act(command.seneca_service, cmd.parameters, function(err, result) {
                //console.log('RESULT! \n ' + result);
                if (err) cmd.update({
                    "command": command.hive,
                    "status": "ERROR",
                    "result": {
                        "data": err
                    }
                });
                cmd.update({
                    "command": command.hive,
                    "status": "OK",
                    "result": result
                });
            })
        }
    });
};

function createClients(client, callback) {
    seneca.client(client);
    callback();
}
<commit_msg>changes on commands Device parameter<commit_after>// @flow weak
/*
Description:
  This file is a wrapper for DeviceHive client and device connector logic.
*/

const config = require('config'); // Get configuration file
const async = require('async');
const mongo = require('./lib/mongo');
var hive = null;
var seneca = require('seneca')(); // Create seneca bus connection
var mongodb = new mongo(config.device_config.mongo, function(err, res) {
    if (err) console.log(err);
    //console.log('MONGO STARTED')
});
/*
Here we initialize the device/client object which register the app as a device
and opens channels for device and client connections. As e result we are given
"HiveConnections" object which we use to:
  1) Create client connections to the other service on seneca bus by using the config file.
  2) Subscribe the connector device for the according commands used by the other services
      and direct them to the corresponding seneca bus patterns using again config file.
  3) Subscribe the connector device for native commands for managing subscriptions dedicated to
      other services.
*/
var Device = require('./device.js')(function(err, HiveConnections) {
    hive = HiveConnections;
    seneca.use('./busPlugin', HiveConnections)
        .ready(function(err) {
            if (err) console.log(err)
            seneca.listen();
            async.each(config.device_config.seneca_clients, createClients, function(err, res) {
                if (err) console.log(err)
            });
            async.each(config.device_config.sub_for_comands, subscribeForCommands, function(err, res) {
                if (err) console.log(err)
            });
            subscribeForNative(['connector/subscribe', 'connector/unsubscribe', 'connector/showSubs'], function(err, res) {
                if (err) console.log(err);
                //console.log(res);
            });
            initialNotificationSub(function(err, res) {
                if (err) console.log(err);
                console.log(res);
            });
        });
});

function subscribeAndUpdate(args, callback) {
    hive.client.subscribe(
        function(err, subscription) {
            if (err) callback(err);
            //console.log(subscription);
            mongodb.updateSub({
                Device: args.Device,
                notification: args.notification,
                subID: args.subID,
                subService: args.subService
            }, {
                subID: subscription.id
            }, function(err, res) {
                if (err) callback(err);
            })
            //console.log("SUBSCRIBE DONE")
            subscription.message(function(deviceIds, options) {
                //console.log(options)
                async.each(config.device_config.services_and_sub_paths,
                    function(service, callback) {
                        if (service.service == args.subService) {
                            options.parameters.Device = deviceIds;
                            //console.log(options);
                            seneca.act(service.sub_path, options.parameters, function(err, res) {
                                if (err) callback(err);
                                callback(null);
                            });
                        } else {
                            callback(null);
                        }
                    },
                    function(err, res) {
                        if (err) console.log(err);
                    });
            });
            callback(null);

        }, {
            subscription: {
                deviceIds: args.Device,
                names: args.notification,
                onMessage: args.notification
            }
        }
    );
}

function initialNotificationSub(callback) {
    mongodb.showSubs(function(err, res) {
        if (err) console.error(err)
        else if (res.length == 0)
            callback(null, 'Subscription database is empty! :)');
        else {
            async.each(res, subscribeAndUpdate, function(err, res) {
                if (err) console.log(err);
            })
        }
    });
}

function subscribeForNative(commands, callback) {
    var subcmd = hive.device.subscribe(function(err, res) {
        if (err) callback(err, null);
        console.log('DEVICE SUBSCRIBES TO MASAGES ' + JSON.stringify(res));
        callback(null, res);
    }, {
        names: commands
    });
    subcmd.message(function(cmd) {
        if (cmd.command == 'connector/subscribe') {
            //console.log("DATABASE SUBSCRIBEEE! \n" + JSON.stringify(cmd));
            if (cmd.parameters.hasOwnProperty('Device') == true &&
                cmd.parameters.hasOwnProperty('notification') == true &&
                cmd.parameters.hasOwnProperty('service') == true) {
                //console.log("properties are present!")
                addClientSub(cmd, function(err, res) {
                    if (err) cmd.update(err);
                    cmd.update({
                        "command": 'connector/subscribe',
                        "status": "OK",
                        "result": "Subscribe Done!"
                    });
                })
            } else {
                cmd.update({
                    "command": 'connector/subscribe',
                    "status": "ERROR",
                    "result": "Missing Device , notification or service argument!"
                })
            }
        } else if (cmd.command == 'connector/showSubs') {
            mongodb.showSubs(function(err, res) {
                if (err)
                    cmd.update({
                        "command": 'connector/showSubs',
                        "status": "Error",
                        "result": "Error!"
                    });
                else {
                    cmd.update({
                        "command": 'connector/showSubs',
                        "status": "OK",
                        "result": res
                    });
                }
            });
        } else {
            //console.log("DATABASE SUBSCRIBEEE! \n" + JSON.stringify(cmd));
            if (cmd.parameters.hasOwnProperty('Device') == true &&
                cmd.parameters.hasOwnProperty('service') == true) {
                //console.log("properties are present!")
                removeClientSub(cmd, function(err, res) {
                    if (err) cmd.update(err);
                    cmd.update({
                        "command": 'connector/unsubscribe',
                        "status": "OK",
                        "result": "Unsubscribe Done!"
                    });
                })
            } else {
                cmd.update({
                    "command": 'connector/unsubscribe',
                    "status": "ERROR",
                    "result": "Missing Device and service arguments!"
                })
            }
        }
    })
};

function removeClientSub(cmd, callback) {
    async.waterfall([
        async.apply(mongodb.findSub, {
            Device: cmd.parameters.Device,
            subService: cmd.parameters.service
        }),
        unsubscribe,
        mongodb.removeSub,
    ], function(err, res) {
        if (err)
            callback({
                "command": 'connector/unsubscribe',
                "status": "ERROR",
                "result": "Can't unsubscribe for device!"
            })
        else {
            callback(null);
        }
    })
}

function unsubscribe(args, callback) {
    //console.log(args);
    hive.client.unsubscribe(args.subID,
        function(err, res) {
            //console.log('UNSUBSCRIBING!');
            //console.log(res)
            if (err) callback(err)
            else callback(null, args)
        })
}

function addClientSub(cmd, callback) {
    //console.log("MAKE CLIENT SUB")
    hive.client.subscribe(
        function(err, subscription) {
            if (err)
                callback({
                    "command": 'connector/subscribe',
                    "status": "ERROR",
                    "result": "Can't subscribe for device!"
                })
            callback(null)
            //console.log(subscription);
            mongodb.addSub({
                Device: cmd.parameters.Device,
                notification: cmd.parameters.notification,
                subID: subscription.id,
                subService: cmd.parameters.service
            }, function(err, res) {
                if (err) console.log(err);
            })
            //console.log("SUBSCRIBE DONE")
            subscription.message(function(deviceIds, options) {
                //console.log(options)
                async.each(config.device_config.services_and_sub_paths,
                    function(service, callback) {
                        if (service.service == cmd.parameters.service) {
                            options.parameters.Device = deviceIds;
                            //console.log(options);
                            seneca.act(service.sub_path, options.parameters, function(err, res) {
                                if (err) callback(err);
                                callback(null);
                            });
                        } else {
                            callback(null);
                        }
                    },
                    function(err, res) {
                        if (err) console.log(err);
                    });
            });

        }, {
            subscription: {
                deviceIds: cmd.parameters.Device,
                names: cmd.parameters.notification,
                onMessage: cmd.parameters.notification
            }
        }
    );
};

function subscribeForCommands(command, callback) {
    var subcmd = hive.device.subscribe(function(err, res) {
        if (err) callback(err, null);
        console.log('DEVICE SUBSCRIBES TO MASAGES ' + JSON.stringify(res));
        callback(null, res);
    }, {
        names: [command.hive]
    });
    subcmd.message(function(cmd) {
        if (cmd.command == command.hive) {
            //console.log('COMMAND IN CONNECTOR! \n ' + cmd)
            seneca.act(command.seneca_service, cmd.parameters, function(err, result) {
                //console.log('RESULT! \n ' + result);
                if (err) cmd.update({
                    "command": command.hive,
                    "status": "ERROR",
                    "result": {
                        "data": err
                    }
                });
                cmd.update({
                    "command": command.hive,
                    "status": "OK",
                    "result": result
                });
            })
        }
    });
};

function createClients(client, callback) {
    seneca.client(client);
    callback();
}
<|endoftext|>


<commit_before>import {Socket} from "phoenix"

class TanxApp {

  // TODO: Break this up into multiple classes.

  constructor() {
    this.setupChannel();
    this.setupPlayerList();
    this.setupPlayerControl();
    this.setupArenaControls();
    this.setupArenaAnimation();
  }

  //////////////////////////////////////////////////////////////////////////////
  // CHANNEL CONTROL

  setupChannel() {
    let socket = new Socket("/ws");
    socket.connect()
    this._channel = socket.chan("game", {});

    this._channel.join().receive("ok", chan => {
      this.setupPlayerList();
    });
  }

  pushToChannel(event, payload) {
    if (!payload) payload = {};
    this._channel.push(event, payload);
  }

  onChannelEvent(event, callback) {
    this._channel.on(event, callback);
  }

  //////////////////////////////////////////////////////////////////////////////
  // PLAYER LIST VIEW

  setupPlayerList() {
    // Make sure we get an initial view. Subsequent changes will be broadcasted
    // from the server.
    this.pushToChannel("view_players");

    this.onChannelEvent("view_players", players => {
      this.renderPlayersTable(players.players);
    });
  }

  renderPlayersTable(players) {
    let playerTable = $('#player-rows');
    playerTable.empty();
    if (players.length == 0) {
      playerTable.html('
(No players)
');
    } else {
      players.forEach(player => {
        let row = $('
');
        if (player.is_me) {
          row.addClass('info');
        }
        row.html('' + player.name + '	' + player.kills +
          '	' + player.deaths + '	');
        playerTable.append(row);
      });
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // PLAYER JOINING AND RENAMING CONTROL

  setupPlayerControl() {
    this._hasPlayer = false;

    $('#tanx-join-btn').on('click', () => {
      this.joinPlayer();
    });
    $('#tanx-leave-btn').on('click', () => {
      this.leavePlayer();
    });
    $('#tanx-rename-btn').on('click', () => {
      this.renamePlayer();
    });

    $('#tanx-name-field').on('keypress', (event) => {
      if (event.which == 13) {
        $('#tanx-rename-btn:visible').click();
        $('#tanx-join-btn:visible').click();
      }
    });

    this.leavePlayer();
  }

  joinPlayer() {
    $('#tanx-join-btn').hide();
    $('#tanx-rename-btn').show();
    $('#tanx-leave-btn').show();
    $('#tanx-arena-container').show();

    if (!this._hasPlayer) {
      this._hasPlayer = true;
      this.pushToChannel("join", {name: $('#tanx-name-field').val()});
      this.startArenaAnimation();
    }
  }

  leavePlayer() {
    $('#tanx-join-btn').show();
    $('#tanx-rename-btn').hide();
    $('#tanx-leave-btn').hide();
    $('#tanx-arena-container').hide();

    if (this._hasPlayer) {
      this._hasPlayer = false;
      this.pushToChannel("leave");
    }
  }

  renamePlayer() {
    if (this.hasPlayer()) {
      this.pushToChannel("rename", {name: $('#tanx-name-field').val()});
    }
  }

  hasPlayer() {
    return this._hasPlayer;
  }

  //////////////////////////////////////////////////////////////////////////////
  // ARENA CONTROLS

  setupArenaControls() {
    this._upKey = false;
    this._leftKey = false;
    this._rightKey = false;

    $('#tanx-arena').on('keydown', (event) => {
      this.arenaKeyEvent(event.which, true);
    });
    $('#tanx-arena').on('keyup', (event) => {
      this.arenaKeyEvent(event.which, false);
    });

    $('#tanx-launch-tank-btn').on('click', () => {
      this.launchTank();
    });
    $('#tanx-remove-tank-btn').on('click', () => {
      this.removeTank();
    });
  }

  arenaKeyEvent(which, isDown) {
    switch (which) {
      case 37: // left arrow
      case 74: // J
        if (this._leftKey != isDown) {
          this._leftKey = isDown;
          this.pushToChannel("control_tank", {button: "left", down: isDown})
        }
        break;
      case 39: // right arrow
      case 76: // L
        if (this._rightKey != isDown) {
          this._rightKey = isDown;
          this.pushToChannel("control_tank", {button: "right", down: isDown})
        }
        break;
      case 38: // up arrow
      case 40: // down arrow
      case 73: // I
      case 75: // K
        if (this._upKey != isDown) {
          this._upKey = isDown;
          this.pushToChannel("control_tank", {button: "forward", down: isDown})
        }
        break;
    }
  }

  launchTank() {
    if (this.hasPlayer()) {
      this.pushToChannel("launch_tank", {});
      $('#tanx-arena').focus();
    }
  }

  removeTank() {
    if (this.hasPlayer()) {
      this.pushToChannel("remove_tank", {});
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // ARENA ANIMATION

  setupArenaAnimation() {
    this.NUM_TIMESTAMPS = 10;
    this._timestamps = null;
    this._receivedArena = null;
    this._receivedFrame = false;

    this.onChannelEvent("view_arena", arena => {
      if (this.hasPlayer()) {
        if (this._receivedFrame) {
          this.updateArena(arena);
        } else {
          this._receivedArena = arena;
        }
      }
    });
  }

  startArenaAnimation() {
    this._timestamps = [];
    this.runAnimation();
  }

  runAnimation() {
    this._receivedArena = null;
    this._receivedFrame = false;

    this.pushToChannel("view_arena");

    window.requestAnimationFrame(ignore => {
      if (this.hasPlayer()) {
        if (this._receivedArena) {
          this.updateArena(this._receivedArena);
        } else {
          this._receivedFrame = true;
        }
      }
    })
  }

  updateArena(arena) {
    // Render the frame
    this.renderArena(arena);

    // Update FPS indicator
    if (this._timestamps.push(Date.now()) > this.NUM_TIMESTAMPS) {
      this._timestamps.shift();
    }
    let len = this._timestamps.length - 1
    if (len > 0) {
      let fps = Math.round(1000 * len / (this._timestamps[len] - this._timestamps[0]));
      $('#tanx-fps').text(fps);
    }

    // Update tank launch/remove buttons
    let hasTank = arena.tanks.some(tank => tank.is_me);
    $('#tanx-launch-tank-btn').toggle(!hasTank);
    $('#tanx-remove-tank-btn').toggle(hasTank);

    // Request next frame
    this.runAnimation();
  }

  renderArena(arena) {
    $('#tanx-arena pre').text(JSON.stringify(arena, null, 4));

    if(this.canvas()) {
      var context = this.canvas().getContext("2d");

      // Clear the canvas
      context.clearRect(0, 0, this.canvas().width, this.canvas().height);

      // Draw tanks
      arena.tanks.forEach(tank => {
        this.renderTank(context, tank);
      });

      // Draw missiles
      arena.missiles.forEach(missile => {
        this.renderMissile(context, missile);
      });
    }
  }

  renderTank(context, tank) {
    context.save();

    let tankRect = this.onScreenRect(tank.x, tank.y, tank.radius*2, tank.radius*2);
    let barrelRect = this.onScreenRect(tank.x, tank.y, 1, 0.2);

    context.translate(tankRect.x, tankRect.y);

    context.rotate(tank.heading);

    // TODO: Replace this with some nice graphics
    if(tank.is_me) {
      context.fillStyle = "#0000FF";
    } else {
      context.fillStyle = "#FF0000";
    }
    context.fillRect(-tankRect.width/2, -tankRect.height/2, tankRect.width, tankRect.height);
    context.fillRect(0, -barrelRect.height/2, barrelRect.width, barrelRect.height)

    context.restore();
  }

  renderMissile(context, missile) {
    context.save();

    let missileRect = this.onScreenRect(missile.x, missile.y, 0.2, 0.2);
    context.translate(missileRect.x, missileRect.y);

    context.rotate(missile.heading);

    // TODO: Replace this with some nice graphics
    context.fillStyle = "#00FF00";
    context.fillRect(-missileRect.width/2, -missileRect.height/2, missileRect.width, missileRect.height);

    context.restore();
  }

  canvas() {
    return $('#tanx-arena canvas').get(0);
  }

  onScreenPoint(x, y) {
    let offset = this.canvas().width / 2;
    let scaleFactor = 10; // TODO: This should be calculated with: offset / arena.radius

    let screenX = (x * scaleFactor) + offset;
    let screenY = (y * scaleFactor) + offset;
    return {x: screenX, y: screenY};
  }

  onScreenRect(x, y, width, height) {
    let scaleFactor = 10; // TODO: This should be calculated with: offset / arena.radius

    let screenPoint = this.onScreenPoint(x, y);
    let screenWidth = width * scaleFactor;
    let screenHeight = height * scaleFactor;
    return {x: screenPoint.x, y: screenPoint.y, width: screenWidth, height: screenHeight};
  }

}

let App = new TanxApp();
window.Tanx = App;

export default App;
<commit_msg>Added names above enemy tanks on the canvas.<commit_after>import {Socket} from "phoenix"

class TanxApp {

  // TODO: Break this up into multiple classes.

  constructor() {
    this.setupChannel();
    this.setupPlayerList();
    this.setupPlayerControl();
    this.setupArenaControls();
    this.setupArenaAnimation();
  }

  //////////////////////////////////////////////////////////////////////////////
  // CHANNEL CONTROL

  setupChannel() {
    let socket = new Socket("/ws");
    socket.connect()
    this._channel = socket.chan("game", {});

    this._channel.join().receive("ok", chan => {
      this.setupPlayerList();
    });
  }

  pushToChannel(event, payload) {
    if (!payload) payload = {};
    this._channel.push(event, payload);
  }

  onChannelEvent(event, callback) {
    this._channel.on(event, callback);
  }

  //////////////////////////////////////////////////////////////////////////////
  // PLAYER LIST VIEW

  setupPlayerList() {
    // Make sure we get an initial view. Subsequent changes will be broadcasted
    // from the server.
    this.pushToChannel("view_players");

    this.onChannelEvent("view_players", players => {
      this.renderPlayersTable(players.players);
    });
  }

  renderPlayersTable(players) {
    let playerTable = $('#player-rows');
    playerTable.empty();
    if (players.length == 0) {
      playerTable.html('
(No players)
');
    } else {
      players.forEach(player => {
        let row = $('
');
        if (player.is_me) {
          row.addClass('info');
        }
        row.html('' + player.name + '	' + player.kills +
          '	' + player.deaths + '	');
        playerTable.append(row);
      });
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // PLAYER JOINING AND RENAMING CONTROL

  setupPlayerControl() {
    this._hasPlayer = false;

    $('#tanx-join-btn').on('click', () => {
      this.joinPlayer();
    });
    $('#tanx-leave-btn').on('click', () => {
      this.leavePlayer();
    });
    $('#tanx-rename-btn').on('click', () => {
      this.renamePlayer();
    });

    $('#tanx-name-field').on('keypress', (event) => {
      if (event.which == 13) {
        $('#tanx-rename-btn:visible').click();
        $('#tanx-join-btn:visible').click();
      }
    });

    this.leavePlayer();
  }

  joinPlayer() {
    $('#tanx-join-btn').hide();
    $('#tanx-rename-btn').show();
    $('#tanx-leave-btn').show();
    $('#tanx-arena-container').show();

    if (!this._hasPlayer) {
      this._hasPlayer = true;
      this.pushToChannel("join", {name: $('#tanx-name-field').val()});
      this.startArenaAnimation();
    }
  }

  leavePlayer() {
    $('#tanx-join-btn').show();
    $('#tanx-rename-btn').hide();
    $('#tanx-leave-btn').hide();
    $('#tanx-arena-container').hide();

    if (this._hasPlayer) {
      this._hasPlayer = false;
      this.pushToChannel("leave");
    }
  }

  renamePlayer() {
    if (this.hasPlayer()) {
      this.pushToChannel("rename", {name: $('#tanx-name-field').val()});
    }
  }

  hasPlayer() {
    return this._hasPlayer;
  }

  //////////////////////////////////////////////////////////////////////////////
  // ARENA CONTROLS

  setupArenaControls() {
    this._upKey = false;
    this._leftKey = false;
    this._rightKey = false;

    $('#tanx-arena').on('keydown', (event) => {
      this.arenaKeyEvent(event.which, true);
    });
    $('#tanx-arena').on('keyup', (event) => {
      this.arenaKeyEvent(event.which, false);
    });

    $('#tanx-launch-tank-btn').on('click', () => {
      this.launchTank();
    });
    $('#tanx-remove-tank-btn').on('click', () => {
      this.removeTank();
    });
  }

  arenaKeyEvent(which, isDown) {
    switch (which) {
      case 37: // left arrow
      case 74: // J
        if (this._leftKey != isDown) {
          this._leftKey = isDown;
          this.pushToChannel("control_tank", {button: "left", down: isDown})
        }
        break;
      case 39: // right arrow
      case 76: // L
        if (this._rightKey != isDown) {
          this._rightKey = isDown;
          this.pushToChannel("control_tank", {button: "right", down: isDown})
        }
        break;
      case 38: // up arrow
      case 40: // down arrow
      case 73: // I
      case 75: // K
        if (this._upKey != isDown) {
          this._upKey = isDown;
          this.pushToChannel("control_tank", {button: "forward", down: isDown})
        }
        break;
    }
  }

  launchTank() {
    if (this.hasPlayer()) {
      this.pushToChannel("launch_tank", {});
      $('#tanx-arena').focus();
    }
  }

  removeTank() {
    if (this.hasPlayer()) {
      this.pushToChannel("remove_tank", {});
    }
  }

  //////////////////////////////////////////////////////////////////////////////
  // ARENA ANIMATION

  setupArenaAnimation() {
    this.NUM_TIMESTAMPS = 10;
    this._timestamps = null;
    this._receivedArena = null;
    this._receivedFrame = false;

    this.onChannelEvent("view_arena", arena => {
      if (this.hasPlayer()) {
        if (this._receivedFrame) {
          this.updateArena(arena);
        } else {
          this._receivedArena = arena;
        }
      }
    });
  }

  startArenaAnimation() {
    this._timestamps = [];
    this.runAnimation();
  }

  runAnimation() {
    this._receivedArena = null;
    this._receivedFrame = false;

    this.pushToChannel("view_arena");

    window.requestAnimationFrame(ignore => {
      if (this.hasPlayer()) {
        if (this._receivedArena) {
          this.updateArena(this._receivedArena);
        } else {
          this._receivedFrame = true;
        }
      }
    })
  }

  updateArena(arena) {
    // Render the frame
    this.renderArena(arena);

    // Update FPS indicator
    if (this._timestamps.push(Date.now()) > this.NUM_TIMESTAMPS) {
      this._timestamps.shift();
    }
    let len = this._timestamps.length - 1
    if (len > 0) {
      let fps = Math.round(1000 * len / (this._timestamps[len] - this._timestamps[0]));
      $('#tanx-fps').text(fps);
    }

    // Update tank launch/remove buttons
    let hasTank = arena.tanks.some(tank => tank.is_me);
    $('#tanx-launch-tank-btn').toggle(!hasTank);
    $('#tanx-remove-tank-btn').toggle(hasTank);

    // Request next frame
    this.runAnimation();
  }

  renderArena(arena) {
    $('#tanx-arena pre').text(JSON.stringify(arena, null, 4));

    if(this.canvas()) {
      var context = this.canvas().getContext("2d");

      // Clear the canvas
      context.clearRect(0, 0, this.canvas().width, this.canvas().height);

      // Draw tanks
      arena.tanks.forEach(tank => {
        this.renderTank(context, tank);
      });

      // Draw missiles
      arena.missiles.forEach(missile => {
        this.renderMissile(context, missile);
      });
    }
  }

  renderTank(context, tank) {
    context.save();

    let tankRect = this.onScreenRect(tank.x, tank.y, tank.radius*2, tank.radius*2);
    let barrelRect = this.onScreenRect(tank.x, tank.y, 1, 0.2);

    context.translate(tankRect.x, tankRect.y);

    if(tank.is_me) {
      // my tank color
      context.fillStyle = "#0000FF";
    } else {
      // Add names above enemies
      context.textAlign = "center";
      context.fillText(tank.name, 0, -11);

      // enemy tank color
      context.fillStyle = "#FF0000";
    }

    context.rotate(tank.heading);

    // TODO: Replace this with some nice graphics
    context.fillRect(-tankRect.width/2, -tankRect.height/2, tankRect.width, tankRect.height);
    context.fillRect(0, -barrelRect.height/2, barrelRect.width, barrelRect.height)

    context.restore();
  }

  renderMissile(context, missile) {
    context.save();

    let missileRect = this.onScreenRect(missile.x, missile.y, 0.2, 0.2);
    context.translate(missileRect.x, missileRect.y);

    context.rotate(missile.heading);

    // TODO: Replace this with some nice graphics
    context.fillStyle = "#00FF00";
    context.fillRect(-missileRect.width/2, -missileRect.height/2, missileRect.width, missileRect.height);

    context.restore();
  }

  canvas() {
    return $('#tanx-arena canvas').get(0);
  }

  onScreenPoint(x, y) {
    let offset = this.canvas().width / 2;
    let scaleFactor = 10; // TODO: This should be calculated with: offset / arena.radius

    let screenX = (x * scaleFactor) + offset;
    let screenY = (y * scaleFactor) + offset;
    return {x: screenX, y: screenY};
  }

  onScreenRect(x, y, width, height) {
    let scaleFactor = 10; // TODO: This should be calculated with: offset / arena.radius

    let screenPoint = this.onScreenPoint(x, y);
    let screenWidth = width * scaleFactor;
    let screenHeight = height * scaleFactor;
    return {x: screenPoint.x, y: screenPoint.y, width: screenWidth, height: screenHeight};
  }

}

let App = new TanxApp();
window.Tanx = App;

export default App;
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

let [,, src] = process.argv;
let transform = eval(src) || (line => line);
let env = Object.create(null);

require('readline')
    .createInterface({
        input: process.stdin
    })
    .on('line', line => {
        let ret = transform(line, env);
        if (ret != null) {
            console.log(ret);
        }
    });
<commit_msg>Support columns<commit_after>#!/usr/bin/env node
'use strict';

let [,, src] = process.argv;
let transform = eval(src) || (line => line);
let env = Object.create(null);

require('readline')
    .createInterface({
        input: process.stdin
    })
    .on('line', line => {
        let columns = line.match(/('(\\'|[^'])*'|"(\\"|[^"])*"|\/(\\\/|[^\/])*\/|(\\ |[^ ])+|[\w-]+)/g) || [];
        let ret = transform(line, columns, env);
        if (ret != null) {
            console.log(ret);
        }
    });
<|endoftext|>


<commit_before>import {UserAccount} from '../../src/dashboard-child-routes/user-account';
import {AuthStub, HttpMock, AppStateStub, RouterStub} from './commons';
import {App} from '../../src/app';
import {Validator} from 'aurelia-validation';

class VCMock {
  createForCurrentScope(validator) {
    return {validateTrigger: null};
  }
}

// class HttpStub extends HttpMock {
//   fetch(url) {
//     console.log(url);
//     return Promise.resolve({
//       json: () => Promise.resolve([{name: 'in the jungle'}])
//     });
//   }
// }

class ValidatorMock extends Validator {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  validateObject(obj, rules) {
    return Promise.resolve([{name: 'john', valid: true}]);
  }
  validateProperty(prop, val, rules) {
    return Promise.resolve({});
  }
}

describe('the UserAccount Module', () => {
  let ua;
  let app;
  let auth;
  //let http;

  beforeEach(() => {
    auth = new AuthStub();
    auth.setToken({sub: 'aowifjawifhiawofjo'});
    app = new App(auth, new HttpMock());
    app.router = new RouterStub();
    app.activate();
    ua = new UserAccount(app, new VCMock(), new ValidatorMock());
    ua.app.appState = new AppStateStub();
    //us.app.appState = new AppStateStub();
    ua.selectedCauses = ['other'];
    ua.selectedWorks = ['other'];
    ua.selectedTalents = ['other'];
    ua.activate();
    ua.user = {name: 'Iddris Elba', userType: 'Charity', _id: '3333333', volTalents: ['childcare', 'other'], volCauses: ['Environmental', 'other'], volWorkPrefs: ['counseling', 'other'], volCauseOther: '', volTalentOther: '', volWorkOther: ''};
  });

  // it('should activate user account', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.activate().then(() => {
  //     done();
  //   });
  // });

  // it('should activate user account with preselected attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.app.auth.setToken({sub: '1'});
  //   ua.activate().then(() => {
  //     done();
  //   });
  // });

  it('should validate property', (done) => {
    ua.validator.validateProperty({}, 'school', 'schoolRules');
    done();
  });

  it('setup volunteer', (done) => {
    ua.app.appState = new AppStateStub();
    ua.setupVolunteer().then(() => {
      done();
    });
  });

  it('checkboxes app.expanded', (done) => {
    document.body.innerHTML = '

';
    ua.app.expanded = true;
    ua.app.showCheckboxes('types');
    expect(ua.app.expanded).toBe(false);
    done();
  });

  it('checkboxes closed', (done) => {
    document.body.innerHTML = '

';
    ua.app.expanded = false;
    ua.app.showCheckboxes('types');
    expect(ua.app.expanded).toBe(true);
    done();
  });

  it('should change other cause type', (done) => {
    //volops.activate();
    ua.selectedCauses = ['other'];
    ua.app.selectPickedChange(ua.user, ua, 'selectedCauses', 'volCauseOther', 'causeOther', true, 'volCauses');
    expect(ua.causeOther).toBe(true);
    expect(ua.user.volCauses).toBe(ua.selectedCauses);
    ua.selectedCauses = ['somethingelse'];
    ua.user.volCauseOther = 'Teststring';
    ua.app.selectPickedChange(ua.user, ua, 'selectedCauses', 'volCauseOther', 'causeOther', true, 'volCauses');
    expect(ua.causeOther).toBe(false);
    expect(ua.user.volCauseOther).toBe('');
    expect(ua.user.volCauses).toBe(ua.selectedCauses);

    done();
  });

  it('should change other work type', (done) => {
    //volops.activate();
    ua.selectedWorks = ['other'];
    ua.app.selectPickedChange(ua.user, ua, 'selectedWorks', 'volWorkOther', 'workOther', true, 'volWorkPrefs');
    expect(ua.workOther).toBe(true);
    expect(ua.user.volWorkPrefs).toBe(ua.selectedWorks);
    ua.selectedWorks = ['somethingelse'];
    ua.user.volWorkPrefs = 'Teststring';
    ua.app.selectPickedChange(ua.user, ua, 'selectedWorks', 'volWorkOther', 'workOther', true, 'volWorkPrefs');
    expect(ua.workOther).toBe(false);
    expect(ua.user.volWorkOther).toBe('');
    expect(ua.user.volWorkPrefs).toBe(ua.selectedWorks);

    done();
  });

  it('should change other talent type', (done) => {
    //volops.activate();
    ua.selectedTalents = ['other'];
    ua.app.selectPickedChange(ua.user, ua, 'selectedTalents', 'volTalentOther', 'talentOther', true, 'volTalents');
    expect(ua.talentOther).toBe(true);
    expect(ua.user.volTalents).toBe(ua.selectedTalents);
    ua.selectedTalents = ['somethingelse'];
    ua.user.volTalentOther = 'Teststring';
    ua.app.selectPickedChange(ua.user, ua, 'selectedTalents', 'volTalentOther', 'talentOther', true, 'volTalents');
    expect(ua.talentOther).toBe(false);
    expect(ua.user.volTalentOther).toBe('');
    expect(ua.user.volTalents).toBe(ua.selectedTalents);

    done();
  });

  it('should set charity', (done) => {
    ua.setCharity();
    done();
  });

  it('should update user', (done) => {
    ua.updateUser();
    done();
  });

  it('should select picked type', (done) => {
    ua.selectPickChange('causes');
    ua.selectPickChange('work');
    ua.selectPickChange('talents');
    done();
  });
  // it('causePicked without attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.activate().then(() => {
  //     ua.causePicked();
  //     done();
  //   });
  // });

  // it('causePicked with attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.app.auth.setToken({sub: '1'});
  //   ua.activate().then(() => {
  //     ua.causePicked();
  //     done();
  //   });
  // });

  // it('workPicked without attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.activate().then(() => {
  //     ua.workPicked();
  //     done();
  //   });
  // });

  // it('workPicked with attributes', (done) => {
  //   ua.app.appState = new AppStateStub();
  //   ua.app.auth.setToken({sub: '1'});
  //   ua.activate().then(() => {
  //     ua.workPicked();
  //     done();
  //   });
  // });

  it('deletes the user', (done) => {
    ua.deleteUser();
    done();
  });
});
<commit_msg>user account tests updated to have 100% coverage<commit_after>import {UserAccount} from '../../src/dashboard-child-routes/user-account';
import {AuthStub, HttpMock, AppStateStub, RouterStub} from './commons';
import {App} from '../../src/app';
import {Validator} from 'aurelia-validation';

class VCMock {
  createForCurrentScope(validator) {
    return {validateTrigger: null};
  }
}

class HttpStub extends HttpMock {
  fetch(url) {
    console.log(url);
    return Promise.resolve({
      json: () => [{name: 'in the jungle'}]
    });
  }
}

class ValidatorMock extends Validator {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  validateObject(obj, rules) {
    return Promise.resolve([{name: 'john', valid: true}]);
  }
  validateProperty(prop, val, rules) {
    return Promise.resolve({});
  }
}

class AppStateMock extends AppStateStub{
  getUser(uid) {
    this.user = {name: 'Iddris Elba', userType: 'Volunteer', _id: '3333333', volTalents: ['childcare'], volCauses: ['Environmental'], volWorkPrefs: ['counseling'], volCauseOther: '', volTalentOther: '', volWorkOther: '', userDetails: 'newUser', isOhafUser: true};

    return new Promise((resolve) => {
      resolve(this.user);
    });
  }
}

describe('the UserAccount Module', () => {
  let ua;
  let app;
  let auth;

  beforeEach(() => {
    auth = new AuthStub();
    auth.setToken({sub: 'aowifjawifhiawofjo'});
    app = new App(auth, new HttpStub());
    app.router = new RouterStub();
    app.activate();
    ua = new UserAccount(app, new VCMock(), new ValidatorMock());
    ua.app.appState = new AppStateStub();
    ua.selectedCauses = [];
    ua.selectedWorks = [];
    ua.selectedTalents = [];
    ua.activate();
    ua.user = {name: 'Iddris Elba', userType: 'Charity', _id: '3333333', volTalents: ['childcare', 'other'], volCauses: ['Environmental', 'other'], volWorkPrefs: ['counseling', 'other'], volCauseOther: '', volTalentOther: '', volWorkOther: ''};
  });

  it('should validate property', (done) => {
    ua.validator.validateProperty({}, 'school', 'schoolRules');
    done();
  });

  it('setup volunteer', (done) => {
    ua.app.appState = new AppStateStub();
    ua.setupVolunteer();
    done();
  });

  it('setup volunteer with other selected works', (done) => {
    let ua2 = new UserAccount(app, new VCMock(), new ValidatorMock());
    ua2.app.appState = new AppStateMock();
    ua2.activate();
    ua2.setupVolunteer();
    done();
  });

  it('checkboxes app.expanded', (done) => {
    document.body.innerHTML = '

';
    ua.app.expanded = true;
    ua.app.showCheckboxes('types');
    expect(ua.app.expanded).toBe(false);
    done();
  });

  it('checkboxes closed', (done) => {
    document.body.innerHTML = '

';
    ua.app.expanded = false;
    ua.app.showCheckboxes('types');
    expect(ua.app.expanded).toBe(true);
    done();
  });

  it('should change other cause type', (done) => {
    //volops.activate();
    ua.selectedCauses = ['other'];
    ua.app.selectPickedChange(ua.user, ua, 'selectedCauses', 'volCauseOther', 'causeOther', true, 'volCauses');
    expect(ua.causeOther).toBe(true);
    expect(ua.user.volCauses).toBe(ua.selectedCauses);
    ua.selectedCauses = ['somethingelse'];
    ua.user.volCauseOther = 'Teststring';
    ua.app.selectPickedChange(ua.user, ua, 'selectedCauses', 'volCauseOther', 'causeOther', true, 'volCauses');
    expect(ua.causeOther).toBe(false);
    expect(ua.user.volCauseOther).toBe('');
    expect(ua.user.volCauses).toBe(ua.selectedCauses);

    done();
  });

  it('should change other work type', (done) => {
    //volops.activate();
    ua.selectedWorks = ['other'];
    ua.app.selectPickedChange(ua.user, ua, 'selectedWorks', 'volWorkOther', 'workOther', true, 'volWorkPrefs');
    expect(ua.workOther).toBe(true);
    expect(ua.user.volWorkPrefs).toBe(ua.selectedWorks);
    ua.selectedWorks = ['somethingelse'];
    ua.user.volWorkPrefs = 'Teststring';
    ua.app.selectPickedChange(ua.user, ua, 'selectedWorks', 'volWorkOther', 'workOther', true, 'volWorkPrefs');
    expect(ua.workOther).toBe(false);
    expect(ua.user.volWorkOther).toBe('');
    expect(ua.user.volWorkPrefs).toBe(ua.selectedWorks);

    done();
  });

  it('should change other talent type', (done) => {
    //volops.activate();
    ua.selectedTalents = ['other'];
    ua.app.selectPickedChange(ua.user, ua, 'selectedTalents', 'volTalentOther', 'talentOther', true, 'volTalents');
    expect(ua.talentOther).toBe(true);
    expect(ua.user.volTalents).toBe(ua.selectedTalents);
    ua.selectedTalents = ['somethingelse'];
    ua.user.volTalentOther = 'Teststring';
    ua.app.selectPickedChange(ua.user, ua, 'selectedTalents', 'volTalentOther', 'talentOther', true, 'volTalents');
    expect(ua.talentOther).toBe(false);
    expect(ua.user.volTalentOther).toBe('');
    expect(ua.user.volTalents).toBe(ua.selectedTalents);

    done();
  });

  it('should set charity', (done) => {
    ua.setCharity();
    done();
  });

  it('should update user', (done) => {
    ua.updateUser();
    done();
  });

  it('should select picked type', (done) => {
    ua.selectPickChange('causes');
    ua.selectPickChange('work');
    ua.selectPickChange('talents');
    done();
  });

  it('should check whether update can submit', (done) => {
    ua.updateCanSubmit([{valid: false}]);
    done();
  });

  it('deletes the user', (done) => {
    ua.deleteUser();
    done();
  });
});
<|endoftext|>