<commit_before>angular.module("angular-growl").provider("growl", function() {
  "use strict";

  var _ttl = {success: null, error: null, warning: null, info: null},
      _messagesKey = 'messages',
      _messageTextKey = 'text',
      _messageTitleKey = 'title',
      _messageSeverityKey = 'severity',
      _onlyUniqueMessages = true,
      _messageVariableKey = 'variables',
      _referenceId = 0,
      _inline = false,
      _position = 'top-right',
      _disableCloseButton = false,
      _disableIcons = false,
      _reverseOrder = false;

  /**
   * set a global timeout (time to live) after which messages will be automatically closed
   *
   * @param ttl in seconds
   */
  this.globalTimeToLive = function(ttl) {
    if(typeof ttl === 'object') {
      for(var k in ttl) {
        if(ttl.hasOwnProperty(k)) {
          _ttl[k] = ttl[k];
        }
      }
    } else {
      for(var severity in _ttl) {
        if(_ttl.hasOwnProperty(severity)) {
          _ttl[severity] = ttl;
        }
      }
    }
  };

  /**
   * set whether the close button should be displayed (default) or hidden
   *
   * @param {bool} disableCloseButton true to hide close button on all messages
   */
  this.globalDisableCloseButton = function (disableCloseButton) {
    _disableCloseButton = disableCloseButton;
  };

  /**
   * set whether the icons will be shown in the message
   *
   * @param {bool} messageIcons
   */
  this.globalDisableIcons = function (disableIcons) {
    _disableIcons = disableIcons;
  };

  /**
   * set whether message ordering is reversed
   *
   * @param {bool} reverseOrder
   */
   this.globalReversedOrder = function (reverseOrder) {
    _reverseOrder = reverseOrder;
   };

  /**
   * set the key in server sent messages the serverMessagesInterecptor is looking for variables to inject in the message
   *
   * @param  {string} messageVariableKey default: variables
   */
  this.messageVariableKey = function (messageVariableKey) {
    _messageVariableKey = messageVariableKey;
  };

  /**
   * set wheter the notficiation is displayed inline our in growl like fasion
   *
   * @param {bool} inline true to show only inline notifications
   */
  this.globalInlineMessages = function(inline) {
    _inline = inline;
  };

  /**
   * set position
   *
   * @param  {string} messageVariableKey default: top-right
   */
  this.globalPosition = function(position) {
    _position = position;
  };
  /**
   * sets the key in $http response the serverMessagesInterecptor is looking for server-sent messages, value of key
   * needs to be an array of objects
   *
   * @param {string} messagesKey default: messages
   */
  this.messagesKey = function(messagesKey) {
    _messagesKey = messagesKey;
  };

  /**
   * sets the key in server sent messages the serverMessagesInterecptor is looking for text of message
   *
   * @param {string} messageTextKey default: text
   */
  this.messageTextKey = function(messageTextKey) {
    _messageTextKey = messageTextKey;
  };

  /**
   * sets the key in server sent messages the serverMessagesInterecptor is looking for title of message
   *
   * @param {string} messageTextKey default: text
   */
  this.messageTitleKey = function(messageTitleKey) {
    _messageTitleKey = messageTitleKey;
  };

  /**
   * sets the key in server sent messages the serverMessagesInterecptor is looking for severity of message
   *
   * @param {string} messageSeverityKey default: severity
   */
  this.messageSeverityKey = function(messageSeverityKey) {
    _messageSeverityKey = messageSeverityKey;
  };

  this.onlyUniqueMessages = function(onlyUniqueMessages) {
    _onlyUniqueMessages = onlyUniqueMessages;
  };

  /**
   * $http interceptor that can be added to array of $http interceptors during config phase of application
   * via $httpProvider.responseInterceptors.push(...)
   *
   */
  this.serverMessagesInterceptor = ['$q', 'growl', function ($q, growl) {
    function checkResponse(response) {
      if (response.data[_messagesKey] && response.data[_messagesKey].length > 0) {
        growl.addServerMessages(response.data[_messagesKey]);
      }
    }

    function success(response) {
      checkResponse(response);
      return response;
    }

    function error(response) {
      checkResponse(response);
      return $q.reject(response);
    }

    return function (promise) {
      return promise.then(success, error);
    };
  }];

  this.$get = ["$rootScope", "$interpolate", "$filter", function ($rootScope, $interpolate, $filter) {
    var translate;

    try {
      translate = $filter("translate");
    } catch (e) {
      //
    }

    function broadcastMessage(message) {
      if (translate) {
        message.text = translate(message.text, message.variables);
      } else {
        var polation = $interpolate(message.text);
        message.text = polation(message.variables);
      }
      $rootScope.$broadcast("growlMessage", message);
    }

    function sendMessage(text, config, severity) {
      var _config = config || {}, message;

      message = {
        text: text,
        title: _config.title,
        severity: severity,
        ttl: _config.ttl || _ttl[severity],
        variables: _config.variables || {},
        disableCloseButton: _config.disableCloseButton || _disableCloseButton,
        disableIcons: _config.disableIcons === undefined ? _disableIcons : _config.disableIcons,
        position: _config.position || _position,
        referenceId: _config.referenceId || _referenceId
      };

      broadcastMessage(message);
    }

    /**
     * add one warning message with bootstrap class: alert
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function warning(text, config) {
      sendMessage(text, config, "warning");
    }

    /**
     * add one error message with bootstrap classes: alert, alert-error
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function error(text, config) {
      sendMessage(text, config, "error");
    }

    /**
     * add one info message with bootstrap classes: alert, alert-info
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function info(text, config) {
      sendMessage(text, config, "info");
    }

    /**
     * add one success message with bootstrap classes: alert, alert-success
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function success(text, config) {
      sendMessage(text, config, "success");
    }

    /**
     * add a indefinite number of messages that a backend server may have sent as a validation result
     *
     * @param {Array.<object>} messages
     */
    function addServerMessages(messages) {
      var i, message, severity, length;
      length = messages.length;
      for (i = 0; i < length; i++) {
        message = messages[i];

        if (message[_messageTextKey]) {
          severity = message[_messageSeverityKey] || "error";
          var config = {};
          config.variables = message[_messageVariableKey] || {};
          config.title = message[_messageTitleKey];
          sendMessage(message[_messageTextKey], config, severity);
        }
      }
    }

    function onlyUnique() {
      return _onlyUniqueMessages;
    }

    function reverseOrder() {
      return _reverseOrder;
    }

    function inlineMessages() {
      return _inline;
    }

    function position() {
      return _position;
    }

    return {
      warning: warning,
      error: error,
      info: info,
      success: success,
      addServerMessages: addServerMessages,
      onlyUnique: onlyUnique,
      reverseOrder : reverseOrder,
      inlineMessages: inlineMessages,
      position: position
    };
  }];
});
<commit_msg>Fix for Angular 1.3 http interceptor api change<commit_after>angular.module("angular-growl").provider("growl", function() {
  "use strict";

  var _ttl = {success: null, error: null, warning: null, info: null},
      _messagesKey = 'messages',
      _messageTextKey = 'text',
      _messageTitleKey = 'title',
      _messageSeverityKey = 'severity',
      _onlyUniqueMessages = true,
      _messageVariableKey = 'variables',
      _referenceId = 0,
      _inline = false,
      _position = 'top-right',
      _disableCloseButton = false,
      _disableIcons = false,
      _reverseOrder = false;

  /**
   * set a global timeout (time to live) after which messages will be automatically closed
   *
   * @param ttl in seconds
   */
  this.globalTimeToLive = function(ttl) {
    if(typeof ttl === 'object') {
      for(var k in ttl) {
        if(ttl.hasOwnProperty(k)) {
          _ttl[k] = ttl[k];
        }
      }
    } else {
      for(var severity in _ttl) {
        if(_ttl.hasOwnProperty(severity)) {
          _ttl[severity] = ttl;
        }
      }
    }
  };

  /**
   * set whether the close button should be displayed (default) or hidden
   *
   * @param {bool} disableCloseButton true to hide close button on all messages
   */
  this.globalDisableCloseButton = function (disableCloseButton) {
    _disableCloseButton = disableCloseButton;
  };

  /**
   * set whether the icons will be shown in the message
   *
   * @param {bool} messageIcons
   */
  this.globalDisableIcons = function (disableIcons) {
    _disableIcons = disableIcons;
  };

  /**
   * set whether message ordering is reversed
   *
   * @param {bool} reverseOrder
   */
   this.globalReversedOrder = function (reverseOrder) {
    _reverseOrder = reverseOrder;
   };

  /**
   * set the key in server sent messages the serverMessagesInterecptor is looking for variables to inject in the message
   *
   * @param  {string} messageVariableKey default: variables
   */
  this.messageVariableKey = function (messageVariableKey) {
    _messageVariableKey = messageVariableKey;
  };

  /**
   * set wheter the notficiation is displayed inline our in growl like fasion
   *
   * @param {bool} inline true to show only inline notifications
   */
  this.globalInlineMessages = function(inline) {
    _inline = inline;
  };

  /**
   * set position
   *
   * @param  {string} messageVariableKey default: top-right
   */
  this.globalPosition = function(position) {
    _position = position;
  };
  /**
   * sets the key in $http response the serverMessagesInterecptor is looking for server-sent messages, value of key
   * needs to be an array of objects
   *
   * @param {string} messagesKey default: messages
   */
  this.messagesKey = function(messagesKey) {
    _messagesKey = messagesKey;
  };

  /**
   * sets the key in server sent messages the serverMessagesInterecptor is looking for text of message
   *
   * @param {string} messageTextKey default: text
   */
  this.messageTextKey = function(messageTextKey) {
    _messageTextKey = messageTextKey;
  };

  /**
   * sets the key in server sent messages the serverMessagesInterecptor is looking for title of message
   *
   * @param {string} messageTextKey default: text
   */
  this.messageTitleKey = function(messageTitleKey) {
    _messageTitleKey = messageTitleKey;
  };

  /**
   * sets the key in server sent messages the serverMessagesInterecptor is looking for severity of message
   *
   * @param {string} messageSeverityKey default: severity
   */
  this.messageSeverityKey = function(messageSeverityKey) {
    _messageSeverityKey = messageSeverityKey;
  };

  this.onlyUniqueMessages = function(onlyUniqueMessages) {
    _onlyUniqueMessages = onlyUniqueMessages;
  };

  /**
   * $http interceptor that can be added to array of $http interceptors during config phase of application
   * via $httpProvider.responseInterceptors.push(...)
   *
   */
  this.serverMessagesInterceptor = ['$q', 'growl', function ($q, growl) {
    function checkResponse(response) {
      if (response.data[_messagesKey] && response.data[_messagesKey].length > 0) {
        growl.addServerMessages(response.data[_messagesKey]);
      }
    }

	  return {
		  'response': function(response) {
			  checkResponse(response);
			  return response;
		  },
		  'responseError': function(rejection) {
			  checkResponse(rejection);
			  return $q.reject(rejection);
		  }
	  };
  }];

  this.$get = ["$rootScope", "$interpolate", "$filter", function ($rootScope, $interpolate, $filter) {
    var translate;

    try {
      translate = $filter("translate");
    } catch (e) {
      //
    }

    function broadcastMessage(message) {
      if (translate) {
        message.text = translate(message.text, message.variables);
      } else {
        var polation = $interpolate(message.text);
        message.text = polation(message.variables);
      }
      $rootScope.$broadcast("growlMessage", message);
    }

    function sendMessage(text, config, severity) {
      var _config = config || {}, message;

      message = {
        text: text,
        title: _config.title,
        severity: severity,
        ttl: _config.ttl || _ttl[severity],
        variables: _config.variables || {},
        disableCloseButton: _config.disableCloseButton || _disableCloseButton,
        disableIcons: _config.disableIcons === undefined ? _disableIcons : _config.disableIcons,
        position: _config.position || _position,
        referenceId: _config.referenceId || _referenceId
      };

      broadcastMessage(message);
    }

    /**
     * add one warning message with bootstrap class: alert
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function warning(text, config) {
      sendMessage(text, config, "warning");
    }

    /**
     * add one error message with bootstrap classes: alert, alert-error
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function error(text, config) {
      sendMessage(text, config, "error");
    }

    /**
     * add one info message with bootstrap classes: alert, alert-info
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function info(text, config) {
      sendMessage(text, config, "info");
    }

    /**
     * add one success message with bootstrap classes: alert, alert-success
     *
     * @param {string} text
     * @param {{ttl: number}} config
     */
    function success(text, config) {
      sendMessage(text, config, "success");
    }

    /**
     * add a indefinite number of messages that a backend server may have sent as a validation result
     *
     * @param {Array.<object>} messages
     */
    function addServerMessages(messages) {
      var i, message, severity, length;
      length = messages.length;
      for (i = 0; i < length; i++) {
        message = messages[i];

        if (message[_messageTextKey]) {
          severity = message[_messageSeverityKey] || "error";
          var config = {};
          config.variables = message[_messageVariableKey] || {};
          config.title = message[_messageTitleKey];
          sendMessage(message[_messageTextKey], config, severity);
        }
      }
    }

    function onlyUnique() {
      return _onlyUniqueMessages;
    }

    function reverseOrder() {
      return _reverseOrder;
    }

    function inlineMessages() {
      return _inline;
    }

    function position() {
      return _position;
    }

    return {
      warning: warning,
      error: error,
      info: info,
      success: success,
      addServerMessages: addServerMessages,
      onlyUnique: onlyUnique,
      reverseOrder : reverseOrder,
      inlineMessages: inlineMessages,
      position: position
    };
  }];
});
<|endoftext|>


