<commit_before>var locastyle = locastyle || {};
locastyle.general = (function() {
  'use strict';

  var events = {
    '[data-toggle-class]|click': _toggleClass,
    '[data-toggle-text]|click': _toggleText,
    '.ls-link-smooth|click': _smoothScroll
  }

  function init() {
    _loadEvents();
    showSidebar();
    showNotifications();
    subMenu();
    _locationHashTrigger();
    _elementDisabled();
    _linkPreventDefault();
    _btnGroupActivationToogle();
    menuAnchor();
    toggleFields();
  }

  function toggleFields(){
    $('[data-ls-toggle-fields]').on('click', function(evt) {
      evt.preventDefault();
      var $this = $(this);
      var $container = $($this.data('ls-toggle-fields'));
      $container
        .toggleClass('ls-form-disable')
        .toggleClass('ls-form-text');
      $container
        .find(':input').toggleClass('ls-form-text')
        .toggleAttr('disabled');
    });
  }

  function _loadEvents() {
    $.each(events, function(eventDesc, fn) {
      var selectorEvent = eventDesc.split('|')
      $(selectorEvent[0]).on(selectorEvent[1], selectorEvent[2], function(evt) {
        var $this = $(this);
        fn(evt, $this);
      });
    });
  }

  function menuAnchor() {
    $(".ls-active").focus().css('outline', 'none')
  }

  function _toggleClass(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
      cssClass = $this.data('toggle-class');
    $target.toggleClass(cssClass);
  }

  function _toggleText(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target-text') ? $($this.data('target-text')) : $this,
      textChange = $this.data('toggle-text'),
      textOriginal = $target.text();
    $this.data('toggle-text', textOriginal);
    $target.text(textChange);
  }

  function _smoothScroll(evt, $this) {
    evt.preventDefault();
    var $target = $($this.attr('href'));
    if ($target[0]) {
      $('html,body').animate({
        scrollTop: $target.offset().top - 70
      }, 1000);
    }
  }

  function _locationHashTrigger() {
    if (window.location.hash) {
      $('a[class*="ls-"][href="' + window.location.hash + '"]').trigger('click');
    }
  }

  function showSidebar() {
    var $showHide = $('.show-sidebar');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt) {
      $html.toggleClass('sidebar-visible');
      evt.preventDefault();
    });
  }

  function showNotifications() {
    var $showHide = $('.show-notifications');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt) {
      $html.toggleClass('notifications-visible');
      evt.preventDefault();
    });
  }

  function subMenu() {
    $('.ls-submenu > a').on('click', function(evt) {
      $(this).parent().toggleClass('active');
      evt.preventDefault();
    })
    if($('.ls-submenu-item').hasClass('active')){
      console.log($('.ls-submenu-item').closest('ul').parent().addClass('active'))
    }
  }

  function _elementDisabled() {
    var $elementDisabled = $('.disabled') || [disabled = 'disabled'];
    $elementDisabled.on('click', function(evt) {
      evt.preventDefault();
    });
  }

  function _linkPreventDefault(dom_scope) {
    $("a", dom_scope).on("click", function(e) {
      if ($(this).attr("href") === "" || $(this).attr("href") === "#") {
        e.preventDefault();
      }
    });
  }

  function _btnGroupActivationToogle() {
    $(".ls-group-active .ls-btn").on("click", function() {
      $(this).siblings().removeClass("active");
      $(this).addClass("active");
    });
  }

  jQuery.fn.toggleAttr = function(attr) {
    return this.each(function() {
      var $this = $(this);
      $this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
    });
  };

  return {
    init: init
  };

}());
<commit_msg>helper fn same height<commit_after>var locastyle = locastyle || {};
locastyle.general = (function() {
  'use strict';

  var events = {
    '[data-toggle-class]|click': _toggleClass,
    '[data-toggle-text]|click': _toggleText,
    '.ls-link-smooth|click': _smoothScroll
  }

  function init() {
    _loadEvents();
    showSidebar();
    showNotifications();
    subMenu();
    _locationHashTrigger();
    _elementDisabled();
    _linkPreventDefault();
    _btnGroupActivationToogle();
    menuAnchor();
    toggleFields();
    equalHeight();
  }

  function equalHeight () {
    $('[data-ls-target-height]').each(function (i, elem) {
      var selector = $(this).data('ls-target-height')
      var heightMain = $(this).height();
      $(selector).height(heightMain);
    });
  }

  function toggleFields(){
    $('[data-ls-toggle-fields]').on('click', function(evt) {
      evt.preventDefault();
      var $this = $(this);
      var $container = $($this.data('ls-toggle-fields'));
      $container
        .toggleClass('ls-form-disable')
        .toggleClass('ls-form-text');
      $container
        .find(':input').toggleClass('ls-form-text')
        .toggleAttr('disabled');
    });
  }

  function _loadEvents() {
    $.each(events, function(eventDesc, fn) {
      var selectorEvent = eventDesc.split('|')
      $(selectorEvent[0]).on(selectorEvent[1], selectorEvent[2], function(evt) {
        var $this = $(this);
        fn(evt, $this);
      });
    });
  }

  function menuAnchor() {
    $(".ls-active").focus().css('outline', 'none')
  }

  function _toggleClass(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
      cssClass = $this.data('toggle-class');
    $target.toggleClass(cssClass);
  }

  function _toggleText(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target-text') ? $($this.data('target-text')) : $this,
      textChange = $this.data('toggle-text'),
      textOriginal = $target.text();
    $this.data('toggle-text', textOriginal);
    $target.text(textChange);
  }

  function _smoothScroll(evt, $this) {
    evt.preventDefault();
    var $target = $($this.attr('href'));
    if ($target[0]) {
      $('html,body').animate({
        scrollTop: $target.offset().top - 70
      }, 1000);
    }
  }

  function _locationHashTrigger() {
    if (window.location.hash) {
      $('a[class*="ls-"][href="' + window.location.hash + '"]').trigger('click');
    }
  }

  function showSidebar() {
    var $showHide = $('.show-sidebar');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt) {
      $html.toggleClass('sidebar-visible');
      evt.preventDefault();
    });
  }

  function showNotifications() {
    var $showHide = $('.show-notifications');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt) {
      $html.toggleClass('notifications-visible');
      evt.preventDefault();
    });
  }

  function subMenu() {
    $('.ls-submenu > a').on('click', function(evt) {
      $(this).parent().toggleClass('active');
      evt.preventDefault();
    })
    if($('.ls-submenu-item').hasClass('active')){
      console.log($('.ls-submenu-item').closest('ul').parent().addClass('active'))
    }
  }

  function _elementDisabled() {
    var $elementDisabled = $('.disabled') || [disabled = 'disabled'];
    $elementDisabled.on('click', function(evt) {
      evt.preventDefault();
    });
  }

  function _linkPreventDefault(dom_scope) {
    $("a", dom_scope).on("click", function(e) {
      if ($(this).attr("href") === "" || $(this).attr("href") === "#") {
        e.preventDefault();
      }
    });
  }

  function _btnGroupActivationToogle() {
    $(".ls-group-active .ls-btn").on("click", function() {
      $(this).siblings().removeClass("active");
      $(this).addClass("active");
    });
  }

  jQuery.fn.toggleAttr = function(attr) {
    return this.each(function() {
      var $this = $(this);
      $this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
    });
  };

  return {
    init: init
  };

}());
<|endoftext|>


<commit_before>const m = require('mithril');

const LogModel = require('../models/log');
const datetime = require('../utils/dateFormat');

const Logs = module.exports = {
  logs: m.prop()
};

const parse = (logs) => logs.map(
    function (log) {
      let msg = datetime.toShortDateTime(log.timestamp()) + ' - ' +
          log.level() + ': [' + log.label() + '] ' + log.message();

      if (log.meta()) {
        msg += ' ' + JSON.stringify(log.meta());
      }

      return msg;
    }
);

Logs.controller = function () {
  Logs.logs = LogModel.list().then(parse);
};

Logs.view = function () {
  return [
    m('h1', 'Logs'),
    m('div.col s12',
        Logs.logs().reverse().map((l) => m('p', l))
    )
  ];
};
<commit_msg>Display logs in table<commit_after>const m = require('mithril');

const DataDisplay = require('../components/datadisplay');
const LogModel = require('../models/log');

const Logs = module.exports = {
  logs: m.prop()
};

const names = {
  time: 'Timestamp',
  level: 'Level',
  label: 'File',
  msg: 'Message',
  meta: 'Metadata'
};

const parse = (logs) => logs.map(
    function (log) {
      return {
        time: log.timestamp().toUTCString(),
        level: log.level(),
        label: log.label(),
        msg: log.message(),
        meta: log.meta() ? JSON.stringify(log.meta()) : ''
      };
    }
);

Logs.controller = function () {
  Logs.logs = LogModel.list().then(parse);
};

Logs.view = function () {
  return [
    m('h1', 'Logs'),
    m(DataDisplay, {
      names: names,
      data: Logs.logs
    })
  ];
};
<|endoftext|>


<commit_before>TAM_MAX = 255;

first_test = false;

function reavaliar (){

    if (first_test){
        validacao();
    }
}

