<commit_before>Travis.Controllers.Sidebar = SC.Object.extend({
  cookie: 'sidebar_minimized',

  init: function() {
    Travis.Controllers.Workers.create();
    Travis.Controllers.Jobs.create({ queue: 'builds.config'  });
    Travis.Controllers.Jobs.create({ queue: 'builds.common'  });
    Travis.Controllers.Jobs.create({ queue: 'builds.node_js' });
    Travis.Controllers.Jobs.create({ queue: 'builds.php' });
    Travis.Controllers.Jobs.create({ queue: 'builds.rails' });
    Travis.Controllers.Jobs.create({ queue: 'builds.erlang' });

    $(".slider").click(function() { this.toggle(); }.bind(this));
    if($.cookie(this.cookie) === 'true') { this.minimize(); }
    this.persist();
  },

  toggle: function() {
    this.isMinimized() ? this.maximize() : this.minimize();
    this.persist();
  },

  isMinimized: function() {
    return $('#right').hasClass('minimized');
  },

  minimize: function() {
    $('#right').addClass('minimized');
    $('#main').addClass('maximized');
  },

  maximize: function() {
    $('#right').removeClass('minimized');
    $('#main').removeClass('maximized');
  },

  persist: function() {
    $.cookie(this.cookie, this.isMinimized());
  }
});
<commit_msg>Add Spree queue to the sidebar<commit_after>Travis.Controllers.Sidebar = SC.Object.extend({
  cookie: 'sidebar_minimized',

  init: function() {
    Travis.Controllers.Workers.create();
    Travis.Controllers.Jobs.create({ queue: 'builds.config'  });
    Travis.Controllers.Jobs.create({ queue: 'builds.common'  });
    Travis.Controllers.Jobs.create({ queue: 'builds.node_js' });
    Travis.Controllers.Jobs.create({ queue: 'builds.php' });
    Travis.Controllers.Jobs.create({ queue: 'builds.rails' });
    Travis.Controllers.Jobs.create({ queue: 'builds.erlang' });
    Travis.Controllers.Jobs.create({ queue: 'builds.spree' });

    $(".slider").click(function() { this.toggle(); }.bind(this));
    if($.cookie(this.cookie) === 'true') { this.minimize(); }
    this.persist();
  },

  toggle: function() {
    this.isMinimized() ? this.maximize() : this.minimize();
    this.persist();
  },

  isMinimized: function() {
    return $('#right').hasClass('minimized');
  },

  minimize: function() {
    $('#right').addClass('minimized');
    $('#main').addClass('maximized');
  },

  maximize: function() {
    $('#right').removeClass('minimized');
    $('#main').removeClass('maximized');
  },

  persist: function() {
    $.cookie(this.cookie, this.isMinimized());
  }
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require canned_meat/bootstrap-sprockets
//= require_tree .
<commit_msg>Add necessary js includes.<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require canned_meat/bootstrap-sprockets
//= require_tree .
<|endoftext|>


<commit_before>APP.controllers.application = (function() {

  function init() {

    APP.components.mainNavigation.init();
    APP.components.stream.init();
    APP.components.notificatonCenter.init();

    FastClick.attach(document.body);

    window.cookieconsent_options = {
      "message":"Diese Website verwendet Cookies. Indem Sie weiter auf dieser Website navigieren, stimmen Sie unserer Verwendung von Cookies zu.",
      "dismiss":"OK!","learnMore":"Mehr Information",
      "link":"https://www.imgraetzl.at/info/datenschutz",
      "theme": false
    };

    // Set Screen Mode Class
    enquire
        .register("screen and (max-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('mob');
            },
            match : function() {
              $('body').addClass('mob');
              $('body').removeClass('desk');
            }
        })
        .register("screen and (min-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('desk');
            },
            match : function() {
              $('body').addClass('desk');
              $('body').removeClass('mob');
            }
        });

    // TODO: this is a hack! stuff should come from DB
    function injectSponsorCard() {

      var $markup = $('

');

      if(APP.utils.URLendsWith('/stuwerviertel') && APP.utils.isLoggedIn()) {
        $('.card-grid .cardBox').eq(2).after($markup);
      }
      if(APP.utils.URLendsWith('/stuwerviertel') && !APP.utils.isLoggedIn()) {
        $('main').append($markup);
      }
    }

    // Conversion Tracking
    if (window.location.hostname == 'www.imgraetzl.at') {
      $(document).ready(function() {
        if ($("#flash .notice").exists()) {
          if ( $("#flash .notice").text().indexOf('Super, du bist nun registriert!') >= 0 ){
            gtag('event', 'sign_up', {'event_category': 'Registration'}); // GA
            gtag('event', 'conversion', {'send_to': 'AW-807401138/zBwECJ738IABELLt_4AD'}); // G-AW
            fbq('track', 'CompleteRegistration'); // FB
          }
        }
      });
    }

  }

  // ---------------------------------------------------------------------- Returns

  return {
    init: init
  }

})();
<commit_msg>unterstuetzer conversion<commit_after>APP.controllers.application = (function() {

  function init() {

    APP.components.mainNavigation.init();
    APP.components.stream.init();
    APP.components.notificatonCenter.init();

    FastClick.attach(document.body);

    window.cookieconsent_options = {
      "message":"Diese Website verwendet Cookies. Indem Sie weiter auf dieser Website navigieren, stimmen Sie unserer Verwendung von Cookies zu.",
      "dismiss":"OK!","learnMore":"Mehr Information",
      "link":"https://www.imgraetzl.at/info/datenschutz",
      "theme": false
    };

    // Set Screen Mode Class
    enquire
        .register("screen and (max-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('mob');
            },
            match : function() {
              $('body').addClass('mob');
              $('body').removeClass('desk');
            }
        })
        .register("screen and (min-width:" + APP.config.majorBreakpoints.medium + "px)", {
            deferSetup : true,
            setup : function() {
              $('body').addClass('desk');
            },
            match : function() {
              $('body').addClass('desk');
              $('body').removeClass('mob');
            }
        });

    // TODO: this is a hack! stuff should come from DB
    function injectSponsorCard() {

      var $markup = $('

');

      if(APP.utils.URLendsWith('/stuwerviertel') && APP.utils.isLoggedIn()) {
        $('.card-grid .cardBox').eq(2).after($markup);
      }
      if(APP.utils.URLendsWith('/stuwerviertel') && !APP.utils.isLoggedIn()) {
        $('main').append($markup);
      }
    }

    // Conversion Tracking
    if (window.location.hostname == 'www.imgraetzl.at') {
      $(document).ready(function() {
        if ($("#flash .notice").exists()) {

          // Registration
          if ( $("#flash .notice").text().indexOf('Super, du bist nun registriert!') >= 0 ){
            gtag('event', 'sign_up', {'event_category': 'Registration'}); // GA
            gtag('event', 'conversion', {'send_to': 'AW-807401138/zBwECJ738IABELLt_4AD'}); // G-AW
            fbq('track', 'CompleteRegistration'); // FB
          }

          // SignUp Unterstützer-Team
          if ( $("#flash .notice").text().indexOf('Deine Beitrittsanfrage wurde abgeschickt!') >= 0 && document.referrer.indexOf('unterstuetzer-team') >= 0 ){
            fbq('track', 'UnterstuetzerSignUp'); // FB
          }

        }
      });
    }

  }

  // ---------------------------------------------------------------------- Returns

  return {
    init: init
  }

})();
<|endoftext|>


<commit_before>/* global NAF */
var ReservedDataType = { Update: 'u', UpdateMulti: 'um', Remove: 'r' };

class NetworkConnection {

  constructor(networkEntities) {
    this.entities = networkEntities;
    this.setupDefaultDataSubscriptions();

    this.connectedClients = {};
    this.activeDataChannels = {};
  }

  setNetworkAdapter(adapter) {
    this.adapter = adapter;
  }

  setupDefaultDataSubscriptions() {
    this.dataChannelSubs = {};

    this.dataChannelSubs[ReservedDataType.Update]
        = this.entities.updateEntity.bind(this.entities);

    this.dataChannelSubs[ReservedDataType.UpdateMulti]
        = this.entities.updateEntityMulti.bind(this.entities);

    this.dataChannelSubs[ReservedDataType.Remove]
        = this.entities.removeRemoteEntity.bind(this.entities);
  }

  connect(serverUrl, appName, roomName, enableAudio = false) {
    NAF.app = appName;
    NAF.room = roomName;

    this.adapter.setServerUrl(serverUrl);
    this.adapter.setApp(appName);
    this.adapter.setRoom(roomName);

    var webrtcOptions = {
      audio: enableAudio,
      video: false,
      datachannel: true
    };
    this.adapter.setWebRtcOptions(webrtcOptions);

    this.adapter.setServerConnectListeners(
      this.connectSuccess.bind(this),
      this.connectFailure.bind(this)
    );
    this.adapter.setDataChannelListeners(
      this.dataChannelOpen.bind(this),
      this.dataChannelClosed.bind(this),
      this.receivedData.bind(this)
    );
    this.adapter.setRoomOccupantListener(this.occupantsReceived.bind(this));

    return this.adapter.connect();
  }

  onConnect(callback) {
    this.onConnectCallback = callback;

    if (this.isConnected()) {
      callback();
    } else {
      document.body.addEventListener('connected', callback, false);
    }
  }

  connectSuccess(clientId) {
    NAF.log.write('Networked-Aframe Client ID:', clientId);
    NAF.clientId = clientId;

    var evt = new CustomEvent('connected', {'detail': { clientId: clientId }});
    document.body.dispatchEvent(evt);
  }