<commit_before>

WC.renderConversatiom = function(conversation){
    retVal = ""
    retVal += "
"
    retVal += "
"
    retVal += conversation.title
    retVal += "
"
    retVal += "
"
    for(participant in conversation.participants)
    {
        retVal += ""
        retVal += conversation.participants[participant].full_name
        retVal += ""
    }
    retVal += "
"
    retVal += "
"

    return retVal;
};

WC.xmlhttp = new XMLHttpRequest();

WC.run = function(){
    WC.hideAllElements();
    WC.showElement("conversations-loading");
    WC.xmlhttp.onreadystatechange = WC.ajaxReurn;
    WC.xmlhttp.open("GET", WC.getWatercoolrUrl() + "api/v0/conversations/unread.json", true);
    WC.xmlhttp.send();
    document.getElementById("home-link").addEventListener("click",function(){WC.goToInbox();});
};

WC.convoClick = function(e){
    WC.goToInbox(e.target.parentElement.attributes.convoUrl.value);
};

WC.ajaxReurn = function(){
    if (WC.xmlhttp.readyState==4)
    {
        WC.hideAllElements();
        WC.refreshCounter();
        if(WC.xmlhttp.status==200){
            var convoData = JSON.parse(WC.xmlhttp.response);
            if(convoData.length > 0)
            {
                //unread convos
                WC.showElement("conversations");
                rendered_convos = "";
                for(conversation in convoData)
                {
                    rendered_convos += WC.renderConversatiom(convoData[conversation]);
                }
                document.getElementById("conversations-list").innerHTML = rendered_convos;
                for(conversation in convoData)
                {
                    //conversation/watercooler-feedback/79
                    document.getElementById("conversation-" + convoData[conversation].id).addEventListener("click",WC.convoClick);
                }
            }
            if(convoData.length == 0)
            {
                //no unread convos
                WC.showElement("conversations-empty");
            }
        }
        else if(WC.xmlhttp.status==401)
        {
            // need to log in.
            WC.showElement("conversations-login");
        }
        else
        {
            WC.showElement("conversations-error");
        }
    }
};

WC.hideAllElements = function(){
    $(".is-visible").removeClass("is-visible");
}

WC.showElement = function(elementID){
    $("#"+elementID).addClass("is-visible");
}

WC.run();
<commit_msg>dont bother generating a slug<commit_after>

WC.renderConversatiom = function(conversation){
    retVal = ""
    retVal += "
"
    retVal += "
"
    retVal += conversation.title
    retVal += "
"
    retVal += "
"
    for(participant in conversation.participants)
    {
        retVal += ""
        retVal += conversation.participants[participant].full_name
        retVal += ""
    }
    retVal += "
"
    retVal += "
"

    return retVal;
};

WC.xmlhttp = new XMLHttpRequest();

WC.run = function(){
    WC.hideAllElements();
    WC.showElement("conversations-loading");
    WC.xmlhttp.onreadystatechange = WC.ajaxReurn;
    WC.xmlhttp.open("GET", WC.getWatercoolrUrl() + "api/v0/conversations/unread.json", true);
    WC.xmlhttp.send();
    document.getElementById("home-link").addEventListener("click",function(){WC.goToInbox();});
};

WC.convoClick = function(e){
    WC.goToInbox(e.target.parentElement.attributes.convoUrl.value);
};

WC.ajaxReurn = function(){
    if (WC.xmlhttp.readyState==4)
    {
        WC.hideAllElements();
        WC.refreshCounter();
        if(WC.xmlhttp.status==200){
            var convoData = JSON.parse(WC.xmlhttp.response);
            if(convoData.length > 0)
            {
                //unread convos
                WC.showElement("conversations");
                rendered_convos = "";
                for(conversation in convoData)
                {
                    rendered_convos += WC.renderConversatiom(convoData[conversation]);
                }
                document.getElementById("conversations-list").innerHTML = rendered_convos;
                for(conversation in convoData)
                {
                    //conversation/watercooler-feedback/79
                    document.getElementById("conversation-" + convoData[conversation].id).addEventListener("click",WC.convoClick);
                }
            }
            if(convoData.length == 0)
            {
                //no unread convos
                WC.showElement("conversations-empty");
            }
        }
        else if(WC.xmlhttp.status==401)
        {
            // need to log in.
            WC.showElement("conversations-login");
        }
        else
        {
            WC.showElement("conversations-error");
        }
    }
};

WC.hideAllElements = function(){
    $(".is-visible").removeClass("is-visible");
}

WC.showElement = function(elementID){
    $("#"+elementID).addClass("is-visible");
}

WC.run();
<|endoftext|>


<commit_before>import flux from 'flux'

const undo = []

export default new class Dispatcher extends flux.Dispatcher {

  dispatch(action: Function, data?: Object) {
    // undo.push({
    //   data
    // })

    super.dispatch({action, data})
  }

}
<commit_msg>Remove deadcode.<commit_after>import flux from 'flux'

const undo = []

export default new class Dispatcher extends flux.Dispatcher {

  dispatch(action: Function, data?: Object) {
    super.dispatch({action, data})
  }

}
<|endoftext|>


<commit_before>import React from 'react';
import _ from 'underscore';

import {Loader} from 'bilprospekt-ui';

const LoaderDoc = React.createClass({
    render() {
        const divStyle = ({
            position: 'relative',
            height: '200px',
            width: '100%',
            border: '1px solid #E0E0E0',
        });

        return (

Loader

                    <Loader width='25%' message='Laddar in dina listor ...' />

                    {
                        [
                        '<Loader width={25} message="Laddar in dina listor ..." />',
                        ]
                    }

        );
    },
});

export default LoaderDoc;
<commit_msg>Updated code example.<commit_after>import React from 'react';
import _ from 'underscore';

import {Loader} from 'bilprospekt-ui';

const LoaderDoc = React.createClass({
    render() {
        const divStyle = ({
            position: 'relative',
            height: '200px',
            width: '100%',
            border: '1px solid #E0E0E0',
        });

        return (

Loader

                    <Loader width='25%' message='Laddar in dina listor ...' />

                    {
                        [
                        '<Loader width="25%" message="Laddar in dina listor ..." />',
                        ]
                    }

        );
    },
});

export default LoaderDoc;
<|endoftext|>


<commit_before>var expect = require('chai').expect;

function toEnglish(word){
  if ( word === "zero" ){
      return 0;
  }

  if ( word === "one" ){
      return 1;
  }
  if ( word === "two" ){
      return 2;
  }
  if ( word === "three" ){
      return 3;
  }
  if ( word === "four" ){
      return 4;
  }
  if ( word === "five"){
      return 5;
  }
  if ( word === "six"){
      return 6;
  }
  if ( word === "seven"){
    return 7;
  }
  if ( word === "eight"){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }
  if ( word === "ten" ){
    return 10;
  }
}

expect(toEnglish("zero")).to.equal(0);
expect(toEnglish("one")).to.equal(1);
expect(toEnglish("two")).to.equal(2);
expect(toEnglish("three")).to.equal(3);
expect(toEnglish("four")).to.equal(4);
expect(toEnglish("five")).to.equal(5);
expect(toEnglish("six")).to.equal(6);
expect(toEnglish("seven")).to.equal(7);
expect(toEnglish("eight")).to.equal(8);
expect(toEnglish("nine")).to.equal(9);
expect(toEnglish("ten")).to.equal(10);

function plus(A, B){
  return toEnglish(A) + toEnglish(B);
}

expect(plus).to.exist;
expect(plus("zero", "zero")).to.equal(0);
expect(plus("zero", "one")).to.equal(1);
expect(plus("zero", "two")).to.equal(2);
expect(plus("zero", "three")).to.equal(3);
expect(plus("zero", "four")).to.equal(4);
expect(plus("zero", "five")).to.equal(5);
expect(plus("zero", "six")).to.equal(6);
expect(plus("zero", "seven")).to.equal(7);
expect(plus("zero", "eight")).to.equal(8);
expect(plus("zero", "nine")).to.equal(9);

// console.log(plus("zero", "zero"));
// console.log(plus("zero", "one"));
// console.log(plus("zero", "two"));

expect(plus("one", "one")).to.equal(2);
expect(plus("one", "two")).to.equal(3);
expect(plus("one", "three")).to.equal(4);
expect(plus("one", "four")).to.equal(5);
expect(plus("one", "five")).to.equal(6);
expect(plus("one", "six")).to.equal(7);
expect(plus("one", "seven")).to.equal(8);
expect(plus("one", "eight")).to.equal(9);
expect(plus("one", "nine")).to.equal(10);