function validacao(){

   valida=true;

    // Validacao do campo nascimento--------------------------------------------
    var nascimento = document.form.nascimento.value;
    var regexp = /[0-9]{2}-[0-9]{2}-[0-9]{4}/g;

    //se nascimento for diferente de vazio valida o que esta escrito. e se for vazio deixa passar
    if (nascimento != ""){
        if (nascimento.length != 10 || !regexp.test(nascimento)){
            document.form.nascimento.focus();
            document.getElementById("nascimento-msg").innerHTML="Data inválida.
Tente novamente no Formato: (DD-MM-AAAA)";
            valida = false;
        }
    }else {
        document.getElementById("nascimento-msg").innerHTML="";
    }
    //--------------------------------------------------------------------------

   //validacao do campo email--------------------------------------------------
    var email = document.form.email.value;
    usuario = email.substring(0, email.indexOf("@"));
    dominio = email.substring(email.indexOf("@")+ 1, email.length);

    if (email== ""){
        document.form.email.focus();
        document.getElementById("email-msg").innerHTML="*Obrigatório";
        valida = false;
    } else if (email.length > TAM_MAX){
        document.form.email.focus();
        document.getElementById("email-msg").innerHTML="*Email muito grande. Respeite o limite maximo de " + TAM_MAX +" caracteres.";
        valida = false;
    }else if ( email.indexOf("@") == -1 || email.indexOf(".") == -1 ||
             usuario.length <= 2 || dominio.length <= 2){

            document.form.email.focus();
            document.getElementById("email-msg").innerHTML="Email inválido.
Requerido: usuario@dominio.com";
            valida = false;
    } else {
        document.getElementById("email-msg").innerHTML="";
    }
    //--------------------------------------------------------------------------

   //validacao do campo nome ---------------------------------------------------
      var nome = document.form.nome.value;

        //verifica se o campo nome esta vazio
        if (nome=="" ){
            //alert ("Por favor preencher o campo nome.");
            document.form.nome.focus();
            document.getElementById("nome-msg").innerHTML="*Obrigatório";
            valida=false;

        //verifica se a quantidade de caracteres inseridos ´é menor que umtamanho maximo
        }else if (nome.length > TAM_MAX){
            //alert ("Por favor preencha um nome com no máximo 255 letras.");
            document.getElementById("nome-msg").innerHTML="Nome deve ter no máximo " + TAM_MAX + " caracteres.";
            document.form.nome.focus();
            valida =false;
        }else {
            document.getElementById("nome-msg").innerHTML="";
        }

    //--------------------------------------------------------------------------

    first_test=true;
    return valida;

}

<commit_msg>comentarios do javascript<commit_after>TAM_MAX = 255;

first_test = false;

//na primeira interaco do usuario, a funcao de validacao so e chamada pelo botao de cadastrar.
//Depoisde acionado o botao a cada alteracao de campo a funcao reavaliar eh ativada.

//a funcao reavalir eh chamada a cada alteracao no formulario
function reavaliar (){
    //só entra no loop depois que a funcao de validacao ja foi chamada pelo menos uma vez pelo botao de cadastrar
    if (first_test){
        validacao();
    }
}

//funcao que valida os campos do formulario
function validacao(){

   //variavel de controle. Se alguma validcao nao passa essa variavel se torna false
   valida=true;

    // Validacao do campo nascimento--------------------------------------------
    var nascimento = document.form.nascimento.value;
    var regexp = /[0-9]{2}-[0-9]{2}-[0-9]{4}/g;

    //se nascimento for diferente de vazio valida o que esta escrito. e se for vazio deixa passar
    if (nascimento != ""){
        if (nascimento.length != 10 || !regexp.test(nascimento)){
            document.form.nascimento.focus();
            document.getElementById("nascimento-msg").innerHTML="Data inválida.
Tente novamente no Formato: (DD-MM-AAAA)";
            valida = false;
        }
    }else {
        document.getElementById("nascimento-msg").innerHTML="";
    }
    //--------------------------------------------------------------------------

   //validacao do campo email--------------------------------------------------
    var email = document.form.email.value;
    usuario = email.substring(0, email.indexOf("@"));
    dominio = email.substring(email.indexOf("@")+ 1, email.length);

    if (email== ""){
        document.form.email.focus();
        document.getElementById("email-msg").innerHTML="*Obrigatório";
        valida = false;
    } else if (email.length > TAM_MAX){
        document.form.email.focus();
        document.getElementById("email-msg").innerHTML="*Email muito grande. Respeite o limite maximo de " + TAM_MAX +" caracteres.";
        valida = false;
    }else if ( email.indexOf("@") == -1 || email.indexOf(".") == -1 ||
             usuario.length <= 2 || dominio.length <= 2){

            document.form.email.focus();
            document.getElementById("email-msg").innerHTML="Email inválido.
Requerido: usuario@dominio.com";
            valida = false;
    } else {
        document.getElementById("email-msg").innerHTML="";
    }
    //--------------------------------------------------------------------------

   //validacao do campo nome ---------------------------------------------------
      var nome = document.form.nome.value;

        //verifica se o campo nome esta vazio
        if (nome=="" ){
            //alert ("Por favor preencher o campo nome.");
            document.form.nome.focus();
            document.getElementById("nome-msg").innerHTML="*Obrigatório";
            valida=false;

        //verifica se a quantidade de caracteres inseridos ´é menor que umtamanho maximo
        }else if (nome.length > TAM_MAX){
            //alert ("Por favor preencha um nome com no máximo 255 letras.");
            document.getElementById("nome-msg").innerHTML="Nome deve ter no máximo " + TAM_MAX + " caracteres.";
            document.form.nome.focus();
            valida =false;
        }else {
            document.getElementById("nome-msg").innerHTML="";
        }

    //--------------------------------------------------------------------------

    first_test=true;
    return valida;

}

<|endoftext|>


<commit_before>export default async function babelTransform(code) {
  return (await import(
    /* webpackChunkName: "babelTransform" */
    /* webpackMode: "lazy" */
    /* webpackPrefetch: true */
    './babelTransformChunk'
  )).default(code);
}
<commit_msg>perf: Preload babel transform chunk<commit_after>export default async function babelTransform(code) {
  return (await import(
    /* webpackChunkName: "babelTransform" */
    /* webpackPreload: true */
    './babelTransformChunk'
  )).default(code);
}
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _axios = require('axios');

var _axios2 = _interopRequireDefault(_axios);

var _cryptoJs = require('crypto-js');

var _cryptoJs2 = _interopRequireDefault(_cryptoJs);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var isMissing = function isMissing(param) {
  throw new Error('Missing parameter "' + param + '"');
};

var BFXRest = function () {

  /**
   * constructor
   *
   * @param {object} required (API_KEY, API_SECRET)
   */
  function BFXRest(_ref) {
    var API_KEY = _ref.API_KEY,
        API_SECRET = _ref.API_SECRET;
    (0, _classCallCheck3.default)(this, BFXRest);

    this.apiKey = API_KEY;
    this.apiSecret = API_SECRET;
    this.version = 'v1';
    this.baseUrl = 'https://api.bitfinex.com';
  }

  /**
   * _nonce - Nonce generator
   *
   * @return {number}  Incremented nonce
   */

  (0, _createClass3.default)(BFXRest, [{
    key: '_nonce',
    value: function _nonce() {
      return new Date().getTime();
    }

    /**
     * _authReq - Make request params and headers
     *
     * @param  {string} path    Path to api endpoint
     * @param  {object} params  Params for post request
     * @return {promise}        Request promise
     */

  }, {
    key: '_authReq',
    value: function _authReq(path, params) {
      var url = this.baseUrl + '/' + this.version + '/' + path;

      var body = {
        request: '/' + this.version + '/' + path,
        nonce: (0, _stringify2.default)(this._nonce())
      };

      if (!_lodash2.default.isEmpty(params)) {
        _lodash2.default.map(params, function (paramVal, paramKey) {
          body[paramKey] = paramVal;
        });
      }

      var payload = new Buffer((0, _stringify2.default)(body)).toString('base64');

      var signature = _cryptoJs2.default.HmacSHA384(payload, this.apiSecret).toString(_cryptoJs2.default.enc.Hex);

      var headers = {
        'X-BFX-APIKEY': this.apiKey,
        'X-BFX-PAYLOAD': payload,
        'X-BFX-SIGNATURE': signature
      };

      return _axios2.default.post(url, {}, {
        headers: headers
      }).then(function (_ref2) {
        var data = _ref2.data;

        if (data.message) {
          throw new Error(data.message);
        }

        return data;
      });
    }

    /**
     * balance - Current balance of wallets
     *
     * @return {array}  Array of wallets
     */

  }, {
    key: 'walletBalance',
    value: function walletBalance() {
      return this._authReq('balances');
    }
  }, {
    key: 'newOrder',
    value: function newOrder() {
      var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref3$symbol = _ref3.symbol,
          symbol = _ref3$symbol === undefined ? isMissing('symbol') : _ref3$symbol,
          _ref3$amount = _ref3.amount,
          amount = _ref3$amount === undefined ? isMissing('amount') : _ref3$amount,
          _ref3$price = _ref3.price,
          price = _ref3$price === undefined ? isMissing('price') : _ref3$price,
          _ref3$exchange = _ref3.exchange,
          exchange = _ref3$exchange === undefined ? isMissing('exchange') : _ref3$exchange,
          _ref3$side = _ref3.side,
          side = _ref3$side === undefined ? isMissing('side') : _ref3$side,
          _ref3$type = _ref3.type,
          type = _ref3$type === undefined ? isMissing('type') : _ref3$type,
          _ref3$post_only = _ref3.post_only,
          post_only = _ref3$post_only === undefined ? false : _ref3$post_only,
          _ref3$is_hidden = _ref3.is_hidden,
          is_hidden = _ref3$is_hidden === undefined ? false : _ref3$is_hidden;

      var params = {
        symbol: symbol,
        amount: amount,
        price: price,
        exchange: exchange,
        side: side,
        type: type,
        post_only: post_only,
        is_hidden: is_hidden
      };

      // return this._authReq('order/new', params);

      console.log('params', params);
    }
  }, {
    key: 'newMultipleOrders',
    value: function newMultipleOrders() {
      var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref4$orders = _ref4.orders,
          orders = _ref4$orders === undefined ? isMissing('orders') : _ref4$orders;

      if (_lodash2.default.isEmpty(orders) || !_lodash2.default.isArray(orders)) {
        throw new Error('Orders is empty or is not array');
      }

      var params = {
        orders: orders
      };

      return this._authReq('order/new/multi', params);
    }
  }, {
    key: 'cancelOrder',
    value: function cancelOrder() {
      var _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref5$order_id = _ref5.order_id,
          order_id = _ref5$order_id === undefined ? isMissing('order_id') : _ref5$order_id;

      var params = {
        order_id: order_id
      };

      return this._authReq('order/cancel', params);
    }
  }, {
    key: 'cancelMultipleOrders',
    value: function cancelMultipleOrders() {
      var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref6$orders = _ref6.orders,
          orders = _ref6$orders === undefined ? isMissing('orders') : _ref6$orders;

      var params = {
        order_ids: _lodash2.default.map(orders, function (order) {
          return +order.id;
        })
      };

      return this._authReq('order/cancel/multi', params);
    }
  }, {
    key: 'cancelAllOrders',
    value: function cancelAllOrders() {
      return this._authReq('order/cancel/all');
    }
  }, {
    key: 'activeOrders',
    value: function activeOrders() {
      return this._authReq('orders');
    }
  }, {
    key: 'ordersHistory',
    value: function ordersHistory() {
      return this._authReq('orders/hist');
    }
  }]);
  return BFXRest;
}();