  connectFailure(errorCode, message) {
    NAF.log.error(errorCode, "failure to connect");
  }

  occupantsReceived(occupantList) {
    var prevConnectedClients = Object.assign({}, this.connectedClients);
    this.connectedClients = occupantList;
    this.checkForDisconnectingClients(prevConnectedClients, occupantList);
    this.checkForConnectingClients(occupantList);
  }

  checkForDisconnectingClients(oldOccupantList, newOccupantList) {
    for (var id in oldOccupantList) {
      var clientFound = newOccupantList[id];
      if (!clientFound) {
        NAF.log.write('Closing stream to ', id);
        this.adapter.closeStreamConnection(id);
      }
    }
  }

  // Some adapters will handle this internally
  checkForConnectingClients(occupantList) {
    for (var id in occupantList) {
      var startConnection = this.isNewClient(id) && this.adapter.shouldStartConnectionTo(occupantList[id]);
      if (startConnection) {
        NAF.log.write('Opening datachannel to ', id);
        this.adapter.startStreamConnection(id);
      }
    }
  }

  getConnectedClients() {
    return this.connectedClients;
  }

  isConnected() {
    return !!NAF.clientId;
  }

  isMineAndConnected(clientId) {
    return this.isConnected() && NAF.clientId === clientId;
  }

  isNewClient(clientId) {
    return !this.isConnectedTo(clientId);
  }

  isConnectedTo(clientId) {
    return this.adapter.getConnectStatus(clientId) === NAF.adapters.IS_CONNECTED;
  }

  dataChannelOpen(clientId) {
    NAF.log.write('Opened data channel from ' + clientId);
    this.activeDataChannels[clientId] = true;
    this.entities.completeSync(clientId, true);

    var evt = new CustomEvent('clientConnected', {detail: {clientId: clientId}});
    document.body.dispatchEvent(evt);
  }

  dataChannelClosed(clientId) {
    NAF.log.write('Closed data channel from ' + clientId);
    this.activeDataChannels[clientId] = false;
    this.entities.removeEntitiesOfClient(clientId);

    var evt = new CustomEvent('clientDisconnected', {detail: {clientId: clientId}});
    document.body.dispatchEvent(evt);
  }

  hasActiveDataChannel(clientId) {
    return !!(this.activeDataChannels[clientId] && this.activeDataChannels[clientId]);
  }

  broadcastData(dataType, data) {
    this.adapter.broadcastData(dataType, data);
  }

  broadcastDataGuaranteed(dataType, data) {
    this.adapter.broadcastDataGuaranteed(dataType, data);
  }

  sendData(toClientId, dataType, data, guaranteed) {
    if (this.hasActiveDataChannel(toClientId)) {
      if (guaranteed) {
        this.adapter.sendDataGuaranteed(toClientId, dataType, data);
      } else {
        this.adapter.sendData(toClientId, dataType, data);
      }
    } else {
      // console.error("NOT-CONNECTED", "not connected to " + toClient);
    }
  }

  sendDataGuaranteed(toClientId, dataType, data) {
    this.sendData(toClientId, dataType, data, true);
  }

  subscribeToDataChannel(dataType, callback) {
    if (this.isReservedDataType(dataType)) {
      NAF.log.error('NetworkConnection@subscribeToDataChannel: ' + dataType + ' is a reserved dataType. Choose another');
      return;
    }
    this.dataChannelSubs[dataType] = callback;
  }

  unsubscribeToDataChannel(dataType) {
    if (this.isReservedDataType(dataType)) {
      NAF.log.error('NetworkConnection@unsubscribeToDataChannel: ' + dataType + ' is a reserved dataType. Choose another');
      return;
    }
    delete this.dataChannelSubs[dataType];
  }

  isReservedDataType(dataType) {
    return dataType == ReservedDataType.Update
        || dataType == ReservedDataType.Remove;
  }

  receivedData(fromClientId, dataType, data, source) {
    if (this.dataChannelSubs[dataType]) {
      this.dataChannelSubs[dataType](fromClientId, dataType, data, source);
    } else {
      NAF.log.write('NetworkConnection@receivedData: ' + dataType + ' has not been subscribed to yet. Call subscribeToDataChannel()');
    }
  }

  getServerTime() {
    return this.adapter.getServerTime();
  }

  disconnect() {
    this.entities.removeRemoteEntities();
    this.adapter.disconnect();

    NAF.app = '';
    NAF.room = '';
    NAF.clientId = '';
    this.connectedClients = {};
    this.activeDataChannels = {};
    this.adapter = null;

    this.setupDefaultDataSubscriptions();

    document.body.removeEventListener('connected', this.onConnectCallback);
  }
}

module.exports = NetworkConnection;
<commit_msg>simplify hasActiveDataChannel condition<commit_after>/* global NAF */
var ReservedDataType = { Update: 'u', UpdateMulti: 'um', Remove: 'r' };

class NetworkConnection {

  constructor(networkEntities) {
    this.entities = networkEntities;
    this.setupDefaultDataSubscriptions();

    this.connectedClients = {};
    this.activeDataChannels = {};
  }

  setNetworkAdapter(adapter) {
    this.adapter = adapter;
  }

  setupDefaultDataSubscriptions() {
    this.dataChannelSubs = {};

    this.dataChannelSubs[ReservedDataType.Update]
        = this.entities.updateEntity.bind(this.entities);

    this.dataChannelSubs[ReservedDataType.UpdateMulti]
        = this.entities.updateEntityMulti.bind(this.entities);

    this.dataChannelSubs[ReservedDataType.Remove]
        = this.entities.removeRemoteEntity.bind(this.entities);
  }

  connect(serverUrl, appName, roomName, enableAudio = false) {
    NAF.app = appName;
    NAF.room = roomName;

    this.adapter.setServerUrl(serverUrl);
    this.adapter.setApp(appName);
    this.adapter.setRoom(roomName);

    var webrtcOptions = {
      audio: enableAudio,
      video: false,
      datachannel: true
    };
    this.adapter.setWebRtcOptions(webrtcOptions);

    this.adapter.setServerConnectListeners(
      this.connectSuccess.bind(this),
      this.connectFailure.bind(this)
    );
    this.adapter.setDataChannelListeners(
      this.dataChannelOpen.bind(this),
      this.dataChannelClosed.bind(this),
      this.receivedData.bind(this)
    );
    this.adapter.setRoomOccupantListener(this.occupantsReceived.bind(this));

    return this.adapter.connect();
  }

  onConnect(callback) {
    this.onConnectCallback = callback;

    if (this.isConnected()) {
      callback();
    } else {
      document.body.addEventListener('connected', callback, false);
    }
  }

  connectSuccess(clientId) {
    NAF.log.write('Networked-Aframe Client ID:', clientId);
    NAF.clientId = clientId;

    var evt = new CustomEvent('connected', {'detail': { clientId: clientId }});
    document.body.dispatchEvent(evt);
  }

  connectFailure(errorCode, message) {
    NAF.log.error(errorCode, "failure to connect");
  }

  occupantsReceived(occupantList) {
    var prevConnectedClients = Object.assign({}, this.connectedClients);
    this.connectedClients = occupantList;
    this.checkForDisconnectingClients(prevConnectedClients, occupantList);
    this.checkForConnectingClients(occupantList);
  }

  checkForDisconnectingClients(oldOccupantList, newOccupantList) {
    for (var id in oldOccupantList) {
      var clientFound = newOccupantList[id];
      if (!clientFound) {
        NAF.log.write('Closing stream to ', id);
        this.adapter.closeStreamConnection(id);
      }
    }
  }

  // Some adapters will handle this internally
  checkForConnectingClients(occupantList) {
    for (var id in occupantList) {
      var startConnection = this.isNewClient(id) && this.adapter.shouldStartConnectionTo(occupantList[id]);
      if (startConnection) {
        NAF.log.write('Opening datachannel to ', id);
        this.adapter.startStreamConnection(id);
      }
    }
  }

  getConnectedClients() {
    return this.connectedClients;
  }

  isConnected() {
    return !!NAF.clientId;
  }

  isMineAndConnected(clientId) {
    return this.isConnected() && NAF.clientId === clientId;
  }

  isNewClient(clientId) {
    return !this.isConnectedTo(clientId);
  }

  isConnectedTo(clientId) {
    return this.adapter.getConnectStatus(clientId) === NAF.adapters.IS_CONNECTED;
  }

  dataChannelOpen(clientId) {
    NAF.log.write('Opened data channel from ' + clientId);
    this.activeDataChannels[clientId] = true;
    this.entities.completeSync(clientId, true);

    var evt = new CustomEvent('clientConnected', {detail: {clientId: clientId}});
    document.body.dispatchEvent(evt);
  }

  dataChannelClosed(clientId) {
    NAF.log.write('Closed data channel from ' + clientId);
    this.activeDataChannels[clientId] = false;
    this.entities.removeEntitiesOfClient(clientId);

    var evt = new CustomEvent('clientDisconnected', {detail: {clientId: clientId}});
    document.body.dispatchEvent(evt);
  }

  hasActiveDataChannel(clientId) {
    return !!this.activeDataChannels[clientId];
  }

  broadcastData(dataType, data) {
    this.adapter.broadcastData(dataType, data);
  }

  broadcastDataGuaranteed(dataType, data) {
    this.adapter.broadcastDataGuaranteed(dataType, data);
  }

  sendData(toClientId, dataType, data, guaranteed) {
    if (this.hasActiveDataChannel(toClientId)) {
      if (guaranteed) {
        this.adapter.sendDataGuaranteed(toClientId, dataType, data);
      } else {
        this.adapter.sendData(toClientId, dataType, data);
      }
    } else {
      // console.error("NOT-CONNECTED", "not connected to " + toClient);
    }
  }