expect(plus("two", "zero")).to.equal(2);
expect(plus("two", "one")).to.equal(3);
expect(plus("two", "two")).to.equal(4);
expect(plus("two", "three")).to.equal(5);
expect(plus("two", "four")).to.equal(6);
expect(plus("two", "five")).to.equal(7);
expect(plus("two", "six")).to.equal(8);
expect(plus("two", "seven")).to.equal(9);
expect(plus("two", "eight")).to.equal(10);
expect(plus("two", "nine")).to.equal(11);

expect(plus("three", "zero")).to.equal(3);
expect(plus("three", "one")).to.equal(4);
expect(plus("three", "two")).to.equal(5);
expect(plus("three", "three")).to.equal(6);
expect(plus("three", "four")).to.equal(7);
expect(plus("three", "five")).to.equal(8);
expect(plus("three", "six")).to.equal(9);
expect(plus("three", "seven")).to.equal(10);
expect(plus("three", "eight")).to.equal(11);
expect(plus("three", "nine")).to.equal(12);

expect(plus("four","zero")).to.equal(4);
expect(plus("four", "one")).to.equal(5);
expect(plus("four", "two")).to.equal(6);
expect(plus("four", "three")).to.equal(7);
expect(plus("four", "four")).to.equal(8);
expect(plus("four", "five")).to.equal(9);
expect(plus("four", "six")).to.equal(10);
expect(plus("four", "seven")).to.equal(11);
expect(plus("four", "eight")).to.equal(12);
expect(plus("four", "nine")).to.equal(13);

expect(plus("five", "zero")).to.equal(5);
expect(plus("five", "one")).to.equal(6);
expect(plus("five", "two")).to.equal(7);
expect(plus("five", "three")).to.equal(8);
expect(plus("five", "four")).to.equal(9);
expect(plus("five", "five")).to.equal(10);
expect(plus("five", "six")).to.equal(11);
expect(plus("five", "seven")).to.equal(12);
expect(plus("five", "eight")).to.equal(13);
expect(plus("five", "nine")).to.equal(14);

console.log(plus("one", "one"));
<commit_msg>Test #1 - Test Ben's alternative function(plus) syntax<commit_after>var expect = require('chai').expect;

function toEnglish(word){
  if ( word === "zero" ){
      return 0;
  }

  if ( word === "one" ){
      return 1;
  }
  if ( word === "two" ){
      return 2;
  }
  if ( word === "three" ){
      return 3;
  }
  if ( word === "four" ){
      return 4;
  }
  if ( word === "five"){
      return 5;
  }
  if ( word === "six"){
      return 6;
  }
  if ( word === "seven"){
    return 7;
  }
  if ( word === "eight"){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }
  if ( word === "ten" ){
    return 10;
  }
}

expect(toEnglish("zero")).to.equal(0);
expect(toEnglish("one")).to.equal(1);
expect(toEnglish("two")).to.equal(2);
expect(toEnglish("three")).to.equal(3);
expect(toEnglish("four")).to.equal(4);
expect(toEnglish("five")).to.equal(5);
expect(toEnglish("six")).to.equal(6);
expect(toEnglish("seven")).to.equal(7);
expect(toEnglish("eight")).to.equal(8);
expect(toEnglish("nine")).to.equal(9);
expect(toEnglish("ten")).to.equal(10);

//function plus(A, B){
  //return toEnglish(A) + toEnglish(B);
//}

function plus(x,y){
  var x = toEnglish(x);
  var y = toEnglish(y);
  return x + y;

}

expect(plus).to.exist;
expect(plus("zero", "zero")).to.equal(0);
expect(plus("zero", "one")).to.equal(1);
expect(plus("zero", "two")).to.equal(2);
expect(plus("zero", "three")).to.equal(3);
expect(plus("zero", "four")).to.equal(4);
expect(plus("zero", "five")).to.equal(5);
expect(plus("zero", "six")).to.equal(6);
expect(plus("zero", "seven")).to.equal(7);
expect(plus("zero", "eight")).to.equal(8);
expect(plus("zero", "nine")).to.equal(9);

// console.log(plus("zero", "zero"));
// console.log(plus("zero", "one"));
// console.log(plus("zero", "two"));

expect(plus("one", "one")).to.equal(2);
expect(plus("one", "two")).to.equal(3);
expect(plus("one", "three")).to.equal(4);
expect(plus("one", "four")).to.equal(5);
expect(plus("one", "five")).to.equal(6);
expect(plus("one", "six")).to.equal(7);
expect(plus("one", "seven")).to.equal(8);
expect(plus("one", "eight")).to.equal(9);
expect(plus("one", "nine")).to.equal(10);

expect(plus("two", "zero")).to.equal(2);
expect(plus("two", "one")).to.equal(3);
expect(plus("two", "two")).to.equal(4);
expect(plus("two", "three")).to.equal(5);
expect(plus("two", "four")).to.equal(6);
expect(plus("two", "five")).to.equal(7);
expect(plus("two", "six")).to.equal(8);
expect(plus("two", "seven")).to.equal(9);
expect(plus("two", "eight")).to.equal(10);
expect(plus("two", "nine")).to.equal(11);

expect(plus("three", "zero")).to.equal(3);
expect(plus("three", "one")).to.equal(4);
expect(plus("three", "two")).to.equal(5);
expect(plus("three", "three")).to.equal(6);
expect(plus("three", "four")).to.equal(7);
expect(plus("three", "five")).to.equal(8);
expect(plus("three", "six")).to.equal(9);
expect(plus("three", "seven")).to.equal(10);
expect(plus("three", "eight")).to.equal(11);
expect(plus("three", "nine")).to.equal(12);

expect(plus("four", "zero")).to.equal(4);
expect(plus("four", "one")).to.equal(5);
expect(plus("four", "two")).to.equal(6);
expect(plus("four", "three")).to.equal(7);
expect(plus("four", "four")).to.equal(8);
expect(plus("four", "five")).to.equal(9);
expect(plus("four", "six")).to.equal(10);
expect(plus("four", "seven")).to.equal(11);
expect(plus("four", "eight")).to.equal(12);
expect(plus("four", "nine")).to.equal(13);

expect(plus("five", "zero")).to.equal(5);
expect(plus("five", "one")).to.equal(6);
expect(plus("five", "two")).to.equal(7);
expect(plus("five", "three")).to.equal(8);
expect(plus("five", "four")).to.equal(9);
expect(plus("five", "five")).to.equal(10);
expect(plus("five", "six")).to.equal(11);
expect(plus("five", "seven")).to.equal(12);
expect(plus("five", "eight")).to.equal(13);
expect(plus("five", "nine")).to.equal(14);

expect(plus("six", "zero")).to.equal(6);
expect(plus("six", "one")).to.equal(7);
expect(plus("six", "two")).to.equal(8);
expect(plus("six", "three")).to.equal(9);
expect(plus("six", "four")).to.equal(10);
expect(plus("six", "five")).to.equal(11);
expect(plus("six", "six")).to.equal(12);
expect(plus("six", "seven")).to.equal(13);
expect(plus("six", "eight")).to.equal(14);
expect(plus("six", "nine")).to.equal(15);

console.log(plus("one", "one"));
<|endoftext|>