;

exports.default = BFXRest;<commit_msg>build api<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _axios = require('axios');

var _axios2 = _interopRequireDefault(_axios);

var _cryptoJs = require('crypto-js');

var _cryptoJs2 = _interopRequireDefault(_cryptoJs);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var isMissing = function isMissing(param) {
  throw new Error('Missing parameter "' + param + '"');
};

var BFXRest = function () {

  /**
   * constructor
   *
   * @param {object} required (API_KEY, API_SECRET)
   */
  function BFXRest(_ref) {
    var API_KEY = _ref.API_KEY,
        API_SECRET = _ref.API_SECRET;
    (0, _classCallCheck3.default)(this, BFXRest);

    this.apiKey = API_KEY;
    this.apiSecret = API_SECRET;
    this.version = 'v1';
    this.baseUrl = 'https://api.bitfinex.com';
  }

  /**
   * _nonce - Nonce generator
   *
   * @return {number}  Incremented nonce
   */

  (0, _createClass3.default)(BFXRest, [{
    key: '_nonce',
    value: function _nonce() {
      return new Date().getTime();
    }

    /**
     * _authReq - Make request params and headers
     *
     * @param  {string} path    Path to api endpoint
     * @param  {object} params  Params for post request
     * @return {promise}        Request promise
     */

  }, {
    key: '_authReq',
    value: function _authReq(path, params) {
      var url = this.baseUrl + '/' + this.version + '/' + path;

      var body = {
        request: '/' + this.version + '/' + path,
        nonce: (0, _stringify2.default)(this._nonce())
      };

      if (!_lodash2.default.isEmpty(params)) {
        _lodash2.default.map(params, function (paramVal, paramKey) {
          body[paramKey] = paramVal;
        });
      }

      var payload = new Buffer((0, _stringify2.default)(body)).toString('base64');

      var signature = _cryptoJs2.default.HmacSHA384(payload, this.apiSecret).toString(_cryptoJs2.default.enc.Hex);

      var headers = {
        'X-BFX-APIKEY': this.apiKey,
        'X-BFX-PAYLOAD': payload,
        'X-BFX-SIGNATURE': signature
      };

      return _axios2.default.post(url, {}, {
        headers: headers
      }).then(function (_ref2) {
        var data = _ref2.data;

        if (data.message) {
          throw new Error(data.message);
        }

        return data;
      });
    }
  }, {
    key: '_pubReq',
    value: function _pubReq(path) {
      var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      var url = this.baseUrl + '/' + this.version + '/' + path;

      return _axios2.default.get(url, {
        params: params
      });
    }

    /**
     * balance - Current balance of wallets
     *
     * @return {array}  Array of wallets
     */

  }, {
    key: 'walletBalance',
    value: function walletBalance() {
      return this._authReq('balances');
    }
  }, {
    key: 'newOrder',
    value: function newOrder() {
      var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref3$symbol = _ref3.symbol,
          symbol = _ref3$symbol === undefined ? isMissing('symbol') : _ref3$symbol,
          _ref3$amount = _ref3.amount,
          amount = _ref3$amount === undefined ? isMissing('amount') : _ref3$amount,
          _ref3$price = _ref3.price,
          price = _ref3$price === undefined ? isMissing('price') : _ref3$price,
          _ref3$exchange = _ref3.exchange,
          exchange = _ref3$exchange === undefined ? isMissing('exchange') : _ref3$exchange,
          _ref3$side = _ref3.side,
          side = _ref3$side === undefined ? isMissing('side') : _ref3$side,
          _ref3$type = _ref3.type,
          type = _ref3$type === undefined ? isMissing('type') : _ref3$type,
          _ref3$post_only = _ref3.post_only,
          post_only = _ref3$post_only === undefined ? false : _ref3$post_only,
          _ref3$is_hidden = _ref3.is_hidden,
          is_hidden = _ref3$is_hidden === undefined ? false : _ref3$is_hidden;

      var params = {
        symbol: symbol,
        amount: amount,
        price: price,
        exchange: exchange,
        side: side,
        type: type,
        post_only: post_only,
        is_hidden: is_hidden
      };

      return this._authReq('order/new', params);
    }
  }, {
    key: 'newMultipleOrders',
    value: function newMultipleOrders() {
      var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref4$orders = _ref4.orders,
          orders = _ref4$orders === undefined ? isMissing('orders') : _ref4$orders;

      if (_lodash2.default.isEmpty(orders) || !_lodash2.default.isArray(orders)) {
        throw new Error('Orders is empty or is not array');
      }

      var params = {
        orders: orders
      };

      return this._authReq('order/new/multi', params);
    }
  }, {
    key: 'cancelOrder',
    value: function cancelOrder() {
      var _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref5$order_id = _ref5.order_id,
          order_id = _ref5$order_id === undefined ? isMissing('order_id') : _ref5$order_id;

      var params = {
        order_id: order_id
      };

      return this._authReq('order/cancel', params);
    }
  }, {
    key: 'cancelMultipleOrders',
    value: function cancelMultipleOrders() {
      var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref6$orders = _ref6.orders,
          orders = _ref6$orders === undefined ? isMissing('orders') : _ref6$orders;

      var params = {
        order_ids: _lodash2.default.map(orders, function (order) {
          return +order.id;
        })
      };

      return this._authReq('order/cancel/multi', params);
    }
  }, {
    key: 'cancelAllOrders',
    value: function cancelAllOrders() {
      return this._authReq('order/cancel/all');
    }
  }, {
    key: 'activeOrders',
    value: function activeOrders() {
      return this._authReq('orders');
    }
  }, {
    key: 'ordersHistory',
    value: function ordersHistory() {
      return this._authReq('orders/hist');
    }
  }, {
    key: 'ticker',
    value: function ticker(symbol) {
      return this._pubReq('pubticker/' + symbol);
    }
  }, {
    key: 'symbols',
    value: function symbols() {
      return this._pubReq('symbols');
    }
  }, {
    key: 'symbolDitails',
    value: function symbolDitails() {
      return this._pubReq('symbols_details');
    }
  }, {
    key: 'trades',
    value: function trades(symbol) {
      return this._pubReq('trades/' + symbol);
    }
  }, {
    key: 'stats',
    value: function stats(symbol) {
      return this._pubReq('stats/' + symbol);
    }
  }]);
  return BFXRest;
}();

;

exports.default = BFXRest;<|endoftext|>


<commit_before>var CONFIG = require("./config.js");
var CONSTANTS = require("./constants.js");
var util = require("./util.js");
var bidManager = require("./bidManager.js");
// todo: how we can do it optionally (include only iff required) ?
var prebid = require("./adapters/prebid.js");

var registeredAdapters = {};

/* start-test-block */
exports.registeredAdapters = registeredAdapters;
/* end-test-block */

var refThis = this;

// when this function executes, it is only called for prebid adapter; we can remove this flow totally
exports.callAdapters = function(activeSlots){
	var impressionID = util.generateUUID();
	refThis.resetSlots(activeSlots, impressionID);
	refThis.callAdapter(registeredAdapters, activeSlots, impressionID);
};

// when this function executes, it is only called for prebid adapter; we can remove this flow totally
function callAdapter(adapters, slots, impressionID){
	util.forEachOnObject(adapters, function(adapterID, theAdapter){
		//Note: if you have any other parent-adapter like prebid, and
		//		want to add throttling on the parent-adapters then
		//		you will need to add throttling logic here as well
		refThis.setInitTimeForSlotsForAdapter(slots, adapterID);
		theAdapter.fB(slots, impressionID);
	});
}

/* start-test-block */
exports.callAdapter = callAdapter;
/* end-test-block */

// todo: this function can be moved to bidManager
function resetSlots(slots, impressionID){
	util.forEachOnArray(slots, function(key, slot){
		var divID = slot.getDivID();
		bidManager.resetBid(divID, impressionID);
		bidManager.setSizes(divID, util.generateSlotNamesFromPattern(slot, "_W_x_H_"));
	});
}

/* start-test-block */
exports.resetSlots = resetSlots;
/* end-test-block */

// this function is also called by adapters/Prebid to log the init time
// todo: this function can be moved to adapters/prebid
function setInitTimeForSlotsForAdapter(slots, adapterID){
	util.forEachOnObject(slots, function(j, slot){
		bidManager.setCallInitTime(slot.getDivID(), adapterID);
	});
}

exports.setInitTimeForSlotsForAdapter = setInitTimeForSlotsForAdapter;

function registerAdapter(bidAdaptor) {
	if (bidAdaptor) {
		var adapterID = bidAdaptor.ID();
		if (util.isFunction(bidAdaptor.fB)){
			refThis.registeredAdapters[adapterID] = bidAdaptor;
		} else {
			util.log(adapterID + CONSTANTS.MESSAGES.M3);
		}
	} else {
		util.log(CONSTANTS.MESSAGES.M3);
		util.log(bidAdaptor);
	}
}

/* start-test-block */
exports.registerAdapter = registerAdapter;
/* end-test-block */

function registerAdapters(){
	refThis.registerAdapter(prebid.register());
};

exports.registerAdapters = registerAdapters;
<commit_msg>all functions in adapterManager are marked as not in use<commit_after>var CONFIG = require("./config.js");
var CONSTANTS = require("./constants.js");
var util = require("./util.js");
var bidManager = require("./bidManager.js");
// todo: how we can do it optionally (include only iff required) ?
var prebid = require("./adapters/prebid.js");

var registeredAdapters = {};