  sendDataGuaranteed(toClientId, dataType, data) {
    this.sendData(toClientId, dataType, data, true);
  }

  subscribeToDataChannel(dataType, callback) {
    if (this.isReservedDataType(dataType)) {
      NAF.log.error('NetworkConnection@subscribeToDataChannel: ' + dataType + ' is a reserved dataType. Choose another');
      return;
    }
    this.dataChannelSubs[dataType] = callback;
  }

  unsubscribeToDataChannel(dataType) {
    if (this.isReservedDataType(dataType)) {
      NAF.log.error('NetworkConnection@unsubscribeToDataChannel: ' + dataType + ' is a reserved dataType. Choose another');
      return;
    }
    delete this.dataChannelSubs[dataType];
  }

  isReservedDataType(dataType) {
    return dataType == ReservedDataType.Update
        || dataType == ReservedDataType.Remove;
  }

  receivedData(fromClientId, dataType, data, source) {
    if (this.dataChannelSubs[dataType]) {
      this.dataChannelSubs[dataType](fromClientId, dataType, data, source);
    } else {
      NAF.log.write('NetworkConnection@receivedData: ' + dataType + ' has not been subscribed to yet. Call subscribeToDataChannel()');
    }
  }

  getServerTime() {
    return this.adapter.getServerTime();
  }

  disconnect() {
    this.entities.removeRemoteEntities();
    this.adapter.disconnect();

    NAF.app = '';
    NAF.room = '';
    NAF.clientId = '';
    this.connectedClients = {};
    this.activeDataChannels = {};
    this.adapter = null;

    this.setupDefaultDataSubscriptions();

    document.body.removeEventListener('connected', this.onConnectCallback);
  }
}

module.exports = NetworkConnection;
<|endoftext|>


<commit_before>//
// swallowFXPill.js
// Play a swallow sound and trigger visual effects after a pill has been swallowed
//
// Author: Elisa Lupin-Jimenez
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
// All assets are under CC Attribution Non-Commerical
// http://creativecommons.org/licenses/
//

/* globals Render */

(function() {

    var SWALLOW_SOUNDS_URLS = [
        // sounds from https://freesound.org/people/170084/sounds/408205/
        Script.resolvePath("../sounds/swallow-1.wav"),
        Script.resolvePath("../sounds/swallow-2.wav"),
        Script.resolvePath("../sounds/swallow-3.wav"),
        Script.resolvePath("../sounds/swallow-4.wav"),
        Script.resolvePath("../sounds/swallow-5.wav"),
        Script.resolvePath("../sounds/swallow-6.wav"),
        Script.resolvePath("../sounds/swallow-7.wav")
    ];

    // sound from https://freesound.org/people/meschi06/sounds/220914/
    var EFFECT_SOUND_URL = Script.resolvePath("../sounds/space-trip-stereo.wav");

    var SWALLOW_SOUNDS = [];
    var EFFECT_SOUND;

    var WIREFRAME = "Wireframe:LightingModel:enableWireframe";

    var VISUAL_EFFECTS = [
        WIREFRAME,
        1, // Depth
        2, // Albedo
        3, // Normal
        5, // Metallic
        6 // Emissive
    ];

    var SWALLOW_VOLUME = 0.5;
    var EFFECT_VOLUME = 0.9;
    var CHECK_RADIUS = 0.2; // meters
    var LIFETIME = 10; // seconds
    var GRAVITY = {x: 0, y: -9.8, z: 0};
    var PILL_SIZE = {x: 0.1259, y: 0.1259, z: 0.3227};
    var EFFECT_START_TIMEOUT = 300; // ms
    var DEBUG = false;

    var LAST_ACTIVE_PILL_SETTING = "io.highfidelity.spacePills.lastActivePillSetting";

    var _entityID;
    var _this;

    function Pill() {
        return;
    }

    Pill.prototype = {
        swallowPlayback: null,
        effectPlayback: null,
        effectPlaying: null,
        isInactive: true,

        resetRenderDefaults: function() {
            Render.getConfig("RenderMainView").getConfig(WIREFRAME.split(":")[1])[WIREFRAME.split(":")[2]] = false;
            Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").mode = 0;
            Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").enabled = false;
        },

        removeInjector: function() {
            if (_this.effectPlaying !== null) {
                if (_this.effectPlaying.playing) {
                    if (DEBUG) {
                        print("stopping wah sound");
                    }
                    _this.effectPlaying.stop();
                }
            }
        },

        startNearGrab: function(entityID) {
            if (DEBUG) {
                print("starting pill grab");
            }
            var editJSON = {
                visible: true,
                lifetime: -1,
                dynamic: true,
                dimensions: PILL_SIZE,
                collisionless: true,
                gravity: GRAVITY
            };
            Entities.editEntity(entityID, editJSON);
        },

        releaseGrab: function(entityID) {
            if (DEBUG) {
                print("releasing pill grab");
            }
            var age = Entities.getEntityProperties(entityID, 'age').age;
            var editJSON = {
                lifetime: age + LIFETIME,
                collisionless: false
            };
            Entities.editEntity(entityID, editJSON);
        },

        checkIfNearHead: function() {
            if (_this.isInactive && HMD.active) {
                var position = Entities.getEntityProperties(_entityID, "position").position;
                if (Vec3.distance(position, MyAvatar.getJointPosition("Head")) < (CHECK_RADIUS * MyAvatar.scale)) {
                    if (DEBUG) {
                        print("swallowing pill");
                    }
                    _this.isInactive = false;
                    _this.playSwallowEffect(_this.avatarHeadPosition, true);
                }
            }
        },

        enableVisualEffects: function() {
            var size = VISUAL_EFFECTS.length - 1;
            var index = Math.round(Math.random() * size);
            var effect = VISUAL_EFFECTS[index];
            if (DEBUG) {
                print("effect is: " + effect);
            }
            Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").size = {x: -1, y: -1, z: 1, w: 1};
            if (index === 0) {
                Render.getConfig("RenderMainView").getConfig(effect.split(":")[1])[effect.split(":")[2]] = true;
            } else {
                Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").enabled = true;
                Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").mode = effect;
            }
        },

        playSwallowEffect: function(position, isInHMD) {
            if (DEBUG) {
                print("playing swallow effect");
            }
            Settings.setValue(LAST_ACTIVE_PILL_SETTING, _entityID);

            var size = SWALLOW_SOUNDS_URLS.length - 1;
            var index = Math.round(Math.random() * size);
            var swallowSound = SWALLOW_SOUNDS[index];
            var headPosition = MyAvatar.getJointPosition("Head");
            _this.swallowPlayback.position = headPosition;
            Audio.playSound(swallowSound, _this.swallowPlayback);

            Script.setTimeout(function() {
                _this.effectPlaying = Audio.playSound(EFFECT_SOUND, _this.effectPlayback);
            }, EFFECT_START_TIMEOUT);

            _this.enableVisualEffects();

            if (isInHMD) {
                var age = Entities.getEntityProperties(_entityID, 'age').age;
                var editJSON = {
                    visible: false,
                    lifetime: age + LIFETIME,
                    collisionless: true
                };
                Entities.editEntity(_entityID, editJSON);
            } else {
                Script.setTimeout(function() {
                    _this.resetRenderDefaults();
                    _this.isInactive = true;
                }, LIFETIME * 1000);
            }
        },

        mousePressOnEntity: function(entityID, mouseEvent) {
            if (mouseEvent.isLeftButton) {
                if (!HMD.active && _this.isInactive) {
                    if (DEBUG) {
                        print("pill has been clicked");
                    }
                    _this.isInactive = false;
                    _this.playSwallowEffect(_this.avatarHeadPosition, false);
                }
            }
        },

        preload: function(entityID) {
            _this = this;
            if (DEBUG) {
                print("loading new pill");
            }
            Script.update.connect(_this.checkIfNearHead);
            _entityID = entityID;
            SWALLOW_SOUNDS_URLS.forEach(function(swallow) {
                SWALLOW_SOUNDS.push(SoundCache.getSound(swallow));
            });
            EFFECT_SOUND = SoundCache.getSound(EFFECT_SOUND_URL);
            _this.swallowPlayback = {
                volume: SWALLOW_VOLUME
            };
            _this.effectPlayback = {
                volume: EFFECT_VOLUME,
                localOnly: true
            };
        },

        unload: function(entityID) {
            if (DEBUG) {
                print("unloading pill");
            }
            Script.update.disconnect(_this.checkIfNearHead);
            if (_entityID === Settings.getValue(LAST_ACTIVE_PILL_SETTING, Uuid.NULL)) {
                _this.resetRenderDefaults();
                Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").size = {x: 0, y: -1, z: 1, w: 1};
                _this.removeInjector();
            }
        }
    };

    var self = new Pill();
    return self;

});
<commit_msg>changed pill distance, neck and head joints trigger<commit_after>//
// swallowFXPill.js
// Play a swallow sound and trigger visual effects after a pill has been swallowed
//
// Author: Elisa Lupin-Jimenez
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
// All assets are under CC Attribution Non-Commerical
// http://creativecommons.org/licenses/
//

/* globals Render */