<commit_before>(function(){
	"use strict";

	KC3StrategyTabs.expcalc = new KC3StrategyTab("expcalc");

	KC3StrategyTabs.expcalc.definition = {
		tabSelf: KC3StrategyTabs.expcalc,
		goals: {},
		mapexp: [],
		maplist: {},
		shipexp: {},
        goalTemplates: [], // to be initialized in "init"

		rankNames: ["F", "E", "D", "C", "B", "A", "S", "SS" ],
		rankFactors: [0, 0.5, 0.7, 0.8, 1, 1, 1.2],

		/* INIT
		Prepares all data needed
		---------------------------------*/
		init :function(){
			// Check for saved grind data
			if(typeof localStorage.goals != "undefined"){
				this.goals = JSON.parse(localStorage.goals);
			}

			// Get map exp rewards
			this.mapexp = JSON.parse($.ajax({
				url : '../../../../data/exp_map.json',
				async: false
			}).responseText);

			var self = this;
			$.each(this.mapexp, function(worldNum, mapNums){
				$.each(mapNums, function(mapNum, mapExp){
					if(mapExp > 0){
						self.maplist[worldNum+"-"+(mapNum+1)] = mapExp;
					}
				});
			});

            this.goalTemplates = GoalTemplateManager.load();
			console.log(this.maplist);
		},

		/* EXECUTE
		Places data onto the interface
		---------------------------------*/
		execute :function(){
			var self = this;
			// Add map list into the factory drop-downs
			$.each(this.maplist, function(MapName, MapExp){
				$(".tab_expcalc .factory .ship_map select").append("<option>"+MapName+"</option>");
				$(".tab_expcalc .factory .goal_map select").append("<option>"+MapName+"</option>");
			});

			var editingBox, mapSplit;

			// Edit Button
			$(".tab_expcalc .box_goals").on("click", ".ship_edit", function(){
				editingBox = $(this).parent();
				var grindData = self.goals[ "s"+editingBox.data("id") ];

				$(".ship_target input", editingBox).val( grindData[0] );
				$(".ship_map select", editingBox).val( grindData[1]+"-"+grindData[2] );
				$(".ship_rank select", editingBox).val(  grindData[4] );
				$(".ship_fs input", editingBox).prop("checked", grindData[5]);
				$(".ship_mvp input", editingBox).prop("checked", grindData[6]);

				$(".ship_value" , editingBox).hide();
				$(".ship_input" , editingBox).show();

				$(".ship_edit" , editingBox).hide();
				$(".ship_save" , editingBox).show();
			});

			// Save Button
			$(".tab_expcalc .box_goals").on("click", ".ship_save", function(){
				editingBox = $(this).parent();

				mapSplit = $(".ship_map select", editingBox).val().split("-");
				console.log("mapSplit", mapSplit);
				self.goals["s"+ editingBox.data("id") ] = [
					/*0*/ parseInt($(".ship_target input", editingBox).val(), 10), // target level
					/*1*/ parseInt(mapSplit[0], 10), // world
					/*2*/ parseInt(mapSplit[1], 10), // map
					/*3*/ 0, // node
					/*4*/ parseInt($(".ship_rank select", editingBox).val(), 10), // battle rank
					/*5*/ $(".ship_fs input", editingBox).prop("checked")?1:0, // flagship
					/*6*/ $(".ship_mvp input", editingBox).prop("checked")?1:0 // mvp
				];

				self.save();

				self.recompute( editingBox.data("id") );

				$(".ship_value" , editingBox).show();
				$(".ship_input" , editingBox).hide();

				$(".ship_edit" , editingBox).show();
				$(".ship_save" , editingBox).hide();
			});

			// Add to Goals Button
			$(".tab_expcalc").on("click", ".ship_add", function(){
				editingBox = $(this).parent();
				self.goals["s"+ editingBox.data("id") ] = [];
				self.save();
				//window.location.reload();

				$(".ship_edit", editingBox).show();
				$(".ship_rem", editingBox).show();
				editingBox.removeClass("inactive");
				editingBox.appendTo(".tab_expcalc .box_goals");
				self.recompute( editingBox.data("id") );
			});

            function goalTemplateSetupUI(tdata, goalBox) {
                var mapStr = tdata.map.join("-");

                console.log("setup", GoalTemplateManager.showSType(tdata.stype));
                // "show" mode
                $(".goal_type .goal_value",goalBox)
                    .text( GoalTemplateManager.showSType(tdata.stype) );
                $(".goal_map .goal_value",goalBox).text( mapStr );
                $(".goal_rank .goal_value",goalBox).text( self.rankNames[tdata.rank] );
                $(".goal_fs .goal_value",goalBox).text( tdata.flagship? "Yes":"No" );
                $(".goal_mvp .goal_value",goalBox).text( tdata.mvp? "Yes":"No" );

                // "edit" mode
                $(".goal_type input",goalBox)
                    .val( GoalTemplateManager.showSType(tdata.stype) );
                $(".goal_map select",goalBox).val( mapStr );
                $(".goal_rank select",goalBox).val( tdata.rank );
	            $(".goal_fs input", goalBox).prop("checked", tdata.flagship);
	            $(".goal_mvp input", goalBox).prop("checked", tdata.mvp);
            }

            function goalTemplateEdit(t) {
                $(".goal_edit",t).hide();
                $(".goal_save",t).show();

                $(".goal_col .goal_value",t).hide();
                $(".goal_col .goal_input",t).show();
                $(".manage_buttons",t).hide();
            }

            function goalTemplateShow(t) {
                $(".goal_edit",t).show();
                $(".goal_save",t).hide();

                $(".goal_col .goal_value",t).show();
                $(".goal_col .goal_input",t).hide();
                $(".manage_buttons",t).show();
            }

            function goalTemplateRemove(t) {
                var ind = t.index();
                self.goalTemplates.splice(ind,1);
                GoalTemplateManager.save( self.goalTemplates );
                t.remove();
            }

            // for saving modification
            function goalTemplateSave(t) {
                var stypeRaw = $(".goal_type input",t).val();
                var stype = GoalTemplateManager.parseSType( stypeRaw );
                var mapRaw = $(".goal_map select",t).val();
                var map = mapRaw.split("-").map(function (x) { return parseInt(x,10); });
                var rankNum = parseInt($(".goal_rank select", t).val(), 10);
                var flagship = $(".goal_fs input", t).prop("checked");
                var mvp = $(".goal_mvp input", t).prop("checked");

                var result = {
                    stype: stype,
                    map: map,
                    rank: rankNum,
                    flagship: flagship,
                    mvp: mvp };
                self.goalTemplates[t.index()] = result;
                GoalTemplateManager.save( self.goalTemplates );
            }

            // Goal Template Edit & Save button events
            $(".tab_expcalc").on("click", ".goal_template .goal_edit", function() {
                var goalBox = $(this).parent().parent();
                goalTemplateEdit(goalBox);
            });

            $(".tab_expcalc").on("click", ".goal_template .goal_save", function() {
                var goalBox = $(this).parent().parent();
                goalTemplateSave(goalBox);
                goalTemplateSetupUI(self.goalTemplates[ goalBox.index() ], goalBox);
                goalTemplateShow(goalBox);
            });

            $(".tab_expcalc").on("click", ".goal_template .goal_rem", function() {
                var goalBox = $(this).parent().parent();
                goalTemplateRemove(goalBox);
            });

            $.each(this.goalTemplates, function(i,x) {
                var goalBox = $(".tab_expcalc .factory .goal_template").clone();
                goalTemplateSetupUI(self.goalTemplates[i], goalBox);
                goalTemplateShow(goalBox);

                goalBox.appendTo(".tab_expcalc .box_goal_templates");
            });

            $(".tab_expcalc a.new_template").on("click", function () {
                var goalBox = $(".tab_expcalc .factory .goal_template").clone();
                var dat = GoalTemplateManager.newTemplate();
                self.goalTemplates.push(dat);
                GoalTemplateManager.save( self.goalTemplates );
                goalTemplateSetupUI(dat, goalBox);
                goalTemplateShow(goalBox);
                goalBox.appendTo(".tab_expcalc .box_goal_templates");
            });

            // TODO: filter feature
            // TODO: enable/disable
            // TODO: move up / down
            // TODO: apply to goals

			// Remove from Goals Button
			$(".tab_expcalc").on("click", ".ship_rem", function(){
				editingBox = $(this).parent();
				delete self.goals["s"+ editingBox.data("id") ];
				self.save();
				//window.location.reload();

				$(".ship_save", editingBox).hide();
				$(".ship_edit", editingBox).hide();
				$(".ship_rem", editingBox).hide();
				editingBox.addClass("inactive");
				var ThisShip = KC3ShipManager.get(editingBox.data("id"));
				if(ThisShip.master().api_aftershipid > 0 && ThisShip.level<ThisShip.master().api_afterlv){
					$(".tab_expcalc .box_recommend .clear").remove();
					editingBox.appendTo(".tab_expcalc .box_recommend");
					$("<div />").addClass("clear").appendTo(".tab_expcalc .box_recommend");
				}else{
					$(".tab_expcalc .box_other .clear").remove();
					editingBox.appendTo(".tab_expcalc .box_other");
					$("<div />").addClass("clear").appendTo(".tab_expcalc .box_other");
				}
			});

			// Show all ship_save
			var goalBox;
			$.each(KC3ShipManager.list, function(index, ThisShip){
				if(!ThisShip.lock){ return true; }

				// Create the ship box
				goalBox = $(".tab_expcalc .factory .ship_goal").clone();
				goalBox.attr("id", "goalBox"+ThisShip.rosterId);
				goalBox.data("id", ThisShip.rosterId);

				// Icon and level, common for all categories
				$(".ship_icon img", goalBox).attr("src", KC3Meta.shipIcon(ThisShip.masterId) );
				$(".ship_icon img", goalBox).attr("title", ThisShip.name() + ' (' + ThisShip.rosterId + ')' );
				$(".ship_name", goalBox).text( ThisShip.name() );
				$(".ship_type", goalBox).text( ThisShip.stype() );
				$(".ship_lv .ship_value", goalBox).text( ThisShip.level );

				// If ship already on the current goals
				if(typeof self.goals["s"+ThisShip.rosterId] != "undefined"){
					$(".ship_edit", goalBox).show();
					$(".ship_rem", goalBox).show();
					goalBox.appendTo(".tab_expcalc .box_goals");

					self.recompute( ThisShip.rosterId );
					return true;
				}

				goalBox.addClass("inactive");

				// If still has next remodel, add to recommendations
				if(ThisShip.master().api_aftershipid > 0 && ThisShip.level<ThisShip.master().api_afterlv){
					$(".ship_target .ship_value", goalBox).text( ThisShip.master().api_afterlv );
					goalBox.appendTo(".tab_expcalc .box_recommend");
					return true;
				}

				// If this is the last remodel stage, add to others
				if(ThisShip.level<99){
					$(".ship_target .ship_value", goalBox).text( 99 );
				}else{
					$(".ship_target .ship_value", goalBox).text( 155 );
				}
				goalBox.appendTo(".tab_expcalc .box_other");
			});

			//this.save();

			$("<div />").addClass("clear").appendTo(".tab_expcalc .box_recommend");
			$("<div />").addClass("clear").appendTo(".tab_expcalc .box_other");
		},

		save: function(){
			localStorage.goals = JSON.stringify(this.goals);
		},

		recompute: function( rosterId ){
			var goalBox = $("#goalBox"+rosterId);
			var grindData = this.goals["s"+rosterId];
			var ThisShip = KC3ShipManager.get( rosterId );
			var MasterShip = ThisShip.master();

			// This has just been added, no grinding data yet, initialize defaults
			if(grindData.length === 0){
				// As much as possible use arrays nowadays to shrink JSON size, we might run out of the 5MB localStorage allocated for our app
				grindData = [
					/*0*/ (MasterShip.api_aftershipid > 0 && ThisShip.level<MasterShip.api_afterlv)?MasterShip.api_afterlv:(ThisShip.level<99)?99:150, // target level
					/*1*/ 1, // world
					/*2*/ 1, // map
					/*3*/ 1, // node
					/*4*/ 6, // E=1 D=2 C=3 B=4 A=5 S=6 SS=7
					/*5*/ 0, // flagship
					/*6*/ 0 // mvp
				];
				this.goals["s"+ThisShip.rosterId] = grindData;
			}else{

			}

			// Target level
			$(".ship_target .ship_value", goalBox).text( grindData[0] );

			// Experience Left
			var expLeft = KC3Meta.expShip(grindData[0])[1] - ThisShip.exp[0];
			$(".ship_exp .ship_value", goalBox).text( expLeft );

			// Base Experience: MAP
			$(".ship_map .ship_value", goalBox).text( grindData[1]+"-"+grindData[2] );
			var expPerSortie = this.maplist[ grindData[1]+"-"+grindData[2] ];

			// Exp Modifier: MVP
			$(".ship_mvp .ship_value", goalBox).text( grindData[6]?"Yes":"No" );
			$(".ship_mvp .ship_value", goalBox).css('color',(grindData[6]? "#e33" : "#039")); //yes : light red, no : deep blue
			if(grindData[6]===1){ expPerSortie = expPerSortie * 2; }

			// Exp Modifier: FLAGSHIP
			$(".ship_fs .ship_value", goalBox).text( grindData[5]?"Yes":"No" );
			$(".ship_mvp .ship_value", goalBox).css('color',(grindData[6]? "#e33" : "#039"));
			if(grindData[5]===1){ expPerSortie = expPerSortie * 1.5; }

			// Exp Modifier: RANK
			$(".ship_rank .ship_value", goalBox).text( this.rankNames[grindData[4]] );
			expPerSortie = expPerSortie * this.rankFactors[grindData[4]];

			// RESULT: Battles Left
			$(".ship_result .ship_value", goalBox).text( Math.ceil(expLeft / expPerSortie) );
		}

	};

})();
<commit_msg>move up / down<commit_after>(function(){
	"use strict";

	KC3StrategyTabs.expcalc = new KC3StrategyTab("expcalc");

	KC3StrategyTabs.expcalc.definition = {
		tabSelf: KC3StrategyTabs.expcalc,
		goals: {},
		mapexp: [],
		maplist: {},
		shipexp: {},
        goalTemplates: [], // to be initialized in "init"

		rankNames: ["F", "E", "D", "C", "B", "A", "S", "SS" ],
		rankFactors: [0, 0.5, 0.7, 0.8, 1, 1, 1.2],

		/* INIT
		Prepares all data needed
		---------------------------------*/
		init :function(){
			// Check for saved grind data
			if(typeof localStorage.goals != "undefined"){
				this.goals = JSON.parse(localStorage.goals);
			}

			// Get map exp rewards
			this.mapexp = JSON.parse($.ajax({
				url : '../../../../data/exp_map.json',
				async: false
			}).responseText);

			var self = this;
			$.each(this.mapexp, function(worldNum, mapNums){
				$.each(mapNums, function(mapNum, mapExp){
					if(mapExp > 0){
						self.maplist[worldNum+"-"+(mapNum+1)] = mapExp;
					}
				});
			});

            this.goalTemplates = GoalTemplateManager.load();
			console.log(this.maplist);
		},

		/* EXECUTE
		Places data onto the interface
		---------------------------------*/
		execute :function(){
			var self = this;
			// Add map list into the factory drop-downs
			$.each(this.maplist, function(MapName, MapExp){
				$(".tab_expcalc .factory .ship_map select").append("<option>"+MapName+"</option>");
				$(".tab_expcalc .factory .goal_map select").append("<option>"+MapName+"</option>");
			});

			var editingBox, mapSplit;

			// Edit Button
			$(".tab_expcalc .box_goals").on("click", ".ship_edit", function(){
				editingBox = $(this).parent();
				var grindData = self.goals[ "s"+editingBox.data("id") ];

				$(".ship_target input", editingBox).val( grindData[0] );
				$(".ship_map select", editingBox).val( grindData[1]+"-"+grindData[2] );
				$(".ship_rank select", editingBox).val(  grindData[4] );
				$(".ship_fs input", editingBox).prop("checked", grindData[5]);
				$(".ship_mvp input", editingBox).prop("checked", grindData[6]);

				$(".ship_value" , editingBox).hide();
				$(".ship_input" , editingBox).show();

				$(".ship_edit" , editingBox).hide();
				$(".ship_save" , editingBox).show();
			});

			// Save Button
			$(".tab_expcalc .box_goals").on("click", ".ship_save", function(){
				editingBox = $(this).parent();

				mapSplit = $(".ship_map select", editingBox).val().split("-");
				console.log("mapSplit", mapSplit);
				self.goals["s"+ editingBox.data("id") ] = [
					/*0*/ parseInt($(".ship_target input", editingBox).val(), 10), // target level
					/*1*/ parseInt(mapSplit[0], 10), // world
					/*2*/ parseInt(mapSplit[1], 10), // map
					/*3*/ 0, // node
					/*4*/ parseInt($(".ship_rank select", editingBox).val(), 10), // battle rank
					/*5*/ $(".ship_fs input", editingBox).prop("checked")?1:0, // flagship
					/*6*/ $(".ship_mvp input", editingBox).prop("checked")?1:0 // mvp
				];

				self.save();

				self.recompute( editingBox.data("id") );

				$(".ship_value" , editingBox).show();
				$(".ship_input" , editingBox).hide();

				$(".ship_edit" , editingBox).show();
				$(".ship_save" , editingBox).hide();
			});

			// Add to Goals Button
			$(".tab_expcalc").on("click", ".ship_add", function(){
				editingBox = $(this).parent();
				self.goals["s"+ editingBox.data("id") ] = [];
				self.save();
				//window.location.reload();

				$(".ship_edit", editingBox).show();
				$(".ship_rem", editingBox).show();
				editingBox.removeClass("inactive");
				editingBox.appendTo(".tab_expcalc .box_goals");
				self.recompute( editingBox.data("id") );
			});

            function goalTemplateSetupUI(tdata, goalBox) {
                var mapStr = tdata.map.join("-");

                console.log("setup", GoalTemplateManager.showSType(tdata.stype));
                // "show" mode
                $(".goal_type .goal_value",goalBox)
                    .text( GoalTemplateManager.showSType(tdata.stype) );
                $(".goal_map .goal_value",goalBox).text( mapStr );
                $(".goal_rank .goal_value",goalBox).text( self.rankNames[tdata.rank] );
                $(".goal_fs .goal_value",goalBox).text( tdata.flagship? "Yes":"No" );
                $(".goal_mvp .goal_value",goalBox).text( tdata.mvp? "Yes":"No" );

                // "edit" mode
                $(".goal_type input",goalBox)
                    .val( GoalTemplateManager.showSType(tdata.stype) );
                $(".goal_map select",goalBox).val( mapStr );
                $(".goal_rank select",goalBox).val( tdata.rank );
	            $(".goal_fs input", goalBox).prop("checked", tdata.flagship);
	            $(".goal_mvp input", goalBox).prop("checked", tdata.mvp);
            }

            function goalTemplateEdit(t) {
                $(".goal_edit",t).hide();
                $(".goal_save",t).show();

                $(".goal_col .goal_value",t).hide();
                $(".goal_col .goal_input",t).show();
                $(".manage_buttons",t).hide();
            }

            function goalTemplateShow(t) {
                $(".goal_edit",t).show();
                $(".goal_save",t).hide();

                $(".goal_col .goal_value",t).show();
                $(".goal_col .goal_input",t).hide();
                $(".manage_buttons",t).show();
            }

            function goalTemplateRemove(t) {
                var ind = t.index();
                self.goalTemplates.splice(ind,1);
                GoalTemplateManager.save( self.goalTemplates );
                t.remove();
            }

            // swap two templates, make sure abs(index1 - index2) == 1
            // and index1 is a valid index (index2 doesn't have to be)
            function goalTemplateSwap(index1,index2) {
                if (Math.abs(index1 - index2) == 1) {
                    if (index2 >= 0 && index2 < self.goalTemplates.length) {
                        // swap data
                        var tmp = self.goalTemplates[index1];
                        self.goalTemplates[index1] = self.goalTemplates[index2];
                        self.goalTemplates[index2] = tmp;
                        GoalTemplateManager.save( self.goalTemplates );
                        // setup UI
                        var cs = $(".box_goal_templates").children();
                        goalTemplateSetupUI(self.goalTemplates[index1],
                                            cs[index1]);
                        goalTemplateShow(cs[index1]);
                        goalTemplateSetupUI(self.goalTemplates[index2],
                                            cs[index2]);
                        goalTemplateShow(cs[index2]);
                    }
                }
            }

            // for saving modification
            function goalTemplateSave(t) {
                var stypeRaw = $(".goal_type input",t).val();
                var stype = GoalTemplateManager.parseSType( stypeRaw );
                var mapRaw = $(".goal_map select",t).val();
                var map = mapRaw.split("-").map(function (x) { return parseInt(x,10); });
                var rankNum = parseInt($(".goal_rank select", t).val(), 10);
                var flagship = $(".goal_fs input", t).prop("checked");
                var mvp = $(".goal_mvp input", t).prop("checked");

                var result = {
                    stype: stype,
                    map: map,
                    rank: rankNum,
                    flagship: flagship,
                    mvp: mvp };
                self.goalTemplates[t.index()] = result;
                GoalTemplateManager.save( self.goalTemplates );
            }

            // Goal Template Edit & Save button events
            $(".tab_expcalc").on("click", ".goal_template .goal_edit", function() {
                var goalBox = $(this).parent().parent();
                goalTemplateEdit(goalBox);
            });

            $(".tab_expcalc").on("click", ".goal_template .goal_save", function() {
                var goalBox = $(this).parent().parent();
                goalTemplateSave(goalBox);
                goalTemplateSetupUI(self.goalTemplates[ goalBox.index() ], goalBox);
                goalTemplateShow(goalBox);
            });

            $(".tab_expcalc").on("click", ".goal_template .goal_rem", function() {
                var goalBox = $(this).parent().parent();
                goalTemplateRemove(goalBox);
            });

            $(".tab_expcalc").on("click", ".goal_template .goal_up", function() {
                var goalBox = $(this).parent().parent();
                var ind = goalBox.index();
                goalTemplateSwap(ind, ind-1);
            });

            $(".tab_expcalc").on("click", ".goal_template .goal_down", function() {
                var goalBox = $(this).parent().parent();
                var ind = goalBox.index();
                goalTemplateSwap(ind, ind+1);
            });

            // inserting existing templates
            $.each(this.goalTemplates, function(i,x) {
                var goalBox = $(".tab_expcalc .factory .goal_template").clone();
                goalTemplateSetupUI(self.goalTemplates[i], goalBox);
                goalTemplateShow(goalBox);

                goalBox.appendTo(".tab_expcalc .box_goal_templates");
            });

            $(".tab_expcalc a.new_template").on("click", function () {
                var goalBox = $(".tab_expcalc .factory .goal_template").clone();
                var dat = GoalTemplateManager.newTemplate();
                self.goalTemplates.push(dat);
                GoalTemplateManager.save( self.goalTemplates );
                goalTemplateSetupUI(dat, goalBox);
                goalTemplateShow(goalBox);
                goalBox.appendTo(".tab_expcalc .box_goal_templates");
            });

            // TODO: filter feature (turn on / clear)
            // TODO: enable/disable
            // TODO: apply to goals

			// Remove from Goals Button
			$(".tab_expcalc").on("click", ".ship_rem", function(){
				editingBox = $(this).parent();
				delete self.goals["s"+ editingBox.data("id") ];
				self.save();
				//window.location.reload();

				$(".ship_save", editingBox).hide();
				$(".ship_edit", editingBox).hide();
				$(".ship_rem", editingBox).hide();
				editingBox.addClass("inactive");
				var ThisShip = KC3ShipManager.get(editingBox.data("id"));
				if(ThisShip.master().api_aftershipid > 0 && ThisShip.level<ThisShip.master().api_afterlv){
					$(".tab_expcalc .box_recommend .clear").remove();
					editingBox.appendTo(".tab_expcalc .box_recommend");
					$("<div />").addClass("clear").appendTo(".tab_expcalc .box_recommend");
				}else{
					$(".tab_expcalc .box_other .clear").remove();
					editingBox.appendTo(".tab_expcalc .box_other");
					$("<div />").addClass("clear").appendTo(".tab_expcalc .box_other");
				}
			});

			// Show all ship_save
			var goalBox;
			$.each(KC3ShipManager.list, function(index, ThisShip){
				if(!ThisShip.lock){ return true; }

				// Create the ship box
				goalBox = $(".tab_expcalc .factory .ship_goal").clone();
				goalBox.attr("id", "goalBox"+ThisShip.rosterId);
				goalBox.data("id", ThisShip.rosterId);

				// Icon and level, common for all categories
				$(".ship_icon img", goalBox).attr("src", KC3Meta.shipIcon(ThisShip.masterId) );
				$(".ship_icon img", goalBox).attr("title", ThisShip.name() + ' (' + ThisShip.rosterId + ')' );
				$(".ship_name", goalBox).text( ThisShip.name() );
				$(".ship_type", goalBox).text( ThisShip.stype() );
				$(".ship_lv .ship_value", goalBox).text( ThisShip.level );

				// If ship already on the current goals
				if(typeof self.goals["s"+ThisShip.rosterId] != "undefined"){
					$(".ship_edit", goalBox).show();
					$(".ship_rem", goalBox).show();
					goalBox.appendTo(".tab_expcalc .box_goals");

					self.recompute( ThisShip.rosterId );
					return true;
				}

				goalBox.addClass("inactive");

				// If still has next remodel, add to recommendations
				if(ThisShip.master().api_aftershipid > 0 && ThisShip.level<ThisShip.master().api_afterlv){
					$(".ship_target .ship_value", goalBox).text( ThisShip.master().api_afterlv );
					goalBox.appendTo(".tab_expcalc .box_recommend");
					return true;
				}

				// If this is the last remodel stage, add to others
				if(ThisShip.level<99){
					$(".ship_target .ship_value", goalBox).text( 99 );
				}else{
					$(".ship_target .ship_value", goalBox).text( 155 );
				}
				goalBox.appendTo(".tab_expcalc .box_other");
			});

			//this.save();

			$("<div />").addClass("clear").appendTo(".tab_expcalc .box_recommend");
			$("<div />").addClass("clear").appendTo(".tab_expcalc .box_other");
		},

		save: function(){
			localStorage.goals = JSON.stringify(this.goals);
		},

		recompute: function( rosterId ){
			var goalBox = $("#goalBox"+rosterId);
			var grindData = this.goals["s"+rosterId];
			var ThisShip = KC3ShipManager.get( rosterId );
			var MasterShip = ThisShip.master();

			// This has just been added, no grinding data yet, initialize defaults
			if(grindData.length === 0){
				// As much as possible use arrays nowadays to shrink JSON size, we might run out of the 5MB localStorage allocated for our app
				grindData = [
					/*0*/ (MasterShip.api_aftershipid > 0 && ThisShip.level<MasterShip.api_afterlv)?MasterShip.api_afterlv:(ThisShip.level<99)?99:150, // target level
					/*1*/ 1, // world
					/*2*/ 1, // map
					/*3*/ 1, // node
					/*4*/ 6, // E=1 D=2 C=3 B=4 A=5 S=6 SS=7
					/*5*/ 0, // flagship
					/*6*/ 0 // mvp
				];
				this.goals["s"+ThisShip.rosterId] = grindData;
			}else{

			}

			// Target level
			$(".ship_target .ship_value", goalBox).text( grindData[0] );

			// Experience Left
			var expLeft = KC3Meta.expShip(grindData[0])[1] - ThisShip.exp[0];
			$(".ship_exp .ship_value", goalBox).text( expLeft );

			// Base Experience: MAP
			$(".ship_map .ship_value", goalBox).text( grindData[1]+"-"+grindData[2] );
			var expPerSortie = this.maplist[ grindData[1]+"-"+grindData[2] ];

			// Exp Modifier: MVP
			$(".ship_mvp .ship_value", goalBox).text( grindData[6]?"Yes":"No" );
			$(".ship_mvp .ship_value", goalBox).css('color',(grindData[6]? "#e33" : "#039")); //yes : light red, no : deep blue
			if(grindData[6]===1){ expPerSortie = expPerSortie * 2; }

			// Exp Modifier: FLAGSHIP
			$(".ship_fs .ship_value", goalBox).text( grindData[5]?"Yes":"No" );
			$(".ship_mvp .ship_value", goalBox).css('color',(grindData[6]? "#e33" : "#039"));
			if(grindData[5]===1){ expPerSortie = expPerSortie * 1.5; }

			// Exp Modifier: RANK
			$(".ship_rank .ship_value", goalBox).text( this.rankNames[grindData[4]] );
			expPerSortie = expPerSortie * this.rankFactors[grindData[4]];

			// RESULT: Battles Left
			$(".ship_result .ship_value", goalBox).text( Math.ceil(expLeft / expPerSortie) );
		}

	};

})();
<|endoftext|>