/* start-test-block */
exports.registeredAdapters = registeredAdapters;
/* end-test-block */

var refThis = this;

// when this function executes, it is only called for prebid adapter; we can remove this flow totally
// todo: this function can be removed
exports.callAdapters = function(activeSlots){
	var impressionID = util.generateUUID();
	refThis.resetSlots(activeSlots, impressionID);
	refThis.callAdapter(registeredAdapters, activeSlots, impressionID);
};

// when this function executes, it is only called for prebid adapter; we can remove this flow totally
// todo: this function can be removed
function callAdapter(adapters, slots, impressionID){
	util.forEachOnObject(adapters, function(adapterID, theAdapter){
		//Note: if you have any other parent-adapter like prebid, and
		//		want to add throttling on the parent-adapters then
		//		you will need to add throttling logic here as well
		refThis.setInitTimeForSlotsForAdapter(slots, adapterID);
		theAdapter.fB(slots, impressionID);
	});
}

/* start-test-block */
exports.callAdapter = callAdapter;
/* end-test-block */

// todo: this function can be removed
function resetSlots(slots, impressionID){
	util.forEachOnArray(slots, function(key, slot){
		var divID = slot.getDivID();
		bidManager.resetBid(divID, impressionID);
		bidManager.setSizes(divID, util.generateSlotNamesFromPattern(slot, "_W_x_H_"));
	});
}

/* start-test-block */
exports.resetSlots = resetSlots;
/* end-test-block */

// this function is also called by adapters/Prebid to log the init time
// todo: this function can be removed
function setInitTimeForSlotsForAdapter(slots, adapterID){
	util.forEachOnObject(slots, function(j, slot){
		bidManager.setCallInitTime(slot.getDivID(), adapterID);
	});
}

exports.setInitTimeForSlotsForAdapter = setInitTimeForSlotsForAdapter;

// todo: this function can be removed
function registerAdapter(bidAdaptor) {
	if (bidAdaptor) {
		var adapterID = bidAdaptor.ID();
		if (util.isFunction(bidAdaptor.fB)){
			refThis.registeredAdapters[adapterID] = bidAdaptor;
		} else {
			util.log(adapterID + CONSTANTS.MESSAGES.M3);
		}
	} else {
		util.log(CONSTANTS.MESSAGES.M3);
		util.log(bidAdaptor);
	}
}

/* start-test-block */
exports.registerAdapter = registerAdapter;
/* end-test-block */

// todo: this function can be removed
function registerAdapters(){
	refThis.registerAdapter(prebid.register());
};

exports.registerAdapters = registerAdapters;
<|endoftext|>


<commit_before>import { SpritePlayer, SpriteBullet, ShootSound } from "../SpriteConstants";
import { CharacterWitdh, CharacterHeight, DirectionBoomerang } from "../Constants";

const Damage = 10;
const Velocity = 200;
const MaxBullet = 10;
const TimeLapse = 10;
const MaxLife = 1000;

class Character extends Phaser.Sprite {

  constructor(game, x, y, key, frame) {
    super(game, x, y, SpritePlayer, frame);
    game.physics.arcade.enable(this);
    //this.body.gravity.y = 500;
    this.body.bounce.x = this.body.bounce.y = 0;
    this.body.mass = 1;
    this.direction = 1;
    this.anchor.setTo(0.5, 0.5);
    this.life = MaxLife;

    const fire = [8, 9, 10, 11];
    const walk = [0, 1, 2, 3, 4, 5, 6, 7];
    const slide = [12, 13, 14, 15, 14, 13, 12];

    this.animations.add('walk', walk, TimeLapse, false);
    this.animations.add('slide', slide, TimeLapse, false);
    this.animations.add('fire', fire, TimeLapse * 6, false);

    this.weapon = game.add.weapon(MaxBullet, SpriteBullet);
    this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
    this.weapon.bulletAngleOffset = 90;
    //this.weapon.addBulletAnimation("fire", fire, TimeLapse, true);
    this.weapon.bulletAngleVariance = 5;
    this.weapon.bulletSpeed = 500;
    this.weapon.fireRate = 300;

    this.weapon.trackSprite(this, 30, 20, true);
    this.shootFx = game.add.audio(ShootSound);
    this.shootFx.allowMultiple = true;
    this.shootFx.addMarker('shootMarker', 0, 0.3);

    this.pad = this.game.input.gamepad.pad1;
    this.cursor = game.input.keyboard.createCursorKeys();

    this.fireButton = game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR);
    this.fireClick = game.input.activePointer.leftButton;

    this.up = game.input.keyboard.addKey(Phaser.Keyboard.Z);
    this.leftKey = game.input.keyboard.addKey(Phaser.Keyboard.Q);
    this.rightKey = game.input.keyboard.addKey(Phaser.Keyboard.D);
    this.down = game.input.keyboard.addKey(Phaser.Keyboard.S);