(function() {

    var SWALLOW_SOUNDS_URLS = [
        // sounds from https://freesound.org/people/170084/sounds/408205/
        Script.resolvePath("../sounds/swallow-1.wav"),
        Script.resolvePath("../sounds/swallow-2.wav"),
        Script.resolvePath("../sounds/swallow-3.wav"),
        Script.resolvePath("../sounds/swallow-4.wav"),
        Script.resolvePath("../sounds/swallow-5.wav"),
        Script.resolvePath("../sounds/swallow-6.wav"),
        Script.resolvePath("../sounds/swallow-7.wav")
    ];

    // sound from https://freesound.org/people/meschi06/sounds/220914/
    var EFFECT_SOUND_URL = Script.resolvePath("../sounds/space-trip-stereo.wav");

    var SWALLOW_SOUNDS = [];
    var EFFECT_SOUND;

    var WIREFRAME = "Wireframe:LightingModel:enableWireframe";

    var VISUAL_EFFECTS = [
        WIREFRAME,
        1, // Depth
        2, // Albedo
        3, // Normal
        5, // Metallic
        6 // Emissive
    ];

    var SWALLOW_VOLUME = 0.5;
    var EFFECT_VOLUME = 0.9;
    var CHECK_RADIUS = 0.25; // meters
    var LIFETIME = 10; // seconds
    var GRAVITY = {x: 0, y: -9.8, z: 0};
    var PILL_SIZE = {x: 0.1259, y: 0.1259, z: 0.3227};
    var EFFECT_START_TIMEOUT = 300; // ms
    var DEBUG = false;

    var LAST_ACTIVE_PILL_SETTING = "io.highfidelity.spacePills.lastActivePillSetting";

    var _entityID;
    var _this;

    function Pill() {
        return;
    }

    Pill.prototype = {
        swallowPlayback: null,
        effectPlayback: null,
        effectPlaying: null,
        isInactive: true,

        resetRenderDefaults: function() {
            Render.getConfig("RenderMainView").getConfig(WIREFRAME.split(":")[1])[WIREFRAME.split(":")[2]] = false;
            Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").mode = 0;
            Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").enabled = false;
        },

        removeInjector: function() {
            if (_this.effectPlaying !== null) {
                if (_this.effectPlaying.playing) {
                    if (DEBUG) {
                        print("stopping wah sound");
                    }
                    _this.effectPlaying.stop();
                }
            }
        },

        startNearGrab: function(entityID) {
            if (DEBUG) {
                print("starting pill grab");
            }
            var editJSON = {
                visible: true,
                lifetime: -1,
                dynamic: true,
                dimensions: PILL_SIZE,
                collisionless: true,
                gravity: GRAVITY
            };
            Entities.editEntity(entityID, editJSON);
        },

        releaseGrab: function(entityID) {
            if (DEBUG) {
                print("releasing pill grab");
            }
            var age = Entities.getEntityProperties(entityID, 'age').age;
            var editJSON = {
                lifetime: age + LIFETIME,
                collisionless: false
            };
            Entities.editEntity(entityID, editJSON);
        },

        checkIfNearHead: function() {
            if (_this.isInactive && HMD.active) {
                var position = Entities.getEntityProperties(_entityID, "position").position;
                if ((Vec3.distance(position, MyAvatar.getJointPosition("Head")) < (CHECK_RADIUS * MyAvatar.scale)) ||
                    (Vec3.distance(position, MyAvatar.getJointPosition("Neck")) < (CHECK_RADIUS * MyAvatar.scale))) {
                    if (DEBUG) {
                        print("swallowing pill");
                    }
                    _this.isInactive = false;
                    _this.playSwallowEffect(_this.avatarHeadPosition, true);
                }
            }
        },

        enableVisualEffects: function() {
            var size = VISUAL_EFFECTS.length - 1;
            var index = Math.round(Math.random() * size);
            var effect = VISUAL_EFFECTS[index];
            if (DEBUG) {
                print("effect is: " + effect);
            }
            Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").size = {x: -1, y: -1, z: 1, w: 1};
            if (index === 0) {
                Render.getConfig("RenderMainView").getConfig(effect.split(":")[1])[effect.split(":")[2]] = true;
            } else {
                Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").enabled = true;
                Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").mode = effect;
            }
        },

        playSwallowEffect: function(position, isInHMD) {
            if (DEBUG) {
                print("playing swallow effect");
            }
            Settings.setValue(LAST_ACTIVE_PILL_SETTING, _entityID);

            var size = SWALLOW_SOUNDS_URLS.length - 1;
            var index = Math.round(Math.random() * size);
            var swallowSound = SWALLOW_SOUNDS[index];
            var headPosition = MyAvatar.getJointPosition("Head");
            _this.swallowPlayback.position = headPosition;
            Audio.playSound(swallowSound, _this.swallowPlayback);

            Script.setTimeout(function() {
                _this.effectPlaying = Audio.playSound(EFFECT_SOUND, _this.effectPlayback);
            }, EFFECT_START_TIMEOUT);

            _this.enableVisualEffects();

            if (isInHMD) {
                var age = Entities.getEntityProperties(_entityID, 'age').age;
                var editJSON = {
                    visible: false,
                    lifetime: age + LIFETIME,
                    collisionless: true
                };
                Entities.editEntity(_entityID, editJSON);
            } else {
                Script.setTimeout(function() {
                    _this.resetRenderDefaults();
                    _this.isInactive = true;
                }, LIFETIME * 1000);
            }
        },

        mousePressOnEntity: function(entityID, mouseEvent) {
            if (mouseEvent.isLeftButton) {
                if (!HMD.active && _this.isInactive) {
                    if (DEBUG) {
                        print("pill has been clicked");
                    }
                    _this.isInactive = false;
                    _this.playSwallowEffect(_this.avatarHeadPosition, false);
                }
            }
        },

        preload: function(entityID) {
            _this = this;
            if (DEBUG) {
                print("loading new pill");
            }
            Script.update.connect(_this.checkIfNearHead);
            _entityID = entityID;
            SWALLOW_SOUNDS_URLS.forEach(function(swallow) {
                SWALLOW_SOUNDS.push(SoundCache.getSound(swallow));
            });
            EFFECT_SOUND = SoundCache.getSound(EFFECT_SOUND_URL);
            _this.swallowPlayback = {
                volume: SWALLOW_VOLUME
            };
            _this.effectPlayback = {
                volume: EFFECT_VOLUME,
                localOnly: true
            };
        },

        unload: function(entityID) {
            if (DEBUG) {
                print("unloading pill");
            }
            Script.update.disconnect(_this.checkIfNearHead);
            if (_entityID === Settings.getValue(LAST_ACTIVE_PILL_SETTING, Uuid.NULL)) {
                _this.resetRenderDefaults();
                Render.getConfig("RenderMainView").getConfig("DebugDeferredBuffer").size = {x: 0, y: -1, z: 1, w: 1};
                _this.removeInjector();
            }
        }
    };

    var self = new Pill();
    return self;

});
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.3.3
var BASE_PATH, DATA_PATH, LOG_FILE, PUBLIC_PATH, UPLOAD_PATH, app, checkPort, dir, dirs, echo, express, fs, getFiles, io, isSet, os, port, request, server, shorten, sortByDate, startListen, url, util, _i, _len;

express = require("express");

fs = require("fs");

os = require("os");

request = require("request");

util = require('util');

/* 定数
*/

BASE_PATH = "../../../../";

DATA_PATH = BASE_PATH + "data/";

UPLOAD_PATH = BASE_PATH + "uploads/";

PUBLIC_PATH = "../public/";

LOG_FILE = "log.txt";

/* 標準出力を上書き
*/

echo = console.log;

console.log = function() {
  var scr;
  scr = util.format.apply(this, arguments) + '\n';
  return fs.appendFileSync(LOG_FILE, scr);
};

/* app
*/

app = express();

app.use(function(req, res, next){
  var hostname = req.headers.host;
  if(hostname == null || hostname == undefined){
    /* hostヘッダーがついていないのはHTTP1.1では
     * 規約違反である.*/
    res.send(400);
    return;
  }
  /*
   * localhostへのアクセスのみ許可.
   * 127.0.0.1も許可しない
   */
  if(hostname.match(/^localhost/) != null){
    next();
  }else{
    /* localhost以外からのアクセスは400で応答 */
    res.send(400);
  }
});

app.use(require("connect").bodyParser());

/* static
*/

app.use("/", express["static"](__dirname + "/" + PUBLIC_PATH));

app.use("/uploads", express["static"](__dirname + "/" + UPLOAD_PATH));

/* データディレクトリがない場合は作成
*/

dirs = [DATA_PATH, UPLOAD_PATH];

for (_i = 0, _len = dirs.length; _i < _len; _i++) {
  dir = dirs[_i];
  try {
    fs.statSync(dir);
  } catch (e) {
    fs.mkdirSync(dir, "777");
  }
}

/* 内部で使う関数
*/

getFiles = function(dataPath) {
  var files, list;
  files = fs.readdirSync(dataPath);
  list = [];
  files.forEach(function(fileName) {
    var data, file;
    if (fileName.match(/.+\.json/)) {
      file = fs.readFileSync(dataPath + fileName) + "";
      if (file) {
        data = null;
        try {
          data = JSON.parse(file);
        } catch (e) {
          console.log(e);
        }
        if (data) {
          return list.push(data);
        }
      }
    }
  });
  return list;
};

isSet = function(arg) {
  return (arg != null) && arg !== "";
};