<commit_before>(function () {
    "use strict";

    requirejs.config({
    	urlArgs: '_=' + Date.now(), // Cache bust
    	paths: {
    		text: '../node_modules/minify/node_modules/text/text',
    		minify: '../node_modules/minify/minify'
    	}
    });
})();
<commit_msg>Revised dependency path due to npm 3.x.x<commit_after>(function () {
    "use strict";

    requirejs.config({
    	urlArgs: '_=' + Date.now(), // Cache bust
    	paths: {
    		text: '../node_modules/text/text',
    		minify: '../node_modules/minify/minify'
    	}
    });
})();
<|endoftext|>


<commit_before>"use strict";

var starterkit_manager = function (pl) {
  var path = require('path'),
    fs = require('fs-extra'),
    JSON5 = require('json5'),
    _ = require('lodash'),
    paths = pl.config.paths;

  function loadStarterKit(starterkitName) {
    try {
      var kit = require(starterkitName);
    } catch (ex) {
      console.log(ex);
      console.log(starterkitName + ' not found, please use npm to install it first');
    }
    console.log(kit);
  }

  function listStarterkits() {
    console.log('https://github.com/search?utf8=%E2%9C%93&q=starterkit+in%3Aname%2C+user%3Apattern-lab&type=Repositories&ref=searchresults');
  }

  function packStarterkit() {

  }

  return {
    load_starterkit: function (starterkitName) {
      loadStarterKit(starterkitName);
    },
    list_starterkits: function () {
      listStarterkits();
    },
    pack_starterkit: function () {
      packStarterkit();
    }
  };

};