    this.lastDirection = null;
  }

  update() {
    if(!this.isDeath()) {
      this.body.velocity.x = 0;
      this.body.velocity.y = 0;
      this.rotation = this.game.physics.arcade.angleToPointer(this);
      let move = null;
      //console.log(this.angle)

      if (this.cursor.left.isDown || this.leftKey.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1 ) {
          this.body.velocity.x = -Velocity;
          this.direction = -1;
          this.lastDirection = DirectionBoomerang.left;
          move = "left";
      }
      else if (this.cursor.right.isDown || this.rightKey.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.1) {
          this.body.velocity.x = Velocity;
          this.direction = 1;
          this.lastDirection = DirectionBoomerang.right;
          move = "right";
      }

      if (this.cursor.up.isDown || this.up.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) < -0.1) {
        this.body.velocity.y = -Velocity;
        this.lastDirection = DirectionBoomerang.up;
        move = "up";
      } else if (this.cursor.down.isDown || this.down.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) > 0.1) {
        this.body.velocity.y = Velocity;
        this.lastDirection = DirectionBoomerang.down;
        move = "down";
      }

      if(this.fireButton.isDown || this.fireClick.isDown || this.pad.justPressed(Phaser.Gamepad.XBOX360_A)) {
        this.weapon.fire();
        if(!this.shootFx.isPlaying) {
          this.shootFx.play("shootMarker");
        }
        this.animations.play("fire");
      }
      this.anim(move);
    }
  }

  anim(move) {
    const angle = this.angle;
    if(move === "left") {
      if((angle < - 90 + 10 && angle > -90 - 10) || (angle > 90 - 10 && angle < 90 + 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(move === "right") {
      if((angle < - 90 + 10 && angle > - 90 - 10) || (angle > 90 - 10 && angle < 90 + 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(move === "up") {
      if((angle > - 10 && angle < 10) || (angle > - 180 + 10 && angle > 180 - 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(move === "down") {
      if((angle > - 10 && angle < 10) || (angle > - 180 + 10 && angle > 180 - 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(!move) {
      this.animations.stop("walk");
      this.animations.stop("slide");
    }
  }

  directionChoosed() {
    return this.lastDirection;
  }

  damage() {
    this.life = this.life - Damage;
  }

  cure() {
    this.life = this.life + Damage;
  }

  lifeInPercent() {
    return this.life / MaxLife;
  }

  isDeath() {
    return this.life < 0;
  }

  isOutSideTheLevel(game) {
    return this.body.position.x + CharacterWitdh < 0 ||
           this.body.position.x > game.world.bounds.width ||
           this.body.position.y < 0 ||
           this.body.position.y + CharacterHeight > game.world.bounds.height;
  }

  bullets() {
    return this.weapon.bullets;
  }

}

export default Character;<commit_msg>add gamepad<commit_after>import { SpritePlayer, SpriteBullet, ShootSound } from "../SpriteConstants";
import { CharacterWitdh, CharacterHeight, DirectionBoomerang } from "../Constants";

const Damage = 10;
const Velocity = 200;
const MaxBullet = 10;
const TimeLapse = 10;
const MaxLife = 1000;

class Character extends Phaser.Sprite {

  constructor(game, x, y, key, frame) {
    super(game, x, y, SpritePlayer, frame);
    game.physics.arcade.enable(this);
    //this.body.gravity.y = 500;
    this.body.bounce.x = this.body.bounce.y = 0;
    this.body.mass = 1;
    this.direction = 1;
    this.anchor.setTo(0.5, 0.5);
    this.life = MaxLife;

    const fire = [8, 9, 10, 11];
    const walk = [0, 1, 2, 3, 4, 5, 6, 7];
    const slide = [12, 13, 14, 15, 14, 13, 12];

    this.animations.add('walk', walk, TimeLapse, false);
    this.animations.add('slide', slide, TimeLapse, false);
    this.animations.add('fire', fire, TimeLapse * 6, false);

    this.weapon = game.add.weapon(MaxBullet, SpriteBullet);
    this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
    this.weapon.bulletAngleOffset = 90;
    //this.weapon.addBulletAnimation("fire", fire, TimeLapse, true);
    this.weapon.bulletAngleVariance = 5;
    this.weapon.bulletSpeed = 500;
    this.weapon.fireRate = 300;

    this.weapon.trackSprite(this, 30, 20, true);
    this.shootFx = game.add.audio(ShootSound);
    this.shootFx.allowMultiple = true;
    this.shootFx.addMarker('shootMarker', 0, 0.3);

    game.input.gamepad.start();
    this.pad = game.input.gamepad.pad1;
    this.cursor = game.input.keyboard.createCursorKeys();

    this.fireButton = game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR);
    this.fireClick = game.input.activePointer.leftButton;

    this.up = game.input.keyboard.addKey(Phaser.Keyboard.Z);
    this.leftKey = game.input.keyboard.addKey(Phaser.Keyboard.Q);
    this.rightKey = game.input.keyboard.addKey(Phaser.Keyboard.D);
    this.down = game.input.keyboard.addKey(Phaser.Keyboard.S);

    this.lastDirection = null;
  }

  update() {
    if(!this.isDeath()) {
      this.body.velocity.x = 0;
      this.body.velocity.y = 0;
      this.rotation = this.game.physics.arcade.angleToPointer(this);
      let move = null;
      //console.log(this.angle)

      if (this.cursor.left.isDown || this.leftKey.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.1 ) {
          this.body.velocity.x = -Velocity;
          this.direction = -1;
          this.lastDirection = DirectionBoomerang.left;
          move = "left";
      }
      else if (this.cursor.right.isDown || this.rightKey.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.1) {
          this.body.velocity.x = Velocity;
          this.direction = 1;
          this.lastDirection = DirectionBoomerang.right;
          move = "right";
      }

      if (this.cursor.up.isDown || this.up.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) < -0.1) {
        this.body.velocity.y = -Velocity;
        this.lastDirection = DirectionBoomerang.up;
        move = "up";
      } else if (this.cursor.down.isDown || this.down.isDown || this.pad.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_Y) > 0.1) {
        this.body.velocity.y = Velocity;
        this.lastDirection = DirectionBoomerang.down;
        move = "down";
      }

      if(this.fireButton.isDown || this.fireClick.isDown || this.pad.justPressed(Phaser.Gamepad.XBOX360_A)) {
        this.weapon.fire();
        if(!this.shootFx.isPlaying) {
          this.shootFx.play("shootMarker");
        }
        this.animations.play("fire");
      }
      this.anim(move);
    }
  }

  anim(move) {
    const angle = this.angle;
    if(move === "left") {
      if((angle < - 90 + 10 && angle > -90 - 10) || (angle > 90 - 10 && angle < 90 + 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(move === "right") {
      if((angle < - 90 + 10 && angle > - 90 - 10) || (angle > 90 - 10 && angle < 90 + 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(move === "up") {
      if((angle > - 10 && angle < 10) || (angle > - 180 + 10 && angle > 180 - 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(move === "down") {
      if((angle > - 10 && angle < 10) || (angle > - 180 + 10 && angle > 180 - 10)) {
        this.animations.play("slide");
      } else {
        this.animations.play("walk");
      }
    }

    if(!move) {
      this.animations.stop("walk");
      this.animations.stop("slide");
    }
  }

  directionChoosed() {
    return this.lastDirection;
  }

  damage() {
    this.life = this.life - Damage;
  }

  cure() {
    this.life = this.life + Damage;
  }

  lifeInPercent() {
    return this.life / MaxLife;
  }

  isDeath() {
    return this.life < 0;
  }

  isOutSideTheLevel(game) {
    return this.body.position.x + CharacterWitdh < 0 ||
           this.body.position.x > game.world.bounds.width ||
           this.body.position.y < 0 ||
           this.body.position.y + CharacterHeight > game.world.bounds.height;
  }

  bullets() {
    return this.weapon.bullets;
  }

}

export default Character;<|endoftext|>


<commit_before>/*!
 * ColumboJS.0.2.js
 * @author Gabor Zsoter
 *
 *
 * Usage example
 * ------------------
 *
 * Load component's inline js scripts within this closure
 * and pass in jQuery reference for example:
 *
 * Columbo.add("name_of_your_component", function($) {
 *
 *    ... your script here
 *
 * });
 *
 *
 * Then call them in the footer
 *
 * Columbo.run(jQuery);
 *
 */

 (function (w, undefined) {

    "use strict";

    var NAMESPACE = "Columbo";

    var exports = {};
    var collector = [];

	/*
	 * Turn on/off logging @ console
	 */
    var log = true;

    var debug = function (msg, type) {
        var level = type || "info";
        var color = level === "error" ? "red" : "green";
        log && w.console && w.console[level] && w.console[level]('%c' + NAMESPACE + "JS %c-> " + msg, 'color:blue;font-weight:bold;font-size:1.2em' , 'color:'+color+';font-style:italic;');
    };

    exports.add = function (name, func) {
        debug("REGISTERED:: " + name , "warn");
        collector.push([name, func]);
    };

    exports.run = function ($) {
        $.each(collector, function (i, el) {
			debug(el[0], "group");
            try {
                el[1]($);
            } catch (err) {
                debug(
                    "Your script failed: \n\n\tComponent: '" + el[0] + "'\n\n" +
                    "\tError: " + err.message + "\n", "error");

            }
			debug(el[0], "groupEnd");
            debug("Script has been executed | '" + el[0] + "' | @row: " + (i + 1));
            el.length = 0;
        });
    };

    w[NAMESPACE] = exports;

    debug("Listening!");

}(window, undefined));
<commit_msg>removed tab<commit_after>/*!
 * ColumboJS.0.2.js
 * @author Gabor Zsoter
 *
 *
 * Usage example
 * ------------------
 *
 * Load component's inline js scripts within this closure
 * and pass in jQuery reference for example:
 *
 * Columbo.add("name_of_your_component", function($) {
 *
 *    ... your script here
 *
 * });
 *
 *
 * Then call them in the footer
 *
 * Columbo.run(jQuery);
 *
 */

 (function (w, undefined) {

    "use strict";

    var NAMESPACE = "Columbo";

    var exports = {};
    var collector = [];

	/*
	 * Turn on/off logging @ console
	 */
    var log = true;

    var debug = function (msg, type) {
        var level = type || "info";
        var color = level === "error" ? "red" : "green";
        log && w.console && w.console[level] && w.console[level]('%c' + NAMESPACE + "JS %c-> " + msg, 'color:blue;font-weight:bold;font-size:1.2em' , 'color:'+color+';font-style:italic;');
    };

    exports.add = function (name, func) {
        debug("REGISTERED:: " + name , "warn");
        collector.push([name, func]);
    };

    exports.run = function ($) {
        $.each(collector, function (i, el) {
            debug(el[0], "group");
            try {
                el[1]($);
            } catch (err) {
                debug(
                    "Your script failed: \n\n\tComponent: '" + el[0] + "'\n\n" +
                    "\tError: " + err.message + "\n", "error");

            }
			debug(el[0], "groupEnd");
            debug("Script has been executed | '" + el[0] + "' | @row: " + (i + 1));
            el.length = 0;
        });
    };

    w[NAMESPACE] = exports;

    debug("Listening!");

}(window, undefined));
<|endoftext|>


<commit_before>export default function pointerCoords() {
    let self;

    function calculateCoords(event) {
        const pX = event.clientX || 0;
        const pY = event.clientY || 0;
        const sX = window.pageXOffset;
        const sY = window.pageYOffset;
        self.x = pX + sX;
        self.y = pY + sY;
        self.percentX = self.x / window.innerWidth;
        self.percentY = self.y / window.innerHeight;
    }

    self = {
        x: 0,
        y: 0,
        percentX: 0,
        percentY: 0,
        isListening: false,

        on: function() {
            document.body.addEventListener('mousemove', calculateCoords);
            document.body.addEventListener('touchmove', calculateCoords);
            self.isListening = true;
            return this;
        },
        off: function() {
            document.body.removeEventListener('mousemove', calculateCoords);
            document.body.removeEventListener('touchmove', calculateCoords);
            self.isListening = false;
            return this;
        }
    };
    return self;
}
<commit_msg>:heavy_plus_sign: Expose more props in pointercoords<commit_after>import getPageHeight from '../dom/getPageHeight';

export default function pointerCoords() {
    let self = null;

    function calculateCoords(event) {
        const touch = event.touches && event.touches.length;
        const p = touch ? event.touches[0] : event;
        const cX = p.clientX || 0;
        const cY = p.clientY || 0;
        const pX = window.pageXOffset;
        const pY = window.pageYOffset;
        self.event = event;
        self.clientX = cX;
        self.clientY = cY;
        self.x = cX + pX;
        self.y = cY + pY;
        self.percentX = self.x / window.innerWidth;
        self.percentY = self.y / getPageHeight();
    }

    self = {
        event: null,
        clientX: 0,
        clientY: 0,
        x: 0,
        y: 0,
        percentX: 0,
        percentY: 0,
        isListening: false,

        on: function() {
            document.body.addEventListener('mousemove', calculateCoords);
            document.body.addEventListener('touchmove', calculateCoords);
            self.isListening = true;
            return this;
        },
        off: function() {
            document.body.removeEventListener('mousemove', calculateCoords);
            document.body.removeEventListener('touchmove', calculateCoords);
            self.isListening = false;
            return this;
        }
    };
    return self;
}
<|endoftext|>


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

// Verify that the HTTP server implementation handles multiple instances
// of the same header as per RFC2616: joining the handful of fields by ', '
// that support it, and dropping duplicates for other fields.

var common = require('../common');
var assert = require('assert');
var http = require('http');

var multipleAllowed = [
  'Accept',
  'Accept-Charset',
  'Accept-Encoding',
  'Accept-Language',
  'Connection',
  'Cookie',
  'DAV', // GH-2750
  'Pragma', // GH-715
  'Link', // GH-1187
  'WWW-Authenticate', // GH-1083
  'Proxy-Authenticate', // GH-4052
  'Sec-Websocket-Extensions', // GH-2764
  'Sec-Websocket-Protocol', // GH-2764
  'Via', // GH-6660

  // not a special case, just making sure it's parsed correctly
  'X-Forwarded-For',

  // make sure that unspecified headers is treated as multiple
  'Some-Random-Header',
  'X-Some-Random-Header',
];

var multipleForbidden = [
  'Content-Type',
  'User-Agent',
  'Referer',
  'Host',
  'Authorization',
  'Proxy-Authorization',
  'If-Modified-Since',
  'If-Unmodified-Since',
  'From',
  'Location',
  'Max-Forwards',

  // special case, tested differently
  //'Content-Length',
];

var srv = http.createServer(function(req, res) {
  multipleForbidden.forEach(function(header) {
    assert.equal(req.headers[header.toLowerCase()], 'foo', 'header parsed incorrectly: ' + header);
  });
  multipleAllowed.forEach(function(header) {
    assert.equal(req.headers[header.toLowerCase()], 'foo, bar', 'header parsed incorrectly: ' + header);
  });
  assert.equal(req.headers['content-length'], 0);

  res.writeHead(200, {'Content-Type' : 'text/plain'});
  res.end('EOF');

  srv.close();
});

function makeHeader(value) {
  return function(header) {
    return [header, value];
  }
}

var headers = []
  .concat(multipleAllowed.map(makeHeader('foo')))
  .concat(multipleForbidden.map(makeHeader('foo')))
  .concat(multipleAllowed.map(makeHeader('bar')))
  .concat(multipleForbidden.map(makeHeader('bar')))
  // content-length is a special case since node.js
  // is dropping connetions with non-numeric headers
  .concat([['content-length', 0], ['content-length', 123]]);

srv.listen(common.PORT, function() {
  http.get({
    host: 'localhost',
    port: common.PORT,
    path: '/',
    headers: headers,
  });
});
<commit_msg>up-to-date (Jan 01, 2017)<commit_after>// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// Verify that the HTTP server implementation handles multiple instances
// of the same header as per RFC2616: joining the handful of fields by ', '
// that support it, and dropping duplicates for other fields.

var common = require('../common');
var assert = require('assert');
var http = require('http');

var multipleAllowed = [
  'Accept',
  'Accept-Charset',
  'Accept-Encoding',
  'Accept-Language',
  'Connection',
  'Cookie',
  'DAV', // GH-2750
  'Pragma', // GH-715
  'Link', // GH-1187
  'WWW-Authenticate', // GH-1083
  'Proxy-Authenticate', // GH-4052
  'Sec-Websocket-Extensions', // GH-2764
  'Sec-Websocket-Protocol', // GH-2764
  'Via', // GH-6660

  // not a special case, just making sure it's parsed correctly
  'X-Forwarded-For',

  // make sure that unspecified headers is treated as multiple
  'Some-Random-Header',
  'X-Some-Random-Header',
];

var multipleForbidden = [
  'Content-Type',
  'User-Agent',
  'Referer',
  'Host',
  'Authorization',
  'Proxy-Authorization',
  'If-Modified-Since',
  'If-Unmodified-Since',
  'From',
  'Location',
  'Max-Forwards',

  // special case, tested differently
  //'Content-Length',
];

var srv = http.createServer(function(req, res) {
  multipleForbidden.forEach(function(header) {
    assert.equal(req.headers[header.toLowerCase()], 'foo', 'header parsed incorrectly: ' + header);
  });
  multipleAllowed.forEach(function(header) {
    assert.equal(req.headers[header.toLowerCase()], 'foo, bar', 'header parsed incorrectly: ' + header);
  });
  assert.equal(req.headers['content-length'], 0);

  res.writeHead(200, {'Content-Type' : 'text/plain'});
  res.end('EOF');

  srv.close();
});

function makeHeader(value) {
  return function(header) {
    return [header, value];
  }
}

var headers = []
  .concat(multipleAllowed.map(makeHeader('foo')))
  .concat(multipleForbidden.map(makeHeader('foo')))
  .concat(multipleAllowed.map(makeHeader('bar')))
  .concat(multipleForbidden.map(makeHeader('bar')))
  // content-length is a special case since node.js
  // is dropping connetions with non-numeric headers
  .concat([['content-length', 0]]);

srv.listen(common.PORT, function() {
  http.get({
    host: 'localhost',
    port: common.PORT,
    path: '/',
    headers: headers,
  });
});
<|endoftext|>


<commit_before>/**
 * Created by xubt on 6/17/16.
 */
kanbanApp.directive('task', function ($uibModal) {
    return {
        restrict: 'E',
        templateUrl: 'component/task/partials/task.html',
        replace: true,
        transclude: true,
        scope: {
            task: '='
        },
        controller: ['$scope', 'localStorageService', 'assignmentServices', 'tasksServices', function ($scope, localStorageService, assignmentServices, tasksServices) {
            $scope.assign = function (_task) {
                var thisScope = $scope;
                $uibModal.open({
                    animation: false,
                    templateUrl: 'component/task/partials/assignment-confirm.html',
                    controller: function ($scope, $uibModalInstance) {
                        $scope.title = '确认信息';
                        if (thisScope.isIamAssigned) {
                            $scope.message = "你确定不再做该任务吗?";
                            $scope.ok = function () {
                                var userId = localStorageService.get("userId");
                                var myAssignmentLink;
                                angular.forEach(thisScope.assignments, function (_assignment) {
                                    if (userId === _assignment.assignee) {
                                        myAssignmentLink = _assignment._links.self.href;
                                        return;
                                    }
                                });
                                var assignmentPromise = assignmentServices.giveUp(myAssignmentLink);
                                assignmentPromise.then(function (_data) {
                                    thisScope.loadAssignments();
                                });
                                $uibModalInstance.close();
                            };
                        }
                        else {
                            $scope.message = "你确定要认领该任务吗?";
                            $scope.ok = function () {
                                var assignment = {
                                    taskId: _task.id,
                                    assignee: localStorageService.get("userId"),
                                    assigner: localStorageService.get("userId")
                                };

                                var assignmentPromise = assignmentServices.assign(assignment, _task._links.assignments.href);
                                assignmentPromise.then(function (_data) {
                                    thisScope.loadAssignments();
                                });
                                $uibModalInstance.close();
                            };
                        }
                        $scope.cancel = function () {
                            $uibModalInstance.dismiss('cancel');
                        };
                    },
                    size: 'sm'
                });
            };

            $scope.updateTask = function (_summary, _task) {
                var task = _task;
                task.summary = _summary;
                var taskPromise = tasksServices.update(task);
                taskPromise.then(function () {
                });
            };
            $scope.openDeleteModal = function (_message, _link) {
                var currentScope = $scope;
                $uibModal.open({
                    animation: false,
                    templateUrl: 'foundation/modal/partials/confirm-dialog.html',
                    controller: function ($scope, $uibModalInstance) {
                        $scope.title = '警告';
                        $scope.message = "确定要删除" + _message + "吗?";
                        $scope.ok = function () {
                            var _taskDeletePromise = tasksServices.deleteByLink(_link);
                            _taskDeletePromise.then(function () {
                                currentScope.$parent.loadTasks();
                            });
                            $uibModalInstance.close();
                        };
                        $scope.cancel = function () {
                            $uibModalInstance.dismiss('cancel');
                        };
                    },
                    size: 'sm'
                });
            };

            $scope.isAssigned = function () {
                var userId = localStorageService.get("userId");
                $scope.isIamAssigned = false;
                angular.forEach($scope.assignments, function (_assignment) {
                    if (userId === _assignment.assignee) {
                        $scope.isIamAssigned = true;
                        return;
                    }
                });
                $scope.assignTip = $scope.isIamAssigned === true ? "我不做了" : "认领";
            };
        }]
    };
});

<commit_msg>optimizing task update.<commit_after>/**
 * Created by xubt on 6/17/16.
 */
kanbanApp.directive('task', function ($uibModal) {
    return {
        restrict: 'E',
        templateUrl: 'component/task/partials/task.html',
        replace: true,
        transclude: true,
        scope: {
            task: '='
        },
        controller: ['$scope', 'localStorageService', 'assignmentServices', 'tasksServices', function ($scope, localStorageService, assignmentServices, tasksServices) {
            $scope.assign = function (_task) {
                var thisScope = $scope;
                $uibModal.open({
                    animation: false,
                    templateUrl: 'component/task/partials/assignment-confirm.html',
                    controller: function ($scope, $uibModalInstance) {
                        $scope.title = '确认信息';
                        if (thisScope.isIamAssigned) {
                            $scope.message = "你确定不再做该任务吗?";
                            $scope.ok = function () {
                                var userId = localStorageService.get("userId");
                                var myAssignmentLink;
                                angular.forEach(thisScope.assignments, function (_assignment) {
                                    if (userId === _assignment.assignee) {
                                        myAssignmentLink = _assignment._links.self.href;
                                        return;
                                    }
                                });
                                var assignmentPromise = assignmentServices.giveUp(myAssignmentLink);
                                assignmentPromise.then(function (_data) {
                                    thisScope.loadAssignments();
                                });
                                $uibModalInstance.close();
                            };
                        }
                        else {
                            $scope.message = "你确定要认领该任务吗?";
                            $scope.ok = function () {
                                var assignment = {
                                    taskId: _task.id,
                                    assignee: localStorageService.get("userId"),
                                    assigner: localStorageService.get("userId")
                                };

                                var assignmentPromise = assignmentServices.assign(assignment, _task._links.assignments.href);
                                assignmentPromise.then(function (_data) {
                                    thisScope.loadAssignments();
                                });
                                $uibModalInstance.close();
                            };
                        }
                        $scope.cancel = function () {
                            $uibModalInstance.dismiss('cancel');
                        };
                    },
                    size: 'sm'
                });
            };

            $scope.updateTask = function (_summary, _task) {
                var task = _task;
                if (task.summary == "") {
                    return;
                }
                task.summary = _summary;
                var taskPromise = tasksServices.update(task);
                taskPromise.then(function () {
                });
            };
            $scope.openDeleteModal = function (_message, _link) {
                var currentScope = $scope;
                $uibModal.open({
                    animation: false,
                    templateUrl: 'foundation/modal/partials/confirm-dialog.html',
                    controller: function ($scope, $uibModalInstance) {
                        $scope.title = '警告';
                        $scope.message = "确定要删除" + _message + "吗?";
                        $scope.ok = function () {
                            var _taskDeletePromise = tasksServices.deleteByLink(_link);
                            _taskDeletePromise.then(function () {
                                currentScope.$parent.loadTasks();
                            });
                            $uibModalInstance.close();
                        };
                        $scope.cancel = function () {
                            $uibModalInstance.dismiss('cancel');
                        };
                    },
                    size: 'sm'
                });
            };

            $scope.isAssigned = function () {
                var userId = localStorageService.get("userId");
                $scope.isIamAssigned = false;
                angular.forEach($scope.assignments, function (_assignment) {
                    if (userId === _assignment.assignee) {
                        $scope.isIamAssigned = true;
                        return;
                    }
                });
                $scope.assignTip = $scope.isIamAssigned === true ? "我不做了" : "认领";
            };
        }]
    };
});

<|endoftext|>


<commit_before>describe('Initalise free scroll', function(){

	it('should exist', function(){
		expect(FreeScroll).toBeDefined();
	});

	it('has a on method', function(){
		expect(FreeScroll.fn.on).toBeDefined();
	});

	it('has a off method', function(){
		expect(FreeScroll.fn.off).toBeDefined();
	});

	it('has a protected fire method', function(){
		expect(FreeScroll.fire).toBeDefined();
	});

	it('has a protected noMore method', function(){
		expect(FreeScroll.noMore).toBeDefined();
	});

	it('has a helper class', function(){
		expect(FreeScroll.helper).toBeDefined();
	});

	it('has a xhr class', function(){
		expect(FreeScroll.xhr).toBeDefined();
	});

	it('has a helper class with parseJSON method', function(){
		expect(FreeScroll.helper.parseJSON).toBeDefined();
	});

});<commit_msg>updated public api tests.<commit_after>describe('Initalise free scroll', function(){

	it('should exist', function(){
		expect(FreeScroll).toBeDefined();
	});

	it('has a more method', function(){
		expect(FreeScroll.fn.more).toBeDefined();
	});

	it('has a finish method', function(){
		expect(FreeScroll.fn.finish).toBeDefined();
	});

	it('has a addEvent method', function(){
		expect(FreeScroll.fn.addEvent).toBeDefined();
	});

	it('has a removeEvent method', function(){
		expect(FreeScroll.fn.removeEvent).toBeDefined();
	});

	it('has a each method', function(){
		expect(FreeScroll.fn.each).toBeDefined();
	});

	it('has a protected noMore method', function(){
		expect(FreeScroll.noMore).toBeDefined();
	});

	it('has a helper class', function(){
		expect(FreeScroll.helper).toBeDefined();
	});

	it('has a xhr class', function(){
		expect(FreeScroll.xhr).toBeDefined();
	});

	it('has a helper class with parseJSON method', function(){
		expect(FreeScroll.helper.parseJSON).toBeDefined();
	});

});<|endoftext|>


<commit_before>require('./check-versions')()

process.env.NODE_ENV = 'production'

var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')

var spinner = ora('building for production...')
spinner.start()

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  webpack(webpackConfig, function (err, stats) {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})
<commit_msg>修改配置使得build时删除dist下所有文件 <commit_after>require('./check-versions')()

process.env.NODE_ENV = 'production'

var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')

var spinner = ora('building for production...')
spinner.start()

// rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
rm(path.join(config.build.assetsRoot, '*.*'), err => {
  if (err) throw err
  webpack(webpackConfig, function (err, stats) {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})
<|endoftext|>


<commit_before>//Processamento de parâmentros via URL

//Foi solicitada mudança de mapa por URL?
if (URLSetBaseLayer!=null){
	switch(URLSetBaseLayer) {
		case 'satelite' : URLSetBaseLayer = 'lMBT'; break;
	}

	if(BaselayersValidas.match(URLSetBaseLayer)){
		$('#map-select-layer').val(URLSetBaseLayer);
		$('#map-select-layer').change();
	}
}

    //Se foi solicitado marcador no mapa
    if (MarkerLatLonByURL !=null){
	if (!MapPreventNewUserMakers){
		MapPreventNewUserMakers = true;
		UserTempMarker.setLatLng(MarkerLatLonByURL);
		map.setView(MarkerLatLonByURL, 18);
		var Msg = TempMarkerMsg(MarkerLatLonByURL[0],MarkerLatLonByURL[1]);
 		UserTempMarker.bindPopup(Msg).addTo(map);
		UserTempMarker.openPopup();
	}else{
		MapPreventNewUserMakers = false;
		map.removeLayer(UserTempMarker);
	}
    }

if (CamadaDeDados !=null){
   var OK = true;
   switch( CamadaDeDados  ) {
	case 'hospedagem' : AddDataOverlay('hospedagem','Hospedagem',HotelIcon,'map'); break;
	case 'barrest'    : AddDataOverlay('bares-restaurantes','Bares e Restaurantes',AlimentIcon,'map'); break;
	case 'taxi'       : AddDataOverlay('taxi','Táxi',TaxiIcon,'car'); break;
	case 'ribeiraorun5k2017'    : AddDataOverlay('ribeiraorun5k2017','Ribeirao Run 5k',UserIconOnClick,'walk'); break;
        default           : OK = false;
   }
   if(OK){
      ControleListDadosGeoJSON.addTo(map);
   }
}

$(".btnMapSatSwitcher").click(function(e) {
   e.preventDefault();
   if(MapCompareActive){
	   MapCompareActiveStop();
   }else{

	if( IsSatelliteLayer()){
		$('#map-select-layer').val('lMNK');
	}else{
		$('#map-select-layer').val('lMBT');
	}
        $('#map-select-layer').change();
   }
});

$(".btnListDadosGeoJSON").click(function(e) {
   e.preventDefault();
   var URL = 'dados/?d='+CamadaDeDados;
   window.location.href = URL;
});
<commit_msg>Update proc-param.js<commit_after>//Processamento de parâmentros via URL

//Foi solicitada mudança de mapa por URL?
if (URLSetBaseLayer!=null){
	switch(URLSetBaseLayer) {
		case 'satelite' : URLSetBaseLayer = 'lMBT'; break;
	}

	if(BaselayersValidas.match(URLSetBaseLayer)){
		$('#map-select-layer').val(URLSetBaseLayer);
		$('#map-select-layer').change();
	}
}

    //Se foi solicitado marcador no mapa
    if (MarkerLatLonByURL !=null){
	if (!MapPreventNewUserMakers){
		MapPreventNewUserMakers = true;
		UserTempMarker.setLatLng(MarkerLatLonByURL);
		map.setView(MarkerLatLonByURL, 18);
		var Msg = TempMarkerMsg(MarkerLatLonByURL[0],MarkerLatLonByURL[1]);
 		UserTempMarker.bindPopup(Msg).addTo(map);
		UserTempMarker.openPopup();
	}else{
		MapPreventNewUserMakers = false;
		map.removeLayer(UserTempMarker);
	}
    }

if (CamadaDeDados !=null){
   var OK = true;
   switch( CamadaDeDados  ) {
	case 'hospedagem' : AddDataOverlay('hospedagem','Hospedagem',HotelIcon,'map'); break;
	case 'barrest'    : AddDataOverlay('bares-restaurantes','Bares e Restaurantes',AlimentIcon,'map'); break;
	case 'taxi'       : AddDataOverlay('taxi','Táxi',TaxiIcon,'car'); break;
	case 'ribeiraorun5k2017'    : AddDataOverlay('ribeiraorun5k2017','Ribeirao Run 5k',null,'walk'); break;
        default           : OK = false;
   }
   if(OK){
      ControleListDadosGeoJSON.addTo(map);
   }
}

$(".btnMapSatSwitcher").click(function(e) {
   e.preventDefault();
   if(MapCompareActive){
	   MapCompareActiveStop();
   }else{

	if( IsSatelliteLayer()){
		$('#map-select-layer').val('lMNK');
	}else{
		$('#map-select-layer').val('lMBT');
	}
        $('#map-select-layer').change();
   }
});

$(".btnListDadosGeoJSON").click(function(e) {
   e.preventDefault();
   var URL = 'dados/?d='+CamadaDeDados;
   window.location.href = URL;
});
<|endoftext|>


<commit_before>(function (exports) {

    'use strict';

    function RRuleField(element, options) {
        this.element = element;
        this.options = $.extend(true, {}, RRuleField._defaultOptions, options);
        this.init();
    }

    RRuleField._defaultOptions = {
        'daysOfWeek':   ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
        'changeClass':  'rrulefield-input'
    };

    var dayCodes = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
    var dayMap = [RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR, RRule.SA, RRule.SU];

    RRuleField.prototype.init = function()
    {
        this._rrule = RRule.fromString(this.element.val());
        this.render();
    };

    /**
     * Render the form fields for this widget
     */
    RRuleField.prototype.render = function()
    {
        var self = this;
        // mask the original input field
        $(self.element).hide();
        // create a container in which we can store all our input fields for defining the RRule
        self.container = $("
").insertAfter(self.element);

        // render the days of the week selection
        self.renderDaysOfWeek(self.container);
        self.renderWeekSelection(self.container);

        // update the field every time the rrule field form is changed
        $(self.container).on('change', '.'+self.options.changeClass, function(e) {self.updateField()});
    };

    /**
     * Check current rule configuration for whether the given day should be selected in the form
     *
     * @param day
     * @returns {boolean}
     */
    RRuleField.prototype.isDaySelected = function(day)
    {
        if (this._rrule.options.byweekday)
            return ($.inArray(parseInt(day), this._rrule.options.byweekday) > -1);
        if (this._rrule.options.bynweekday) {
            for (var i in this._rrule.options.bynweekday) {
                if (day == this._rrule.options.bynweekday[i][0]) {
                    return true;
                }
            }
        }
        return false;
    };

    /**
     * Only returns true if not all weeks are selected, and the specific week should be.
     *
     * @param week
     * @returns {boolean}
     */
    RRuleField.prototype.isWeekSelected = function(week)
    {
        if (this._rrule.options.byweekday) {
            // if the rrule library has set a byweekday option
            // this implies all weeks selected
            return false;
        }
        else if (this._rrule.options.bynweekday) {
            for (var i in this._rrule.options.bynweekday) {
                if (week == this._rrule.options.bynweekday[i][1])
                    return true;
            }
        }
        return false;
    };

    /**
     * Create the form component for selecting the days of the week the rule applies to
     *
     * @TODO: templating?
     */
    RRuleField.prototype.renderDaysOfWeek = function(container)
    {
        var self = this;

        var fields = "
Day(s) of the Week:
";
        for (var i in dayCodes) {
            fields += '<input type="checkbox" name="dayOfWeek[]" value="' + i + '" class="'+ this.options.changeClass +'"';
            if (self.isDaySelected(i)) {
                fields += ' checked';
            }

            fields += '/>' + self.options.daysOfWeek[i] + '';
        }

        $(container).append(fields);
    };

    /**
     * Create form component for selecting which weeks of the month the rule applies to
     *
     * @param container
     */
    RRuleField.prototype.renderWeekSelection = function(container)
    {
        var self = this;

        var weekSelection = $('
');
        container.append(weekSelection);

        // flag to determine set the everyweek box checked
        var everyWeek = true;

        // the individual weeks checkboxes span
        var weekFields = 'or
';
        for (var i = 1; i <=5; i++) {
            weekFields += '<input type="checkbox" name="week-number[]" value="' + i + '" class="week-number ' + this.options.changeClass + '" ';
            if (self.isWeekSelected(i)) {
                everyWeek = false;
                weekFields += ' checked';
            }
            weekFields += '/>Week ' + i + '';
        }
        weekFields += '';

        // defining this afterward so we can apply the checked property correctly.
        var everyWeekField = '
Weeks of the Month:
<input type="checkbox" name="every-week" class="every-week '+ this.options.changeClass +'";';
        if (everyWeek)
            everyWeekField += ' checked';
        everyWeekField += '/>Every Week';
        // the hint field is there to explain why you can't uncheck the every week box alone.
        everyWeekField += 'select a week number to uncheck this
';

        weekSelection.append(everyWeekField + weekFields);

        weekSelection.on('change', 'input', function(e) {
            var showHint = false;
            if ($(e.target).hasClass('every-week')) {
                if ($(e.target).prop('checked')) {
                    weekSelection.find('.week-number:checked').prop('checked', false);
                }
                else {
                    if (weekSelection.find('.week-number:checked').length == 0) {
                        $(e.target).prop('checked', true);
                        showHint = true;
                    }
                }
            }
            else {
                if (weekSelection.find('.week-number:checked').length == 0) {
                    weekSelection.find('.every-week').prop('checked', true);
                }
                else {
                    weekSelection.find('.every-week').prop('checked', false);
                }
            }
            if (showHint) {
                weekSelection.find('.hint').fadeIn();
            }
            else {
                weekSelection.find('.hint').fadeOut();
            }
        });
    };

    /**
     * This iterates through the form to pull out the selected values, create a new RRule object and use that
     * to populate the original form element.
     */
    RRuleField.prototype.updateField = function()
    {
        var self = this;
        var weekdays = [];
        $(self.container).find('input[name="dayOfWeek\[\]"]').each(function() {
            if ($(this).prop('checked'))
                weekdays.push(dayMap[parseInt($(this).val())]);
        });

        var rruleOptions = {};
        if (!weekdays.length) {
            weekdays = dayMap;
        }

        if ($(self.container).find('input[name="every-week"]').prop('checked')) {
            rruleOptions.freq = RRule.WEEKLY;
            rruleOptions.byweekday = weekdays;
        }
        else {
            rruleOptions.freq = RRule.MONTHLY;
            rruleOptions.byweekday = [];
            for (var i in weekdays) {
                $(self.container).find('.week-number:checked').each(function() {
                    rruleOptions.byweekday.push(weekdays[i].nth(parseInt($(this).val())));
                });
            }
        }
        self._rrule = new RRule(rruleOptions);
        $(self.element).val(self._rrule.toString());
    };

    /**
     * Simple attachment function
     *
     * @param element
     * @param options
     * @returns {*}
     */
    function attach(element, options)
    {
        if (options === undefined)
            options = {};
        // TODO: (if this were ever to become useful) a remove and replace method to refresh it
        if (!element.data('OpenEyes.UI.Widgets.RRuleField')) {
            element.data('OpenEyes.UI.Widgets.RRuleField', new RRuleField(element, options));
        }
        return element;
    }

    exports.RRuleField = attach;

}(this.OpenEyes.UI.Widgets));<commit_msg>+ simple error handling for invaid rrule entry in widget<commit_after>(function (exports) {

    'use strict';

    function RRuleField(element, options) {
        this.element = element;
        this.options = $.extend(true, {}, RRuleField._defaultOptions, options);
        this.init();
    }

    RRuleField._defaultOptions = {
        'daysOfWeek':   ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
        'changeClass':  'rrulefield-input'
    };

    var dayCodes = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
    var dayMap = [RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR, RRule.SA, RRule.SU];

    RRuleField.prototype.init = function()
    {
        try {
            this._rrule = RRule.fromString(this.element.val());
        }
        catch (e) {
            // simple error handling here. In theory should never arise, but this will at
            // least prevent the widget from masking any issues by still rendering the form
            console.log(this.element.val() + ' is not a valid for rrule');
            return;
        }
        this.render();
    };

    /**
     * Render the form fields for this widget
     */
    RRuleField.prototype.render = function()
    {
        var self = this;
        // mask the original input field
        $(self.element).hide();
        // create a container in which we can store all our input fields for defining the RRule
        self.container = $("
").insertAfter(self.element);

        // render the days of the week selection
        self.renderDaysOfWeek(self.container);
        self.renderWeekSelection(self.container);

        // update the field every time the rrule field form is changed
        $(self.container).on('change', '.'+self.options.changeClass, function(e) {self.updateField()});
    };

    /**
     * Check current rule configuration for whether the given day should be selected in the form
     *
     * @param day
     * @returns {boolean}
     */
    RRuleField.prototype.isDaySelected = function(day)
    {
        if (this._rrule.options.byweekday)
            return ($.inArray(parseInt(day), this._rrule.options.byweekday) > -1);
        if (this._rrule.options.bynweekday) {
            for (var i in this._rrule.options.bynweekday) {
                if (day == this._rrule.options.bynweekday[i][0]) {
                    return true;
                }
            }
        }
        return false;
    };

    /**
     * Only returns true if not all weeks are selected, and the specific week should be.
     *
     * @param week
     * @returns {boolean}
     */
    RRuleField.prototype.isWeekSelected = function(week)
    {
        if (this._rrule.options.byweekday) {
            // if the rrule library has set a byweekday option
            // this implies all weeks selected
            return false;
        }
        else if (this._rrule.options.bynweekday) {
            for (var i in this._rrule.options.bynweekday) {
                if (week == this._rrule.options.bynweekday[i][1])
                    return true;
            }
        }
        return false;
    };

    /**
     * Create the form component for selecting the days of the week the rule applies to
     *
     * @TODO: templating?
     */
    RRuleField.prototype.renderDaysOfWeek = function(container)
    {
        var self = this;

        var fields = "
Day(s) of the Week:
";
        for (var i in dayCodes) {
            fields += '<input type="checkbox" name="dayOfWeek[]" value="' + i + '" class="'+ this.options.changeClass +'"';
            if (self.isDaySelected(i)) {
                fields += ' checked';
            }

            fields += '/>' + self.options.daysOfWeek[i] + '';
        }

        $(container).append(fields);
    };

    /**
     * Create form component for selecting which weeks of the month the rule applies to
     *
     * @param container
     */
    RRuleField.prototype.renderWeekSelection = function(container)
    {
        var self = this;

        var weekSelection = $('
');
        container.append(weekSelection);

        // flag to determine set the everyweek box checked
        var everyWeek = true;

        // the individual weeks checkboxes span
        var weekFields = 'or
';
        for (var i = 1; i <=5; i++) {
            weekFields += '<input type="checkbox" name="week-number[]" value="' + i + '" class="week-number ' + this.options.changeClass + '" ';
            if (self.isWeekSelected(i)) {
                everyWeek = false;
                weekFields += ' checked';
            }
            weekFields += '/>Week ' + i + '';
        }
        weekFields += '';

        // defining this afterward so we can apply the checked property correctly.
        var everyWeekField = '
Weeks of the Month:
<input type="checkbox" name="every-week" class="every-week '+ this.options.changeClass +'";';
        if (everyWeek)
            everyWeekField += ' checked';
        everyWeekField += '/>Every Week';
        // the hint field is there to explain why you can't uncheck the every week box alone.
        everyWeekField += 'select a week number to uncheck this
';

        weekSelection.append(everyWeekField + weekFields);

        weekSelection.on('change', 'input', function(e) {
            var showHint = false;
            if ($(e.target).hasClass('every-week')) {
                if ($(e.target).prop('checked')) {
                    weekSelection.find('.week-number:checked').prop('checked', false);
                }
                else {
                    if (weekSelection.find('.week-number:checked').length == 0) {
                        $(e.target).prop('checked', true);
                        showHint = true;
                    }
                }
            }
            else {
                if (weekSelection.find('.week-number:checked').length == 0) {
                    weekSelection.find('.every-week').prop('checked', true);
                }
                else {
                    weekSelection.find('.every-week').prop('checked', false);
                }
            }
            if (showHint) {
                weekSelection.find('.hint').fadeIn();
            }
            else {
                weekSelection.find('.hint').fadeOut();
            }
        });
    };

    /**
     * This iterates through the form to pull out the selected values, create a new RRule object and use that
     * to populate the original form element.
     */
    RRuleField.prototype.updateField = function()
    {
        var self = this;
        var weekdays = [];
        $(self.container).find('input[name="dayOfWeek\[\]"]').each(function() {
            if ($(this).prop('checked'))
                weekdays.push(dayMap[parseInt($(this).val())]);
        });

        var rruleOptions = {};
        if (!weekdays.length) {
            weekdays = dayMap;
        }

        if ($(self.container).find('input[name="every-week"]').prop('checked')) {
            rruleOptions.freq = RRule.WEEKLY;
            rruleOptions.byweekday = weekdays;
        }
        else {
            rruleOptions.freq = RRule.MONTHLY;
            rruleOptions.byweekday = [];
            for (var i in weekdays) {
                $(self.container).find('.week-number:checked').each(function() {
                    rruleOptions.byweekday.push(weekdays[i].nth(parseInt($(this).val())));
                });
            }
        }
        self._rrule = new RRule(rruleOptions);
        $(self.element).val(self._rrule.toString());
    };

    /**
     * Simple attachment function
     *
     * @param element
     * @param options
     * @returns {*}
     */
    function attach(element, options)
    {
        if (options === undefined)
            options = {};
        // TODO: (if this were ever to become useful) a remove and replace method to refresh it
        if (!element.data('OpenEyes.UI.Widgets.RRuleField')) {
            element.data('OpenEyes.UI.Widgets.RRuleField', new RRuleField(element, options));
        }
        return element;
    }

    exports.RRuleField = attach;

}(this.OpenEyes.UI.Widgets));<|endoftext|>