shorten = function(str, length) {
  var postfix, s;
  s = str.replace(/\n|\\|\/|\:|\*|\?|\"|\<|\>|\|/g, "");
  postfix = "...";
  if (s.length > length) {
    if (length > postfix.length) {
      return s.slice(0, length - postfix.length) + postfix;
    } else {
      return s.slice(0, length);
    }
  } else {
    return s;
  }
};

sortByDate = function(a, b) {
  var ax, bx;
  if (!a) {
    return -1;
  } else if (!b) {
    return 1;
  }
  ax = (new Date(a.date)).getTime();
  bx = (new Date(b.date)).getTime();
  if (ax == null) {
    ax = 0;
  }
  if (bx == null) {
    bx = 0;
  }
  return ax - bx;
};

/* API
*/

app.post("/upload", function(req, res) {
  var files, saved;
  files = req.files.files;
  if (typeof files.forEach !== 'function') {
    files = [files];
  }
  saved = [];
  files.forEach(function(file) {
    var data, newPath;
    data = fs.readFileSync(file.path);
    if (data) {
      newPath = __dirname + "/" + UPLOAD_PATH + file.name;
      fs.writeFileSync(newPath, data);
      console.log("saved:" + file.name);
      return saved.push(UPLOAD_PATH + file.name);
    }
  });
  return res.send(JSON.stringify(saved));
});

app.post("/write", function(req, res) {
  var data;
  data = req.body;
  if (isSet(data.name) && isSet(data.date) && isSet(data.text)) {
    return fs.writeFile(DATA_PATH + shorten(data.name, 10) + "「" + shorten(data.text, 20) + "」" + ".json", JSON.stringify(data), function(err) {
      if (err) {
        return res.send("0");
      } else {
        return res.send("1");
      }
    });
  }
});

app.get("/page/:page/:per", function(req, res) {
  var end, files, page, per, sliced, start;
  files = getFiles(DATA_PATH);
  files.sort(sortByDate);
  page = parseInt(req.params.page);
  per = parseInt(req.params.per);
  start = Math.max(files.length - (page + 1) * per, 0);
  end = Math.max(files.length - page * per, 0);
  sliced = files.slice(start, end);
  return res.send(JSON.stringify(sliced));
});

app.get("/read", function(req, res) {
  return res.send(JSON.stringify(getFiles(DATA_PATH)));
});

app.get("/exit", function(req, res) {
  console.log("httpからサーバーが終了されました");
  return process.exit(0);
});

/**
 * ポート番号の設定
 * macとwindowsではコロン(:)がディレクトリ名に使えない文字なので
 * ドライブ文字と被らない::をセパレータとして使う
 * 実行しているディレクトリ::portの並びで保存する
*/

checkPort = function() {
  var default_port, detected, dirToPortString, exists, file, lines, port, portDirString, portfile, runtime_dir, separator;
  dirToPortString = function(port) {
    return runtime_dir + separator + port + "\n";
  };
  portfile = os.tmpDir() + "/.dropboard.port";
  runtime_dir = __dirname;
  default_port = 50000;
  port = default_port;
  separator = "::";
  detected = false;
  exists = fs.existsSync(portfile);
  if (exists) {
    file = fs.readFileSync(portfile, "utf-8");
    lines = file.split("\n");
    lines.forEach(function(line) {
      var pear;
      pear = line.split(separator);
      if (pear.length === 2 && pear[0] === runtime_dir) {
        port = Number(pear[1]);
        return detected = true;
      }
    });
    if (!detected) {
      port = default_port + lines.length;
    }
  }
  portDirString = runtime_dir + separator + port + "\n";
  if (!detected || !exists) {
    fs.appendFileSync(portfile, portDirString, "utf-8");
  }
  return port;
};

port = checkPort();

url = "http://localhost:" + port + "/";

process.on('uncaughtException', function(err) {
  if (err.errno === 'EADDRINUSE') {
    return request(url + "exit", function(error, response, body) {
      return startListen();
    });
  }
});

/* WebSocketの準備
*/

server = require('http').createServer(app);

io = require('socket.io').listen(server);

io.set('log level', 1);

io.sockets.on('connection', function(socket) {
  /**
   * クライアントからの接続時にDATA_PATHの
   * 監視を開始する.
  */

  var watcher;
  watcher = fs.watch(DATA_PATH, function(event, filename) {
    /**
     * ディレクトリに変更があった際にupdateイベントを
     * クライアントにpushする.
    */
    return socket.emit('update', {});
  });
  /**
   * クライアントから切断された際に
   * ディレクトリの監視を停止する.
  */

  return socket.on('disconnect', function() {
    return watcher.close();
  });
});

/**
 * expressのインスタンスではなく
 * httpServerのインスタンスでlistenすること！
 * そうしないとsocket.io.jsが404になる.
*/

startListen = function() {
  return server.listen(port);
};

startListen();

echo(url);
<commit_msg>localhost制限まわり<commit_after>// Generated by CoffeeScript 1.4.0
var BASE_PATH, DATA_PATH, LOG_FILE, PUBLIC_PATH, UPLOAD_PATH, app, checkPort, dir, dirs, echo, express, fs, getFiles, io, isSet, os, port, request, server, shorten, sortByDate, startListen, url, util, _i, _len;

express = require("express");

fs = require("fs");

os = require("os");

request = require("request");

util = require('util');

/* 定数
*/

BASE_PATH = "../../../../";

DATA_PATH = BASE_PATH + "data/";

UPLOAD_PATH = BASE_PATH + "uploads/";

PUBLIC_PATH = "../public/";

LOG_FILE = "log.txt";

/* 標準出力を上書き
*/

echo = console.log;

console.log = function() {
  var scr;
  scr = util.format.apply(this, arguments) + '\n';
  return fs.appendFileSync(LOG_FILE, scr);
};

/* app
*/

app = express();

app.use(require("connect").bodyParser());

/* static
*/

app.use("/", express["static"](__dirname + "/" + PUBLIC_PATH));

app.use("/uploads", express["static"](__dirname + "/" + UPLOAD_PATH));

/* データディレクトリがない場合は作成
*/

dirs = [DATA_PATH, UPLOAD_PATH];

for (_i = 0, _len = dirs.length; _i < _len; _i++) {
  dir = dirs[_i];
  try {
    fs.statSync(dir);
  } catch (e) {
    fs.mkdirSync(dir, "777");
  }
}

/* 内部で使う関数
*/

getFiles = function(dataPath) {
  var files, list;
  files = fs.readdirSync(dataPath);
  list = [];
  files.forEach(function(fileName) {
    var data, file;
    if (fileName.match(/.+\.json/)) {
      file = fs.readFileSync(dataPath + fileName) + "";
      if (file) {
        data = null;
        try {
          data = JSON.parse(file);
        } catch (e) {
          console.log(e);
        }
        if (data) {
          return list.push(data);
        }
      }
    }
  });
  return list;
};

isSet = function(arg) {
  return (arg != null) && arg !== "";
};

shorten = function(str, length) {
  var postfix, s;
  s = str.replace(/\n|\\|\/|\:|\*|\?|\"|\<|\>|\|/g, "");
  postfix = "...";
  if (s.length > length) {
    if (length > postfix.length) {
      return s.slice(0, length - postfix.length) + postfix;
    } else {
      return s.slice(0, length);
    }
  } else {
    return s;
  }
};

sortByDate = function(a, b) {
  var ax, bx;
  if (!a) {
    return -1;
  } else if (!b) {
    return 1;
  }
  ax = (new Date(a.date)).getTime();
  bx = (new Date(b.date)).getTime();
  if (ax == null) {
    ax = 0;
  }
  if (bx == null) {
    bx = 0;
  }
  return ax - bx;
};

/* API
*/

app.post("/upload", function(req, res) {
  var files, saved;
  files = req.files.files;
  if (typeof files.forEach !== 'function') {
    files = [files];
  }
  saved = [];
  files.forEach(function(file) {
    var data, newPath;
    data = fs.readFileSync(file.path);
    if (data) {
      newPath = __dirname + "/" + UPLOAD_PATH + file.name;
      fs.writeFileSync(newPath, data);
      console.log("saved:" + file.name);
      return saved.push(UPLOAD_PATH + file.name);
    }
  });
  return res.send(JSON.stringify(saved));
});

app.post("/write", function(req, res) {
  var data;
  data = req.body;
  if (isSet(data.name) && isSet(data.date) && isSet(data.text)) {
    return fs.writeFile(DATA_PATH + shorten(data.name, 10) + "「" + shorten(data.text, 20) + "」" + ".json", JSON.stringify(data), function(err) {
      if (err) {
        return res.send("0");
      } else {
        return res.send("1");
      }
    });
  }
});

app.get("/page/:page/:per", function(req, res) {
  var end, files, page, per, sliced, start;
  files = getFiles(DATA_PATH);
  files.sort(sortByDate);
  page = parseInt(req.params.page);
  per = parseInt(req.params.per);
  start = Math.max(files.length - (page + 1) * per, 0);
  end = Math.max(files.length - page * per, 0);
  sliced = files.slice(start, end);
  return res.send(JSON.stringify(sliced));
});

app.get("/read", function(req, res) {
  return res.send(JSON.stringify(getFiles(DATA_PATH)));
});

app.get("/exit", function(req, res) {
  console.log("httpからサーバーが終了されました");
  return process.exit(0);
});

/**
 * ポート番号の設定
 * macとwindowsではコロン(:)がディレクトリ名に使えない文字なので
 * ドライブ文字と被らない::をセパレータとして使う
 * 実行しているディレクトリ::portの並びで保存する
*/

checkPort = function() {
  var default_port, detected, dirToPortString, exists, file, lines, port, portDirString, portfile, runtime_dir, separator;
  dirToPortString = function(port) {
    return runtime_dir + separator + port + "\n";
  };
  portfile = os.tmpDir() + "/.dropboard.port";
  runtime_dir = __dirname;
  default_port = 50000;
  port = default_port;
  separator = "::";
  detected = false;
  exists = fs.existsSync(portfile);
  if (exists) {
    file = fs.readFileSync(portfile, "utf-8");
    lines = file.split("\n");
    lines.forEach(function(line) {
      var pear;
      pear = line.split(separator);
      if (pear.length === 2 && pear[0] === runtime_dir) {
        port = Number(pear[1]);
        return detected = true;
      }
    });
    if (!detected) {
      port = default_port + lines.length;
    }
  }
  portDirString = runtime_dir + separator + port + "\n";
  if (!detected || !exists) {
    fs.appendFileSync(portfile, portDirString, "utf-8");
  }
  return port;
};

port = checkPort();

url = "http://localhost:" + port + "/";

process.on('uncaughtException', function(err) {
  if (err.errno === 'EADDRINUSE') {
    return request(url + "exit", function(error, response, body) {
      return startListen();
    });
  }
});

/* WebSocketの準備
*/

server = require('http').createServer(app);

io = require('socket.io').listen(server);

io.set('log level', 1);

io.sockets.on('connection', function(socket) {
  /**
   * クライアントからの接続時にDATA_PATHの
   * 監視を開始する.
  */

  var watcher;
  watcher = fs.watch(DATA_PATH, function(event, filename) {
    /**
     * ディレクトリに変更があった際にupdateイベントを
     * クライアントにpushする.
    */
    return socket.emit('update', {});
  });
  /**
   * クライアントから切断された際に
   * ディレクトリの監視を停止する.
  */

  return socket.on('disconnect', function() {
    return watcher.close();
  });
});

/**
 * expressのインスタンスではなく
 * httpServerのインスタンスでlistenすること！
 * そうしないとsocket.io.jsが404になる.
*/

startListen = function() {
  return server.listen(port);
};

startListen();

echo(url);
<|endoftext|>


<commit_before>'use strict';

import fs from 'fs';
import path from 'path';
import jwt from 'express-jwt';
import upload from '../controllers/upload.controller';

/**
 * Configs multer storage, create directories if not exist.
 *
 * @param {Object} req - HTTP request.
 * @param {Object} res - HTTP response.
 * @param {multerCallback} cb - A callback for multer.
 */
const storage = (req, file, cb) => {
  const STATICS = require(path.join(req.app.pwd, 'configurations', 'statics'));
  const BASE = STATICS.shared.uploads.users;
  const USER_DIR = path.join(BASE, req.body.userId);
  const FIELD_DIR = path.join(USER_DIR, file.fieldname);
  if (!fs.existsSync(path.join(req.app.pwd, USER_DIR))) {
    fs.mkdirSync(path.join(req.app.pwd, USER_DIR));
  }

  if (!fs.existsSync(path.join(req.app.pwd, FIELD_DIR))) {
    fs.mkdirSync(path.join(req.app.pwd, FIELD_DIR));
  }

  cb(null, path.join(req.app.pwd, FIELD_DIR));
};

/**
 * Upload routing and multer configure.
 *
 * @author C Killua
 * @module Konko/Core/Routes/Upload
 * @param {Object} app - Express app.
 */
export default app => {
  const JWT_AUTH = jwt({ secret: app.get('secret'), userProperty: 'payload' });
  const profileAUpload = new app.multer(app, storage, null, { fileSize: 2 * 1024 * 1024 });
  const profileBUpload = new app.multer(app, storage, null, { fileSize: 5 * 1024 * 1024 });

  app.route('/api/v1/upload/avatar')
    .post(JWT_AUTH, profileAUpload.single('avatar'), upload.profileUpload);

  app.route('/api/v1/upload/banner')
    .post(JWT_AUTH, profileBUpload.single('banner'), upload.profileUpload);
};

/**
 * Callback for multer.
 *
 * @callback multerCallback
 * @param {Null} null.
 * @param {String} Path that where the file will store.
 */
<commit_msg>added permission check to upload api route<commit_after>'use strict';

import jwt from 'express-jwt';
import Uploader from '../../../configs/uploader';
import upload from '../controllers/upload.controller';
import permission from '../../../configs/permission';

/**
 * Upload routing and multer configure.
 *
 * @author C Killua
 * @module Konko/Core/Routes/Upload
 * @param {Object} app - Express app.
 */
export default app => {
  const JWT_AUTH = jwt({ secret: app.get('secret'), userProperty: 'payload' });

  app.route('/api/v1/upload/avatar')
    .post(JWT_AUTH, permission.get('allowUser'), Uploader.upload(app, 'avatar'), upload.profileUpload);

  app.route('/api/v1/upload/banner')
    .post(JWT_AUTH, permission.get('allowUser'), Uploader.upload(app, 'banner'), upload.profileUpload);
};
<|endoftext|>


<commit_before>/**
 *
 * @author Patrick Oladimeji
 * @date 10/14/13 15:21:21 PM
 */
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, d3, module, $, property, self */

(function () {
    "use strict";
    var pad = 50;
    /**
        Data can be a 2d array. If this is the case, then each child array represents a dataset for the bar chart
    */
    function bar(data) {
        if (data instanceof Array && !(data[0] instanceof Array)) { data = [data]; }

        var fill = '#76d', axisfont = 'bold 8px sans-serif', gap = 2;
        bar.margin = property.call(bar, {top: 20, left: 45, right: 200, bottom: 50});
        bar.width = property.call(bar, 600);
        bar.height = property.call(bar, 300);
        bar.ylabel = property.call(bar, "");
        bar.xlabel = property.call(bar, "");
        bar.label = property.call(bar, "");
        bar.data = property.call(bar, data || []);
        //legend is an array of names to use for each group.
        //the length of the legend should be the same as the length of the 2d array
        bar.legend = property.call(bar, []);
        bar.legendheight = property.call(bar, 20);

        bar.xdata = property.call(bar, function (d) {
            return d.value;
        });
        bar.ydata = property.call(bar, function (d) { return d.N; });
        //error bar is a function that returns the height of the errorbar to use for each data
        bar.errorbar = property.call(bar, undefined);

        bar.fill = property.call(bar, function (d) { return fill; });

        bar.rectClicked = property.call(bar, function (d, i) {  });
        bar.barSpace = property.call(bar, 0);
        bar.groupSpace = property.call(bar, 10);
        //specifies whether or not text is shown on top of bars would usually return
        bar.columnText = property.call(bar, undefined);
        bar.showXAxis = property.call(bar, true);
        bar.showYAxis = property.call(bar, true);

        bar.render = function (id) {
            id = id || "body";
            var margin = bar.margin();
            var xfield = bar.xdata(), yfield = bar.ydata(), fillfunc = bar.fill();

            var ymax = d3.max(bar.data(), function (d) {
                return d3.max(d, function (n) {
                    if (bar.errorbar()) {
                        return bar.errorbar()(n) + yfield(n);
                    }
                    return yfield(n);
                });
            });
            //padding is a function of the length of the yaxis label
            var yrange = [0, ymax], bspace = bar.barSpace(), gspace = bar.groupSpace();
            var xdomain = bar.data()[0].map(xfield);
            var x = d3.scale.ordinal().rangeRoundBands([0, bar.width()], 0.15).domain(xdomain);
            var y = d3.scale.linear().range([0, bar.height()]).domain(yrange);
            var yaxisscale = d3.scale.linear().range([bar.height(), 0]).domain(yrange);
            var vis = d3.select(id).append("svg:svg")
                .attr("width", bar.width() + margin.left + margin.right)
                .attr("height", bar.height() + margin.top + margin.bottom);
            var gw = x.rangeBand(), bw = gw / bar.data().length;
            var g = vis.append("svg:g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
            var bgs = g.selectAll("g.bargroup").data(bar.data()[0]).enter()
                    .append("g").attr("class", "bargroup").attr("transform", function (d, i) {
                        return "translate(" + x(xfield(d, i)) + ")";
                    });
            var rectGroup = bgs.selectAll("g.rectgroup").data(function (d, i) {
                return bar.data().map(function (a) {
                    return a[i];
                });
            }).enter().append("g").attr("transform", function (d, i) {
                return "translate(" + (i * bw) + ")";
            });
            rectGroup.append("svg:rect").attr("width", bw - bspace)
                .attr("height", function (d, i) {
                    return y(yfield(d, i));
                }).attr("y", function (d, i) {
                    return bar.height() - y(yfield(d, i));
                }).attr("class", 'bar')
                .style("fill", fillfunc).style('stroke', function (d, i) {
                    return d3.rgb(fillfunc(d, i)).darker();
                }).on("click", bar.rectClicked()).append("title").text(function (d, i) {
                    return "x: " + xfield(d, i) + " y:" + yfield(d, i);
                });
            //if there is error bar function draw the error bars
            if (bar.errorbar()) {
                var errorbar = bar.errorbar();
                var bars = bgs.selectAll('line.errorbar').data(function (d, i) {
                    return bar.data().map(function (a) {
                        return a[i];
                    });
                }).enter();
                bars.append('line')
                    .attr("x1", function (d, i) {
                        return i * bw + (bw - bspace) / 2;
                    })
                    .attr("y1", function (d, i) {
                        var ebh = y(errorbar(d, i));//error bar height
                        return isNaN(ebh) ? 0 : bar.height() - y(yfield(d, i)) + ebh;
                    }).attr("x2", function (d, i) {
                        return i * bw + (bw - bspace) / 2;
                    })
                    .attr("y2", function (d, i) {
                        var ebh = y(errorbar(d, i));
                        return isNaN(ebh) ? 0 : bar.height() -  y(yfield(d, i)) - ebh;
                    })
                    .style("fill", "none")
                    .style("stroke", "#a22").style("stroke-width", 0.5);
                //bar hat
                bars.append('line')
                    .attr("x1", function (d, i) {
                        return i * bw + (bw - bspace) / 2  + bw / 4;
                    }).attr("x2", function (d, i) {
                        return i * bw + (bw - bspace) / 2  - bw / 4;
                    }).attr("y1", function (d, i) {
                        var ebh = y(errorbar(d, i));//error bar height
                        return isNaN(ebh) ? 0 : bar.height() - y(yfield(d, i)) + ebh;
                    }).attr("y2", function (d, i) {
                        var ebh = y(errorbar(d, i));//error bar height
                        return isNaN(ebh) ? 0 : bar.height() - y(yfield(d, i)) + ebh;
                    }).style("fill", "none")
                    .style("stroke", "#a22").style("stroke-width", 0.5);

                //bar bottom
                bars.append('line')
                    .attr("x1", function (d, i) {
                        return i * bw + (bw - bspace) / 2  + bw / 4;
                    }).attr("x2", function (d, i) {
                        return i * bw + (bw - bspace) / 2  - bw / 4;
                    }).attr("y1", function (d, i) {
                        var ebh = y(errorbar(d, i));
                        return isNaN(ebh) ? 0 : bar.height() -  y(yfield(d, i)) - ebh;
                    }).attr("y2", function (d, i) {
                        var ebh = y(errorbar(d, i));
                        return isNaN(ebh) ? 0 : bar.height() -  y(yfield(d, i)) - ebh;
                    }).style("fill", "none")
                    .style("stroke", "#a22").style("stroke-width", 0.5);
            }

            //if there is a column text draw it
            if (bar.columnText()) {
                var colText = bar.columnText();
                rectGroup.append("text")
                    .text(colText)
                    .attr("y", function (d, i) {
                        return bar.height() - y(yfield(d, i));
                    }).attr("x", bw / 2)
                    .attr("dy", "-10")
                    .style("text-anchor", "middle")
                    .style("alignment-baseline", "text-after-edge");
            }

            if (bar.showYAxis()) {
                var yaxis = d3.svg.axis().scale(yaxisscale).orient('left');
                g.append("svg:g")
                    .attr("class", "y axis")
                    .call(yaxis);
            }
            if (bar.showXAxis()) {
                var xaxis = d3.svg.axis().scale(x).tickSubdivide(true);
                var xg = g.append("svg:g")
                    .attr("class", 'x axis')
                    .attr("transform", "translate(0," + bar.height() + ")")
                    .call(xaxis);
                xg.selectAll("text").remove();
                //overriding the labels drawn by the svg.axis here so we can use word wrapping
                bgs.append("foreignObject")
                    .attr("width", gw).attr("height", 100)
                    .attr("x", 0).attr("y", bar.height() + 5)
                    .append("xhtml:body")
                    .style("text-align", "center")
                    .style("padding", 0).style("margin", 0)
                    .append("p").html(function (d, i) {
                        return xfield(d, i);
                    });
            }

            //render labels
            vis.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                .append("text")
                .text(bar.label()).attr("x", bar.width() / 2).attr("class", "chartlabel");
            vis.append("g").attr("transform", "translate(" + margin.left + "," + (bar.height() + margin.top + margin.bottom / 2) + ")")
                .append("text").text(bar.xlabel()).style("text-anchor", "middle").style("alignment-baseline", "text-after-edge")
                .attr("class", "axislabel").attr("x", bar.width() / 2);

            vis.append("g").attr("transform", "translate(0," + margin.top + ")").append("text").text(bar.ylabel())
                .style("text-anchor", "middle").style("alignment-baseline", "text-before-edge")
                .attr("class", "axislabel").attr("x", 0).attr("y", bar.height() / 2)
                .attr("transform", "rotate(-90 0 " + (bar.height() / 2) + ")");

            //render legend if any
            if (bar.legend() && bar.legend().length > 0) {
                var keys = vis.append("g").attr('transform', 'translate(' + (pad + bar.width()) + ")")
                    .selectAll('g.key').data(bar.legend()).enter()
                    .append("g").attr("transform", function (d, i) {
                        return "translate(0, " + (pad + bar.legendheight() * i) + ")";
                    });

                keys.append("svg:rect").attr("width", bar.legendheight() * 0.75).attr("height", bar.legendheight() * 0.75)
                    .style('fill', fillfunc).style('stroke', function (d, i) {
                        return d3.rgb(fillfunc(d, i)).darker();
                    });
                keys.append("svg:text").attr("x", bar.legendheight())
                    .attr("y", bar.legendheight() / 2)
                    .text(String).style("alignment-baseline", 'text-after-edge')
                    .style("font-size", (0.65 * bar.legendheight()) + "px");
            }
            return vis;
        };
        return bar;
    }

    if (typeof module === "undefined") {
        self.bar = bar;
    } else {
        module.exports = bar;
    }
}());
<commit_msg>fixed chart label alignment and placement<commit_after>/**
 *
 * @author Patrick Oladimeji
 * @date 10/14/13 15:21:21 PM
 */
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, d3, module, $, property, self */

(function () {
    "use strict";
    var pad = 50;
    function property(v) {
        var p = function (_) {
            if (!arguments.length) {
                return v;
            }
            return this;
        };
        return p;
    }
    /**
        Data can be a 2d array. If this is the case, then each child array represents a dataset for the bar chart
    */
    function bar(data) {
        if (data instanceof Array && !(data[0] instanceof Array)) { data = [data]; }

        var fill = '#76d', axisfont = 'bold 8px sans-serif', gap = 2;
        bar.margin = property.call(bar, {top: 20, left: 45, right: 200, bottom: 50});
        bar.width = property.call(bar, 600);
        bar.height = property.call(bar, 300);
        bar.ylabel = property.call(bar, "");
        bar.xlabel = property.call(bar, "");
        bar.label = property.call(bar, "");
        bar.data = property.call(bar, data || []);
        //legend is an array of names to use for each group.
        //the length of the legend should be the same as the length of the 2d array
        bar.legend = property.call(bar, []);
        bar.legendheight = property.call(bar, 20);

        bar.xdata = property.call(bar, function (d) {
            return d.value;
        });
        bar.ydata = property.call(bar, function (d) { return d.N; });
        //error bar is a function that returns the height of the errorbar to use for each data
        bar.errorbar = property.call(bar, undefined);

        bar.fill = property.call(bar, function (d) { return fill; });

        bar.rectClicked = property.call(bar, function (d, i) {  });
        bar.barSpace = property.call(bar, 0);
        bar.groupSpace = property.call(bar, 10);
        //specifies whether or not text is shown on top of bars would usually return
        bar.columnText = property.call(bar, undefined);
        bar.showXAxis = property.call(bar, true);
        bar.showYAxis = property.call(bar, true);

        bar.render = function (id) {
            id = id || "body";
            var margin = bar.margin();
            var xfield = bar.xdata(), yfield = bar.ydata(), fillfunc = bar.fill();

            var ymax = d3.max(bar.data(), function (d) {
                return d3.max(d, function (n) {
                    if (bar.errorbar()) {
                        return bar.errorbar()(n) + yfield(n);
                    }
                    return yfield(n);
                });
            });
            //padding is a function of the length of the yaxis label
            var yrange = [0, ymax], bspace = bar.barSpace(), gspace = bar.groupSpace();
            var xdomain = bar.data()[0].map(xfield);
            var x = d3.scale.ordinal().rangeRoundBands([0, bar.width()], 0.15).domain(xdomain);
            var y = d3.scale.linear().range([0, bar.height()]).domain(yrange);
            var yaxisscale = d3.scale.linear().range([bar.height(), 0]).domain(yrange);
            var vis = d3.select(id).append("svg:svg")
                .attr("width", bar.width() + margin.left + margin.right)
                .attr("height", bar.height() + margin.top + margin.bottom);
            var gw = x.rangeBand(), bw = gw / bar.data().length;
            var g = vis.append("svg:g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
            var bgs = g.selectAll("g.bargroup").data(bar.data()[0]).enter()
                    .append("g").attr("class", "bargroup").attr("transform", function (d, i) {
                        return "translate(" + x(xfield(d, i)) + ")";
                    });
            var rectGroup = bgs.selectAll("g.rectgroup").data(function (d, i) {
                return bar.data().map(function (a) {
                    return a[i];
                });
            }).enter().append("g").attr("transform", function (d, i) {
                return "translate(" + (i * bw) + ")";
            });
            rectGroup.append("svg:rect").attr("width", bw - bspace)
                .attr("height", function (d, i) {
                    return y(yfield(d, i));
                }).attr("y", function (d, i) {
                    return bar.height() - y(yfield(d, i));
                }).attr("class", 'bar')
                .style("fill", fillfunc).style('stroke', function (d, i) {
                    return d3.rgb(fillfunc(d, i)).darker();
                }).on("click", bar.rectClicked()).append("title").text(function (d, i) {
                    return "x: " + xfield(d, i) + " y:" + yfield(d, i);
                });
            //if there is error bar function draw the error bars
            if (bar.errorbar()) {
                var errorbar = bar.errorbar();
                var bars = bgs.selectAll('line.errorbar').data(function (d, i) {
                    return bar.data().map(function (a) {
                        return a[i];
                    });
                }).enter();
                bars.append('line')
                    .attr("x1", function (d, i) {
                        return i * bw + (bw - bspace) / 2;
                    })
                    .attr("y1", function (d, i) {
                        var ebh = y(errorbar(d, i));//error bar height
                        return isNaN(ebh) ? 0 : bar.height() - y(yfield(d, i)) + ebh;
                    }).attr("x2", function (d, i) {
                        return i * bw + (bw - bspace) / 2;
                    })
                    .attr("y2", function (d, i) {
                        var ebh = y(errorbar(d, i));
                        return isNaN(ebh) ? 0 : bar.height() -  y(yfield(d, i)) - ebh;
                    })
                    .style("fill", "none")
                    .style("stroke", "#a22").style("stroke-width", 0.5);
                //bar hat
                bars.append('line')
                    .attr("x1", function (d, i) {
                        return i * bw + (bw - bspace) / 2  + bw / 4;
                    }).attr("x2", function (d, i) {
                        return i * bw + (bw - bspace) / 2  - bw / 4;
                    }).attr("y1", function (d, i) {
                        var ebh = y(errorbar(d, i));//error bar height
                        return isNaN(ebh) ? 0 : bar.height() - y(yfield(d, i)) + ebh;
                    }).attr("y2", function (d, i) {
                        var ebh = y(errorbar(d, i));//error bar height
                        return isNaN(ebh) ? 0 : bar.height() - y(yfield(d, i)) + ebh;
                    }).style("fill", "none")
                    .style("stroke", "#a22").style("stroke-width", 0.5);

                //bar bottom
                bars.append('line')
                    .attr("x1", function (d, i) {
                        return i * bw + (bw - bspace) / 2  + bw / 4;
                    }).attr("x2", function (d, i) {
                        return i * bw + (bw - bspace) / 2  - bw / 4;
                    }).attr("y1", function (d, i) {
                        var ebh = y(errorbar(d, i));
                        return isNaN(ebh) ? 0 : bar.height() -  y(yfield(d, i)) - ebh;
                    }).attr("y2", function (d, i) {
                        var ebh = y(errorbar(d, i));
                        return isNaN(ebh) ? 0 : bar.height() -  y(yfield(d, i)) - ebh;
                    }).style("fill", "none")
                    .style("stroke", "#a22").style("stroke-width", 0.5);
            }

            //if there is a column text draw it
            if (bar.columnText()) {
                var colText = bar.columnText();
                rectGroup.append("text")
                    .text(colText)
                    .attr("y", function (d, i) {
                        return bar.height() - y(yfield(d, i));
                    }).attr("x", bw / 2)
                    .attr("dy", "-10")
                    .style("text-anchor", "middle")
                    .style("alignment-baseline", "text-after-edge");
            }

            if (bar.showYAxis()) {
                var yaxis = d3.svg.axis().scale(yaxisscale).orient('left');
                g.append("svg:g")
                    .attr("class", "y axis")
                    .call(yaxis);
            }
            if (bar.showXAxis()) {
                var xaxis = d3.svg.axis().scale(x).tickSubdivide(true);
                var xg = g.append("svg:g")
                    .attr("class", 'x axis')
                    .attr("transform", "translate(0," + bar.height() + ")")
                    .call(xaxis);
                xg.selectAll("text").remove();
                //overriding the labels drawn by the svg.axis here so we can use word wrapping
                bgs.append("foreignObject")
                    .attr("width", gw).attr("height", 100)
                    .attr("x", 0).attr("y", bar.height() + 5)
                    .append("xhtml:body")
                    .style("text-align", "center")
                    .style("padding", 0).style("margin", 0)
                    .append("p").html(function (d, i) {
                        return xfield(d, i);
                    });
            }

            //render labels
            vis.append("g").attr("transform", "translate(" + margin.left + ")")
                .append("text")
                .text(bar.label()).attr("x", bar.width() / 2).attr("class", "chartlabel")
				.style("alignment-baseline", "text-before-edge").style("text-anchor", "middle");
            vis.append("g").attr("transform", "translate(" + margin.left + "," + (bar.height() + margin.top + margin.bottom / 2) + ")")
                .append("text").text(bar.xlabel()).style("text-anchor", "middle").style("alignment-baseline", "text-after-edge")
                .attr("class", "axislabel").attr("x", bar.width() / 2);

            vis.append("g").attr("transform", "translate(0," + margin.top + ")").append("text").text(bar.ylabel())
                .style("text-anchor", "middle").style("alignment-baseline", "text-before-edge")
                .attr("class", "axislabel").attr("x", 0).attr("y", bar.height() / 2)
                .attr("transform", "rotate(-90 0 " + (bar.height() / 2) + ")");

            //render legend if any
            if (bar.legend() && bar.legend().length > 0) {
                var keys = vis.append("g").attr('transform', 'translate(' + (pad + bar.width()) + ")")
                    .selectAll('g.key').data(bar.legend()).enter()
                    .append("g").attr("transform", function (d, i) {
                        return "translate(0, " + (pad + bar.legendheight() * i) + ")";
                    });

                keys.append("svg:rect").attr("width", bar.legendheight() * 0.75).attr("height", bar.legendheight() * 0.75)
                    .style('fill', fillfunc).style('stroke', function (d, i) {
                        return d3.rgb(fillfunc(d, i)).darker();
                    });
                keys.append("svg:text").attr("x", bar.legendheight())
                    .attr("y", bar.legendheight() / 2)
                    .text(String).style("alignment-baseline", 'text-after-edge')
                    .style("font-size", (0.65 * bar.legendheight()) + "px");
            }
            return vis;
        };
        return bar;
    }

    if (typeof module === "undefined") {
        self.bar = bar;
    } else {
        module.exports = bar;
    }
}());
<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';

const Leaderboard = React.createClass({

	componentWillMount() {
	this.props.getAllCharacters();
	},

	render() {
		var results = this.props.game.allChars;
		console.log('RESULT',results);
		console.log('props',this.props)

			return (

Continue

Leaderboard

						{results.map((char,i)=>

{char}
)}

			)
	}

})

export default Leaderboard;

         <commit_msg>cleaning up leaderboard component<commit_after>import React from 'react';
import { Link } from 'react-router';

const Leaderboard = React.createClass({

	componentWillMount() {
	this.props.getAllCharacters();
	},

	render() {
		var results = this.props.game.allChars;
		// console.log('RESULT',results);
		// console.log('props',this.props)

			return (

Leaderboard

						{results.map((char,i)=>

{char}
)}

			)
	}

})

export default Leaderboard;

         <|endoftext|>


<commit_before>import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { isPresent } from '@ember/utils';

export default class AddChatAccountXmppComponent extends Component {

  @service('sockethub-xmpp') xmpp;

  @tracked username;
  @tracked host = 'kosmos.org';
  @tracked password;
  @tracked connectError = null;

  get userAddress () {
    return `${this.username}@${this.host}`
  }

  handleConnectError (message) {
    console.debug('[add-chat-account-xmpp] handleConnectError called'); // TODO remove when unregistering handlers is fixed

    if (message.context === 'xmpp' && message['@type'] === 'error' &&
        message.object.condition === 'not-authorized'
    /* && TODO message.actor['@id'] === actor */) {
      this.connectError = {
        title: 'Account connection failed',
        content: message.object.content
      }
      this.unregisterConnectHandlers();
    }
  }

  handleConnectSuccess (message) {
    console.debug('[add-chat-account-xmpp] handleConnectSuccess called'); // TODO remove when unregistering handlers is fixed

    if (message.context === 'xmpp' && message['@type'] === 'connect' &&
        message.actor['@id'] === this.userAddress) {
      console.debug('[add-chat-account-xmpp] connected successfully') // TODO remove

      this.unregisterConnectHandlers();
    }
  }

  registerConnectHandlers () {
    this.xmpp.sockethub.socket._on('message', this.handleConnectError.bind(this));
    this.xmpp.sockethub.socket._on('completed', this.handleConnectSuccess.bind(this));
  }

  unregisterConnectHandlers () {
    // FIXME listeners are not being removed
    this.xmpp.sockethub.socket.off('message', this.handleConnectError.bind(this));
    this.xmpp.sockethub.socket.off('completed', this.handleConnectSuccess.bind(this));
  }

  @action
  submitForm (e) {
    e.preventDefault();
    this.connectError = null;
    this.registerConnectHandlers();
    this.xmpp.connectWithCredentials(this.userAddress, this.password);
  }

}
<commit_msg>Use socket.onAny for ad-hoc listeners<commit_after>import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { isPresent } from '@ember/utils';

export default class AddChatAccountXmppComponent extends Component {

  @service('sockethub-xmpp') xmpp;

  @tracked username;
  @tracked host = 'kosmos.org';
  @tracked password;
  @tracked connectError = null;

  get userAddress () {
    return `${this.username}@${this.host}`
  }

  handleConnectStatus (eventName, message) {
    console.debug('[add-chat-account-xmpp] handleConnectStatus called') // TODO remove

    if (message.context !== 'xmpp' ||
        !['message', 'completed'].includes(eventName)) { return; }

    if (message['@type'] === 'error' &&
        message.object.condition === 'not-authorized'
        /* && TODO message.actor['@id'] === actor */) {
      this.connectError = {
        title: 'Account connection failed',
        content: message.object.content
      }
      this.xmpp.sockethub.socket.offAny();
    }

    if (message['@type'] === 'connect' &&
        message.actor['@id'] === this.userAddress) {
      console.debug('[add-chat-account-xmpp] connected successfully') // TODO remove
      this.xmpp.sockethub.socket.offAny();
    }
  }

  @action
  submitForm (e) {
    e.preventDefault(); this.connectError = null; this.xmpp.sockethub.socket.onAny(this.handleConnectStatus.bind(this));
    this.xmpp.connectWithCredentials(this.userAddress, this.password);
  }

}
<|endoftext|>