module.exports = starterkit_manager;
<commit_msg>rudimentary starterkit support<commit_after>"use strict";

var starterkit_manager = function (pl) {
  var path = require('path'),
    fs = require('fs-extra'),
    JSON5 = require('json5'),
    _ = require('lodash'),
    paths = pl.config.paths;

  function loadStarterKit(starterkitName) {
    try {
      var kitPath = path.resolve(
        path.join(process.cwd(), 'node_modules', starterkitName, pl.config.starterkitSubDir)
      );
      var kitPathDirExists = fs.statSync(kitPath).isDirectory();
      if (kitPathDirExists) {

        //todo check and prompt user is paths().source is not empty

        fs.copy(kitPath, paths.source.root, function(ex) {
          if (ex) {
            console.error(ex);
          }
          console.log('starterkit ' + starterkitName + ' loaded successfully.');
        });

      }
    } catch (ex) {
      console.log(ex);
      console.log(starterkitName + ' not found, please use npm to install it first');
    }
  }

  function listStarterkits() {
    console.log('https://github.com/search?utf8=%E2%9C%93&q=starterkit+in%3Aname%2C+user%3Apattern-lab&type=Repositories&ref=searchresults');
  }

  function packStarterkit() {

  }

  return {
    load_starterkit: function (starterkitName) {
      loadStarterKit(starterkitName);
    },
    list_starterkits: function () {
      listStarterkits();
    },
    pack_starterkit: function () {
      packStarterkit();
    }
  };

};

module.exports = starterkit_manager;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 "Werner Maisl"
 *
 * This file is part of Aurorastation-Wi
 * Aurorastation-Wi is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

new Vue({
    el: '#app',
    data: {
        faxstatus: "Loading Faxmachines",
        faxtitle: "",
        faxbody: "",
        faxannounce: true,
        faxtargets: "",
        faxmachines: ["Loading Faxmachines..."],
        faxresponse: null,
        faxccia: false,
        faxcciareceivername: "",
        faxcciareceiverrank: "",
        faxcciareceiverstation: "NSS Aurora",
        faxcciasendername: "",
        faxcciasenderrank: "",
        faxcciasenderstation: "NTCC Odin",
        faxcciasignature: "",
        faxcciasignaturei: false,
        faxcciasignatureb: false,
        faxcciasignatureu: false,
        faxcciaroundtime: "",

        report: "Ready",
        reporttitle: "",
        reportbody: "",
        reporttype: "ccia",
        reportsender: "",
        reportannounce: true

    },

    computed: {
        faxcciasender: function(){
            return this.faxcciasendername + ", " + this.faxcciasenderrank + ", " + this.faxcciasenderstation;
        },

        faxcciareceiver: function(){
            return this.faxcciareceivername + ", " + this.faxcciareceiverrank + ", " + this.faxcciareceiverstation;
        },

        faxdtgstring: function(){
            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth()+1; //January is 0!
            var yyyy = today.getFullYear()+442;

            return dd + "-" + this.faxcciaroundtime + "-TAU CETI STANDARD-" + mm + "-" + yyyy
        },

        cciafaxready: function(){
            return  this.faxtitle != "" &&
                this.faxbody != "" &&
                this.faxtargets != "" &&
                this.faxcciareceivername != "" &&
                this.faxcciareceiverrank != "" &&
                this.faxcciareceiverstation != "" &&
                this.faxcciasendername != "" &&
                this.faxcciasenderrank != "" &&
                this.faxcciasenderstation != "" &&
                this.faxcciasignature != "" &&
                this.faxcciaroundtime != ""
        },

        faxcciabody: function(){
            return  'TO: '+this.faxcciareceiver +'\r\n' +
                    'FROM: '+this.faxcciasender +'\r\n' +
                    'SUBJECT: '+this.faxtitle+'\r\n' +
                    '
' +
                    'BODY: \r\n' +
                    this.faxbody +
                    '
' +
                    'DTG: '+this.faxdtgstring+'\r\n' +
                    'SIGN: '+this.faxcciasignature+''
        }
    },

    ready: function(){
        //Get the available faxmachines
        this.getfaxmachines();
    },

    methods: {
        getfaxmachines: function()
        {
            this.$http.get('/server/live/faxmachines').then(
            function(response){
                this.$set('faxmachines',response.json());
                this.$set('faxstatus','Waiting for User Input')
            },
            function(response)
            {
                console.log("Failed to get the fax machines");
                this.$set('faxstatus',"Error getting faxmachines")
            }
        );
        },
        sendfax: function()
        {
            this.$set('faxstatus','Sending the fax ...');
            if(this.faxccia)
            {
                this.$http.post('/server/live/sendfax', {
                    'faxtitle':this.faxtitle,
                    'faxbody':this.faxcciabody,
                    'faxtargets': this.faxtargets,
                    'faxannounce': this.faxannounce
                }).then(
                    function(response){
                        this.$set('faxstatus','Fax has been sent');
                        this.$set('faxresponse',response.json())
                        console.log("Fax Sent");
                        console.log(response.json());
                    },
                    function(response){
                        this.$set('faxstatus','Failed to send the fax');
                        console.log("Failed to send the fax");
                    });
            }
            else
            {
                this.$http.post('/server/live/sendfax', {
                    'faxtitle':this.faxtitle,
                    'faxbody':this.faxbody,
                    'faxtargets': this.faxtargets,
                    'faxannounce': this.faxannounce
                }).then(
                    function(response){
                        this.$set('faxstatus','Fax has been sent');
                        this.$set('faxresponse',response.json())
                        console.log("Fax Sent");
                        console.log(response.json());
                    },
                    function(response){
                        this.$set('faxstatus','Failed to send the fax');
                        console.log("Failed to send the fax");
                    });
            }
        },
        sendreport: function()
        {
            this.$set('faxstatus','Sending the fax ...');
            this.$http.post('/server/live/sendreport', {
                'reporttitle':this.reporttitle,
                'reportbody':this.reportbody,
                'reporttype': this.reporttype,
                'reportsender': this.reportsender,
                'reportannounce': this.reportannounce
            }).then(
                function(response){
                    //this.$set('faxstatus','Fax has been sent');
                    //this.$set('faxresponse',response.json())
                    console.log("Report Sent");
                    console.log(response.json());
                },
                function(response){
                    //this.$set('faxstatus','Failed to send the command Report');
                    console.log("Failed to send the Report");
                });
        }
    }
});<commit_msg>Replace fax receiver name<commit_after>/**
 * Copyright (c) 2016 "Werner Maisl"
 *
 * This file is part of Aurorastation-Wi
 * Aurorastation-Wi is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

new Vue({
    el: '#app',
    data: {
        faxstatus: "Loading Faxmachines",
        faxtitle: "",
        faxbody: "",
        faxannounce: true,
        faxtargets: "",
        faxmachines: ["Loading Faxmachines..."],
        faxresponse: null,
        faxccia: false,
        faxcciareceivername: "",
        faxcciareceiverrank: "",
        faxcciareceiverstation: "SCCV Horizon",
        faxcciasendername: "",
        faxcciasenderrank: "",
        faxcciasenderstation: "NTCC Odin",
        faxcciasignature: "",
        faxcciasignaturei: false,
        faxcciasignatureb: false,
        faxcciasignatureu: false,
        faxcciaroundtime: "",

        report: "Ready",
        reporttitle: "",
        reportbody: "",
        reporttype: "ccia",
        reportsender: "",
        reportannounce: true

    },

    computed: {
        faxcciasender: function(){
            return this.faxcciasendername + ", " + this.faxcciasenderrank + ", " + this.faxcciasenderstation;
        },

        faxcciareceiver: function(){
            return this.faxcciareceivername + ", " + this.faxcciareceiverrank + ", " + this.faxcciareceiverstation;
        },

        faxdtgstring: function(){
            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth()+1; //January is 0!
            var yyyy = today.getFullYear()+442;

            return dd + "-" + this.faxcciaroundtime + "-TAU CETI STANDARD-" + mm + "-" + yyyy
        },

        cciafaxready: function(){
            return  this.faxtitle != "" &&
                this.faxbody != "" &&
                this.faxtargets != "" &&
                this.faxcciareceivername != "" &&
                this.faxcciareceiverrank != "" &&
                this.faxcciareceiverstation != "" &&
                this.faxcciasendername != "" &&
                this.faxcciasenderrank != "" &&
                this.faxcciasenderstation != "" &&
                this.faxcciasignature != "" &&
                this.faxcciaroundtime != ""
        },

        faxcciabody: function(){
            return  'TO: '+this.faxcciareceiver +'\r\n' +
                    'FROM: '+this.faxcciasender +'\r\n' +
                    'SUBJECT: '+this.faxtitle+'\r\n' +
                    '
' +
                    'BODY: \r\n' +
                    this.faxbody +
                    '
' +
                    'DTG: '+this.faxdtgstring+'\r\n' +
                    'SIGN: '+this.faxcciasignature+''
        }
    },

    ready: function(){
        //Get the available faxmachines
        this.getfaxmachines();
    },

    methods: {
        getfaxmachines: function()
        {
            this.$http.get('/server/live/faxmachines').then(
            function(response){
                this.$set('faxmachines',response.json());
                this.$set('faxstatus','Waiting for User Input')
            },
            function(response)
            {
                console.log("Failed to get the fax machines");
                this.$set('faxstatus',"Error getting faxmachines")
            }
        );
        },
        sendfax: function()
        {
            this.$set('faxstatus','Sending the fax ...');
            if(this.faxccia)
            {
                this.$http.post('/server/live/sendfax', {
                    'faxtitle':this.faxtitle,
                    'faxbody':this.faxcciabody,
                    'faxtargets': this.faxtargets,
                    'faxannounce': this.faxannounce
                }).then(
                    function(response){
                        this.$set('faxstatus','Fax has been sent');
                        this.$set('faxresponse',response.json())
                        console.log("Fax Sent");
                        console.log(response.json());
                    },
                    function(response){
                        this.$set('faxstatus','Failed to send the fax');
                        console.log("Failed to send the fax");
                    });
            }
            else
            {
                this.$http.post('/server/live/sendfax', {
                    'faxtitle':this.faxtitle,
                    'faxbody':this.faxbody,
                    'faxtargets': this.faxtargets,
                    'faxannounce': this.faxannounce
                }).then(
                    function(response){
                        this.$set('faxstatus','Fax has been sent');
                        this.$set('faxresponse',response.json())
                        console.log("Fax Sent");
                        console.log(response.json());
                    },
                    function(response){
                        this.$set('faxstatus','Failed to send the fax');
                        console.log("Failed to send the fax");
                    });
            }
        },
        sendreport: function()
        {
            this.$set('faxstatus','Sending the fax ...');
            this.$http.post('/server/live/sendreport', {
                'reporttitle':this.reporttitle,
                'reportbody':this.reportbody,
                'reporttype': this.reporttype,
                'reportsender': this.reportsender,
                'reportannounce': this.reportannounce
            }).then(
                function(response){
                    //this.$set('faxstatus','Fax has been sent');
                    //this.$set('faxresponse',response.json())
                    console.log("Report Sent");
                    console.log(response.json());
                },
                function(response){
                    //this.$set('faxstatus','Failed to send the command Report');
                    console.log("Failed to send the Report");
                });
        }
    }
});<|endoftext|>


<commit_before>const server = require('../../server');
const { getter, poster, handler, throws } = require('../../tests/helpers');

describe('log()', () => {
  it('is defined', () => {
    server(parseInt(Math.random() * 10000)).then(ctx => {
      expect(ctx.log).toBeDefined();
      ctx.close();
    });
  });

  it('is inside the middleware', () => {
    const middle = ctx => {
      expect(ctx.log).toBeDefined();
      return 'Hello 世界';
    };
    return getter(middle, {});
  });

  it('has the right methods', () => {
    const middle = ctx => {
      expect(ctx.log.emergency).toBeDefined();
      expect(ctx.log.alert).toBeDefined();
      expect(ctx.log.critical).toBeDefined();
      expect(ctx.log.error).toBeDefined();
      expect(ctx.log.warning).toBeDefined();
      expect(ctx.log.notice).toBeDefined();
      expect(ctx.log.info).toBeDefined();
      expect(ctx.log.debug).toBeDefined();
      return 'Hello 世界';
    };
    return getter(middle, {});
  });

  it('rejects invalid log levels', () => {
    return throws(() => getter([], { log: 'abc' }));
  });
});
<commit_msg>Small test fix<commit_after>const server = require('../../server');
const { getter, poster, handler, throws } = require('../../tests/helpers');

describe('log()', () => {
  it('is defined', () => {
    server(parseInt(1000 + Math.random() * 10000)).then(ctx => {
      expect(ctx.log).toBeDefined();
      ctx.close();
    });
  });

  it('is inside the middleware', () => {
    const middle = ctx => {
      expect(ctx.log).toBeDefined();
      return 'Hello 世界';
    };
    return getter(middle, {});
  });

  it('has the right methods', () => {
    const middle = ctx => {
      expect(ctx.log.emergency).toBeDefined();
      expect(ctx.log.alert).toBeDefined();
      expect(ctx.log.critical).toBeDefined();
      expect(ctx.log.error).toBeDefined();
      expect(ctx.log.warning).toBeDefined();
      expect(ctx.log.notice).toBeDefined();
      expect(ctx.log.info).toBeDefined();
      expect(ctx.log.debug).toBeDefined();
      return 'Hello 世界';
    };
    return getter(middle, {});
  });

  it('rejects invalid log levels', () => {
    return throws(() => getter([], { log: 'abc' }));
  });
});
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------

Copyright 2017 motrohi hirotom1107@gmail.com

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

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

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

------------------------------------------------------------------------
*/
/**
 */
// use "rm-cstyle-cmts"
var rmc = require("../bin/");
// var rmc = require("rm-cstyle-cmts");

// gulp plugin name.
var PLUGIN_NAME = "gulp-rm-cmts";

var through = require("through2");
var PluginError = require("gulp-util").PluginError;

/**
 * remove_ws: default is true;
 * @param { { remove_ws: boolean } } options
 */
module.exports = function (options) {
    options = options || {};
    // default is true;
    const rm_ws = typeof options.remove_ws === "boolean"? options.remove_ws: true;
    /**
     * @this {Transform}
     */
    var transform = function (file, encoding, callback) {
        if (file.isNull()) {
            return callback(null, file);
        }
        if (file.isStream()) {
            this.emit("error", new PluginError(PLUGIN_NAME, 'Streams not supported!'));
        }
        // plugin main
        if (file.isBuffer()) {
            var contents = rmc(file.contents.toString(), rm_ws);
            // Deprecated
            // file.contents = new Buffer(contents);
            // node ^v5.10.0
            file.contents = Buffer.from(contents);
            // // node ^v5.10.0
            // const buf = Buffer.alloc(contents.length);
            // /* const len = */ buf.write(contents, 0);
            // file.contents = buf;
            return callback(null, file);
        }
        this.push(file);
        callback();
    };
    return through.obj(transform);
};
<commit_msg>maintenance<commit_after>/*
-----------------------------------------------------------------------

Copyright 2017 motrohi hirotom1107@gmail.com

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

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

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

------------------------------------------------------------------------
*/
/**
 */
// use "rm-cstyle-cmts"
const rmc = require("../bin/");
// const rmc = require("rm-cstyle-cmts");

// gulp plugin name.
const PLUGIN_NAME = "gulp-rm-cmts";

const through = require("through2");
const PluginError = require("plugin-error");

/**
 * remove_ws: default is true;
 * @param { { remove_ws: boolean } } options
 */
module.exports = function (options) {
    options = options || {};
    // default is true;
    const rm_ws = typeof options.remove_ws === "boolean"? options.remove_ws: true;
    /**
     * @this {Transform}
     */
    const transform = function (file, encoding, callback) {
        if (file.isNull()) {
            return callback(null, file);
        }
        if (file.isStream()) {
            this.emit("error", new PluginError(PLUGIN_NAME, 'Streams not supported!'));
        }
        // plugin main
        if (file.isBuffer()) {
            const contents = rmc(file.contents.toString(), rm_ws);
            // Deprecated
            // file.contents = new Buffer(contents);
            // node ^v5.10.0
            file.contents = Buffer.from(contents);
            // // node ^v5.10.0
            // const buf = Buffer.alloc(contents.length);
            // /* const len = */ buf.write(contents, 0);
            // file.contents = buf;
            return callback(null, file);
        }
        this.push(file);
        callback();
    };
    return through.obj(transform);
};
<|endoftext|>


<commit_before>import { get, set } from '@vueuse/core';
import { computed, getCurrentInstance, ref, watch } from 'kolibri.lib.vueCompositionApi';
import { ContentNodeResource } from 'kolibri.resources';
import { AllCategories, NoCategories } from 'kolibri.coreVue.vuex.constants';
import { deduplicateResources } from '../utils/contentNode';
import { normalizeContentNode } from '../modules/coreLearn/utils';
import useContentNodeProgress from './useContentNodeProgress';

export const searchKeys = [
  'learning_activities',
  'categories',
  'learner_needs',
  'channels',
  'accessibility_labels',
  'languages',
  'grade_levels',
];

const { fetchContentNodeProgress } = useContentNodeProgress();

export default function useSearch(store, router) {
  // Get store and router references from the curent instance
  // but allow them to be passed in to allow for dependency
  // injection, primarily for tests.
  store = store || getCurrentInstance().proxy.$store;
  router = router || getCurrentInstance().proxy.$router;
  const route = computed(() => store.state.route);

  const searchLoading = ref(false);
  const moreLoading = ref(false);
  const _results = ref([]);
  const more = ref(null);
  const labels = ref(null);

  let descendant;

  function setSearchWithinDescendant(d) {
    descendant = d;
  }

  const searchTerms = computed({
    get() {
      const searchTerms = {};
      const query = get(route).query;
      for (let key of searchKeys) {
        const obj = {};
        if (query[key]) {
          for (let value of query[key].split(',')) {
            obj[value] = true;
          }
        }
        searchTerms[key] = obj;
      }
      searchTerms.keywords = query.keywords || '';
      return searchTerms;
    },
    set(value) {
      const query = { ...get(route).query };
      for (let key of searchKeys) {
        const val = Object.keys(value[key] || {})
          .filter(Boolean)
          .join(',');
        if (val.length) {
          query[key] = Object.keys(value[key]).join(',');
        } else {
          delete query[key];
        }
      }
      if (value.keywords && value.keywords.length) {
        query.keywords = value.keywords;
      } else {
        delete query.keywords;
      }
      // Just catch an error from making a redundant navigation rather
      // than try to precalculate this.
      router.push({ ...get(route), query }).catch(() => console.error('BAD'));
    },
  });

  const displayingSearchResults = computed(() =>
    // Happily this works even for keywords, because calling Object.keys
    // on a string value will give an array of the indexes of a string
    // for an empty string, this array will be empty, meaning that this
    // check still works!
    Object.values(get(searchTerms)).some(v => Object.keys(v).length)
  );

  function search() {
    const getParams = {
      include_coach_content:
        store.getters.isAdmin || store.getters.isCoach || store.getters.isSuperuser,
    };
    if (descendant) {
      getParams.tree_id = descendant.tree_id;
      getParams.lft__gt = descendant.lft;
      getParams.rght__lt = descendant.rght;
    }
    if (get(displayingSearchResults)) {
      getParams.max_results = 25;
      const terms = get(searchTerms);
      set(searchLoading, true);
      for (let key of searchKeys) {
        if (key === 'categories') {
          if (terms[key][AllCategories]) {
            getParams['categories__isnull'] = false;
            continue;
          } else if (terms[key][NoCategories]) {
            getParams['categories__isnull'] = true;
            continue;
          }
        }
        if (key === 'channels' && descendant) {
          continue;
        }
        const keys = Object.keys(terms[key]);
        if (keys.length) {
          getParams[key] = keys;
        }
      }
      if (terms.keywords) {
        getParams.keywords = terms.keywords;
      }
      if (store.getters.isUserLoggedIn) {
        fetchContentNodeProgress(getParams);
      }
      ContentNodeResource.fetchCollection({ getParams }).then(data => {
        set(_results, (data.results || []).map(normalizeContentNode));
        set(more, data.more);
        set(labels, data.labels);
        set(searchLoading, false);
      });
    } else if (descendant) {
      getParams.max_results = 1;
      ContentNodeResource.fetchCollection({ getParams }).then(data => {
        set(labels, data.labels);
        set(more, null);
      });
    } else {
      // Clear labels if no search results displaying
      // and we're not gathering labels from the descendant
      set(more, null);
      set(labels, null);
    }
  }

  function searchMore() {
    if (get(displayingSearchResults) && get(more) && !get(moreLoading)) {
      set(moreLoading, true);
      if (store.getters.isUserLoggedIn) {
        fetchContentNodeProgress(get(more));
      }
      return ContentNodeResource.fetchCollection({ getParams: get(more) }).then(data => {
        set(_results, [...get(_results), ...(data.results || []).map(normalizeContentNode)]);
        set(more, data.more);
        set(labels, data.labels);
        set(moreLoading, false);
      });
    }
  }

  function removeFilterTag({ value, key }) {
    if (key === 'keywords') {
      set(searchTerms, {
        ...get(searchTerms),
        [key]: '',
      });
    } else {
      const keyObject = get(searchTerms)[key];
      delete keyObject[value];
      set(searchTerms, {
        ...get(searchTerms),
        [key]: keyObject,
      });
    }
  }

  function clearSearch() {
    set(searchTerms, {});
  }

  function setCategory(category) {
    set(searchTerms, { ...get(searchTerms), categories: { [category]: true } });
  }

  watch(searchTerms, search);

  // Helper to get the route information in a setup() function
  function currentRoute() {
    return get(route);
  }

  const results = computed(() => {
    return deduplicateResources(get(_results));
  });

  return {
    currentRoute,
    searchTerms,
    displayingSearchResults,
    searchLoading,
    moreLoading,
    results,
    more,
    labels,
    search,
    searchMore,
    removeFilterTag,
    clearSearch,
    setCategory,
    setSearchWithinDescendant,
  };
}
<commit_msg>removing BAD console message<commit_after>import { get, set } from '@vueuse/core';
import { computed, getCurrentInstance, ref, watch } from 'kolibri.lib.vueCompositionApi';
import { ContentNodeResource } from 'kolibri.resources';
import { AllCategories, NoCategories } from 'kolibri.coreVue.vuex.constants';
import { deduplicateResources } from '../utils/contentNode';
import { normalizeContentNode } from '../modules/coreLearn/utils';
import useContentNodeProgress from './useContentNodeProgress';

export const searchKeys = [
  'learning_activities',
  'categories',
  'learner_needs',
  'channels',
  'accessibility_labels',
  'languages',
  'grade_levels',
];

const { fetchContentNodeProgress } = useContentNodeProgress();

export default function useSearch(store, router) {
  // Get store and router references from the curent instance
  // but allow them to be passed in to allow for dependency
  // injection, primarily for tests.
  store = store || getCurrentInstance().proxy.$store;
  router = router || getCurrentInstance().proxy.$router;
  const route = computed(() => store.state.route);

  const searchLoading = ref(false);
  const moreLoading = ref(false);
  const _results = ref([]);
  const more = ref(null);
  const labels = ref(null);

  let descendant;

  function setSearchWithinDescendant(d) {
    descendant = d;
  }

  const searchTerms = computed({
    get() {
      const searchTerms = {};
      const query = get(route).query;
      for (let key of searchKeys) {
        const obj = {};
        if (query[key]) {
          for (let value of query[key].split(',')) {
            obj[value] = true;
          }
        }
        searchTerms[key] = obj;
      }
      searchTerms.keywords = query.keywords || '';
      return searchTerms;
    },
    set(value) {
      const query = { ...get(route).query };
      for (let key of searchKeys) {
        const val = Object.keys(value[key] || {})
          .filter(Boolean)
          .join(',');
        if (val.length) {
          query[key] = Object.keys(value[key]).join(',');
        } else {
          delete query[key];
        }
      }
      if (value.keywords && value.keywords.length) {
        query.keywords = value.keywords;
      } else {
        delete query.keywords;
      }
      // Just catch an error from making a redundant navigation rather
      // than try to precalculate this.
      router.push({ ...get(route), query }).catch(() => {});
    },
  });

  const displayingSearchResults = computed(() =>
    // Happily this works even for keywords, because calling Object.keys
    // on a string value will give an array of the indexes of a string
    // for an empty string, this array will be empty, meaning that this
    // check still works!
    Object.values(get(searchTerms)).some(v => Object.keys(v).length)
  );

  function search() {
    const getParams = {
      include_coach_content:
        store.getters.isAdmin || store.getters.isCoach || store.getters.isSuperuser,
    };
    if (descendant) {
      getParams.tree_id = descendant.tree_id;
      getParams.lft__gt = descendant.lft;
      getParams.rght__lt = descendant.rght;
    }
    if (get(displayingSearchResults)) {
      getParams.max_results = 25;
      const terms = get(searchTerms);
      set(searchLoading, true);
      for (let key of searchKeys) {
        if (key === 'categories') {
          if (terms[key][AllCategories]) {
            getParams['categories__isnull'] = false;
            continue;
          } else if (terms[key][NoCategories]) {
            getParams['categories__isnull'] = true;
            continue;
          }
        }
        if (key === 'channels' && descendant) {
          continue;
        }
        const keys = Object.keys(terms[key]);
        if (keys.length) {
          getParams[key] = keys;
        }
      }
      if (terms.keywords) {
        getParams.keywords = terms.keywords;
      }
      if (store.getters.isUserLoggedIn) {
        fetchContentNodeProgress(getParams);
      }
      ContentNodeResource.fetchCollection({ getParams }).then(data => {
        set(_results, (data.results || []).map(normalizeContentNode));
        set(more, data.more);
        set(labels, data.labels);
        set(searchLoading, false);
      });
    } else if (descendant) {
      getParams.max_results = 1;
      ContentNodeResource.fetchCollection({ getParams }).then(data => {
        set(labels, data.labels);
        set(more, null);
      });
    } else {
      // Clear labels if no search results displaying
      // and we're not gathering labels from the descendant
      set(more, null);
      set(labels, null);
    }
  }

  function searchMore() {
    if (get(displayingSearchResults) && get(more) && !get(moreLoading)) {
      set(moreLoading, true);
      if (store.getters.isUserLoggedIn) {
        fetchContentNodeProgress(get(more));
      }
      return ContentNodeResource.fetchCollection({ getParams: get(more) }).then(data => {
        set(_results, [...get(_results), ...(data.results || []).map(normalizeContentNode)]);
        set(more, data.more);
        set(labels, data.labels);
        set(moreLoading, false);
      });
    }
  }

  function removeFilterTag({ value, key }) {
    if (key === 'keywords') {
      set(searchTerms, {
        ...get(searchTerms),
        [key]: '',
      });
    } else {
      const keyObject = get(searchTerms)[key];
      delete keyObject[value];
      set(searchTerms, {
        ...get(searchTerms),
        [key]: keyObject,
      });
    }
  }

  function clearSearch() {
    set(searchTerms, {});
  }

  function setCategory(category) {
    set(searchTerms, { ...get(searchTerms), categories: { [category]: true } });
  }

  watch(searchTerms, search);

  // Helper to get the route information in a setup() function
  function currentRoute() {
    return get(route);
  }

  const results = computed(() => {
    return deduplicateResources(get(_results));
  });

  return {
    currentRoute,
    searchTerms,
    displayingSearchResults,
    searchLoading,
    moreLoading,
    results,
    more,
    labels,
    search,
    searchMore,
    removeFilterTag,
    clearSearch,
    setCategory,
    setSearchWithinDescendant,
  };
}
<|endoftext|>