<commit_before>import { Vue } from 'shared'

window.GobiertoPlans.PlanTypesController = (function() {

    function PlanTypesController() {}

    PlanTypesController.prototype.show = function() {
      _loadPlan();
    };

    function _loadPlan() {

      // filters
      Vue.filter('translate', function (key) {
        if (!key) return
        return key[I18n.locale] || key["es"] || key["en"] || Object.values(key)[0] // fallback translations
      });

      Vue.filter('percent', function (value) {
        if (!value) return
        return (value / 100).toLocaleString(I18n.locale, { style: 'percent', maximumSignificantDigits: 4 })
      });

      Vue.filter('date', function (date) {
        if (!date) return
        return new Date(date).toLocaleString(I18n.locale, { year: 'numeric', month: 'short', day: 'numeric' })
      });

      // define the node root component
      Vue.component('node-root', {
        template: '#node-root-template',
        props: ['model'],
        data: function() {
          return {}
        },
        computed: {
          progressWidth: function () {
            return `${this.model.attributes.progress}%`
          }
        },
        methods: {
          open: function() {
            // Trigger event
            this.$emit('selection', { ...this.model });
          }
        }
      });

      // define the node list component
      Vue.component('node-list', {
        template: '#node-list-template',
        props: ['model', 'level'],
        data: function() {
          return {
            isOpen: false
          }
        },
        methods: {
          setActive: function() {
            if (this.model.type === "category" && !this.model.max_level) {
              var model = { ...this.model };

              this.$emit('selection', model);
            }

            if (this.model.type === "category" && this.model.max_level) {
              this.$emit("toggle");
              this.isOpen = !this.isOpen;
            }
          },
          getLabel: function(level, number_of_elements) {
            var key = this.level["level" + (level + 1)]
            return (number_of_elements == 1 ? key["one"] : key["other"])
          }
        }
      });

      // define the table view component
      Vue.component('table-view', {
        template: '#table-view-template',
        props: ['model', 'header', 'open'],
        data: function() {
          return {}
        },
        methods: {
          getProject: function() {
            if (this.open) {
              var project = { ...this.model };

              this.$emit('selection', project);
            }
          }
        }
      });

      // main object
      new Vue({
        el: '#gobierto-planification',
        name: 'gobierto-planification',
        data: {
          json: {},
          levelKeys: {},
          optionKeys: [],
          activeNode: {},
          showTable: {},
          showTableHeader: true,
          openNode: false,
          rootid: 0
        },
        created: function() {
          this.getJson();

          let vm = this
          function locationHashChanged() {
              vm.getPermalink(window.location.hash.substring(1))
          }

          window.onhashchange = locationHashChanged
        },
        watch: {
          activeNode: {
            handler: function(node) {
              this.showTable = {}
              // update hash when a new node is active
              this.setPermalink()

              this.isOpen(node.level)
            },
            deep: true
          }
        },
        computed: {
          globalProgress: function () {
            return _.meanBy(this.json, 'attributes.progress')
          },
          availableOpts: function () {
            // Filter options object only to those values present in the configuration (optionKeys)
            return _.pick(this.activeNode.attributes.options, _.filter(_.keys(this.activeNode.attributes.options), function (o) {
              return _.includes(_.keys(this.optionKeys), o.toString().toLowerCase())
            }.bind(this)));
          }
        },
        methods: {
          getJson: function() {
            $.getJSON(window.location.href, {format: 'json'}, function(json) {
              // Tree with categories and the leaves (nodes)
              var data = json["plan_tree"];
              // Nodes can have variable attributes and these are their keys
              var optionKeys = json["option_keys"];
              // Keys for different levels
              var levelKeys = json["level_keys"];
              // If you can see the table header
              var showTableHeader = json["show_table_header"];
              // If you can open a node (project)
              var openNode = json["open_node"];

              // Hide spinner
              $(".js-toggle-overlay").removeClass('is-active');

              this.json = data;
              this.levelKeys = levelKeys;
              this.showTableHeader = showTableHeader;
              this.openNode = openNode;
              this.optionKeys = Object.keys(optionKeys).reduce(function(c, k) {
                return (c[k.toLowerCase()] = optionKeys[k]), c;
              }, {});

              // Parse permalink
              if (window.location.hash) {
                this.getPermalink(window.location.hash.substring(1))
              }

            }.bind(this));
          },
          color: function() {
            return this.rootid % this.json.length + 1;
          },
          setRootColor: function(index) {
            return index % this.json.length + 1;
          },
          setSelection: function(model) {
            this.activeNode = model;

            // To know the root node
            this.rootid = this.activeNode.uid.toString().charAt(0);
          },
          isOpen: function(level) {
            if (this.activeNode.level === undefined) return false

            let isOpen = false
            if (this.activeNode.level === 0) {
              // activeNode = 0, it means is a "line"
              // then, it shows level_0 and level_1
              isOpen = (level < 2)
            } else {
              // activeNode = X
              // then, it shows level_0 and level_(X+1), but not those between
              isOpen = (level === 0) || (level === (this.activeNode.level + 1))
            }

            return isOpen
          },
          typeOf: function(val) {
            if (_.isString(val)) {
              return "string"
            } else if (_.isArray(val)) {
              return "array"
            }
            return "object";
          },
          toggle: function(i) {
            Vue.set(this.showTable, i, !(this.showTable[i]));
          },
          getLabel: function(level, number_of_elements) {
            var l = (_.keys(this.levelKeys).length === (level + 1)) ? level : (level + 1);
            var key = this.levelKeys["level" + l];
            return (number_of_elements == 1 ? key["one"] : key["other"]);
          },
          getParent: function() {
            // Initialize args
            var breakpoint = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;

            // From uid, turno into array all parents, and drop last item (myself)
            var ancestors = _.dropRight(this.activeNode.uid.split('.')).map(Number);

            var current = this.json; // First item. ROOT item
            for (var i = 0; i < ancestors.length; i++) {
              if (i === breakpoint) {
                // If there is breakpoint, I get the corresponding ancestor set by breakpoint
                break;
              }

              if (!_.isArray(current)) {
                current = current.children;
              }
              current = current[ancestors[i]];
            }

            return current || {}
          },
          setParent: function() {
            // Initialize args
            var breakpoint = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
            //hack 3rd level (3rd level has no SECTION)
            if (breakpoint === 3) breakpoint = breakpoint - 1;

            this.activeNode = this.getParent(breakpoint);
          },
          setPermalink: function () {
            window.location.hash = this.activeNode.uid
          },
          getPermalink: function (hash) {
            let found = this.searchByUid(hash, this.json)
            if (found) {
              this.setSelection(found)
            }
          },
          searchByUid: function(id, data) {
            let result = false

            if (_.isArray(data)) {
              _.each(data, d => {
                result = findNodeByProp(id, d, 'uid')

                // Return false to break loop
                if (result !== false) {
                  return false;
                }
              })
            } else {
              result = findNodeByProp(id, data, 'uid')
            }

            return result
          }
        }
      })

      function findNodeByProp(id, currentNode, prop = 'id') {
        var i,
          currentChild,
          result;

        if (id == currentNode[prop]) {
          return currentNode;
        } else {

          // Use a for loop instead of forEach to avoid nested functions
          // Otherwise "return" will not work properly
          for (i = 0; i < currentNode.children.length; i += 1) {
            currentChild = currentNode.children[i];

            // Search in the current child
            result = findNodeByProp(id, currentChild, prop);

            // Return the result if the node has been found
            if (result !== false) {
              return result;
            }
          }

          // The node has not been found and we have no more options
          return false;
        }
      }
    }

    return PlanTypesController;
  })();

  window.GobiertoPlans.plan_types_controller = new GobiertoPlans.PlanTypesController;
<commit_msg>leaf node open when must<commit_after>import { Vue } from 'shared'

window.GobiertoPlans.PlanTypesController = (function() {

    function PlanTypesController() {}

    PlanTypesController.prototype.show = function() {
      _loadPlan();
    };

    function _loadPlan() {

      // filters
      Vue.filter('translate', function (key) {
        if (!key) return
        return key[I18n.locale] || key["es"] || key["en"] || Object.values(key)[0] // fallback translations
      });

      Vue.filter('percent', function (value) {
        if (!value) return
        return (value / 100).toLocaleString(I18n.locale, { style: 'percent', maximumSignificantDigits: 4 })
      });

      Vue.filter('date', function (date) {
        if (!date) return
        return new Date(date).toLocaleString(I18n.locale, { year: 'numeric', month: 'short', day: 'numeric' })
      });

      // define the node root component
      Vue.component('node-root', {
        template: '#node-root-template',
        props: ['model'],
        data: function() {
          return {}
        },
        computed: {
          progressWidth: function () {
            return `${this.model.attributes.progress}%`
          }
        },
        methods: {
          open: function() {
            // Trigger event
            this.$emit('selection', { ...this.model });
          }
        }
      });

      // define the node list component
      Vue.component('node-list', {
        template: '#node-list-template',
        props: ['model', 'level'],
        data: function() {
          return {
            isOpen: false
          }
        },
        methods: {
          setActive: function() {
            if (this.model.type === "category" && !this.model.max_level) {
              var model = { ...this.model };

              this.$emit('selection', model);
            }

            if (this.model.type === "category" && this.model.max_level) {
              this.$emit("toggle");
              this.isOpen = !this.isOpen;
            }
          },
          getLabel: function(level, number_of_elements) {
            var key = this.level["level" + (level + 1)]
            return (number_of_elements == 1 ? key["one"] : key["other"])
          }
        }
      });

      // define the table view component
      Vue.component('table-view', {
        template: '#table-view-template',
        props: ['model', 'header', 'open'],
        data: function() {
          return {}
        },
        methods: {
          getProject: function(row) {
            if (this.open) {
              // var project = { ...this.model };
              var project = { ...row };

              this.$emit('selection', project);
            }
          }
        }
      });

      // main object
      new Vue({
        el: '#gobierto-planification',
        name: 'gobierto-planification',
        data: {
          json: {},
          levelKeys: {},
          optionKeys: [],
          activeNode: {},
          showTable: {},
          showTableHeader: true,
          openNode: false,
          rootid: 0
        },
        created: function() {
          this.getJson();

          let vm = this
          function locationHashChanged() {
              vm.getPermalink(window.location.hash.substring(1))
          }

          window.onhashchange = locationHashChanged
        },
        watch: {
          activeNode: {
            handler: function(node) {
              this.showTable = {}
              // update hash when a new node is active
              this.setPermalink()

              this.isOpen(node.level)
            },
            deep: true
          }
        },
        computed: {
          globalProgress: function () {
            return _.meanBy(this.json, 'attributes.progress')
          },
          availableOpts: function () {
            // Filter options object only to those values present in the configuration (optionKeys)
            return _.pick(this.activeNode.attributes.options, _.filter(_.keys(this.activeNode.attributes.options), function (o) {
              return _.includes(_.keys(this.optionKeys), o.toString().toLowerCase())
            }.bind(this)));
          }
        },
        methods: {
          getJson: function() {
            $.getJSON(window.location.href, {format: 'json'}, function(json) {
              // Tree with categories and the leaves (nodes)
              var data = json["plan_tree"];
              // Nodes can have variable attributes and these are their keys
              var optionKeys = json["option_keys"];
              // Keys for different levels
              var levelKeys = json["level_keys"];
              // If you can see the table header
              var showTableHeader = json["show_table_header"];
              // If you can open a node (project)
              var openNode = json["open_node"];

              // Hide spinner
              $(".js-toggle-overlay").removeClass('is-active');

              this.json = data;
              this.levelKeys = levelKeys;
              this.showTableHeader = showTableHeader;
              this.openNode = openNode;
              this.optionKeys = Object.keys(optionKeys).reduce(function(c, k) {
                return (c[k.toLowerCase()] = optionKeys[k]), c;
              }, {});

              // Parse permalink
              if (window.location.hash) {
                this.getPermalink(window.location.hash.substring(1))
              }

            }.bind(this));
          },
          color: function() {
            return this.rootid % this.json.length + 1;
          },
          setRootColor: function(index) {
            return index % this.json.length + 1;
          },
          setSelection: function(model) {
            this.activeNode = model;

            // To know the root node
            this.rootid = this.activeNode.uid.toString().charAt(0);
          },
          isOpen: function(level) {
            if (this.activeNode.level === undefined) return false

            let isOpen = false
            if (this.activeNode.level === 0) {
              // activeNode = 0, it means is a "line"
              // then, it shows level_0 and level_1
              isOpen = (level < 2)
            } else {
              // activeNode = X
              if (this.activeNode.type === "node") {
                // type = node, it means there's no further levels, then it shows as previous one
                isOpen = (level === 0) || (level === this.activeNode.level)
              } else {
                // then, it shows level_0 and level_(X+1), but not those between
                isOpen = (level === 0) || (level === (this.activeNode.level + 1))
              }
            }

            return isOpen
          },
          typeOf: function(val) {
            if (_.isString(val)) {
              return "string"
            } else if (_.isArray(val)) {
              return "array"
            }
            return "object";
          },
          toggle: function(i) {
            Vue.set(this.showTable, i, !(this.showTable[i]));
          },
          getLabel: function(level, number_of_elements) {
            var l = (_.keys(this.levelKeys).length === (level + 1)) ? level : (level + 1);
            var key = this.levelKeys["level" + l];
            return (number_of_elements == 1 ? key["one"] : key["other"]);
          },
          getParent: function() {
            // Initialize args
            var breakpoint = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;

            // From uid, turno into array all parents, and drop last item (myself)
            var ancestors = _.dropRight(this.activeNode.uid.split('.')).map(Number);

            var current = this.json; // First item. ROOT item
            for (var i = 0; i < ancestors.length; i++) {
              if (i === breakpoint) {
                // If there is breakpoint, I get the corresponding ancestor set by breakpoint
                break;
              }

              if (!_.isArray(current)) {
                current = current.children;
              }
              current = current[ancestors[i]];
            }

            return current || {}
          },
          setParent: function() {
            // Initialize args
            var breakpoint = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
            //hack 3rd level (3rd level has no SECTION)
            if (breakpoint === 3) breakpoint = breakpoint - 1;

            this.activeNode = this.getParent(breakpoint);
          },
          setPermalink: function () {
            window.location.hash = this.activeNode.uid
          },
          getPermalink: function (hash) {
            let found = this.searchByUid(hash, this.json)
            if (found) {
              this.setSelection(found)
            }
          },
          searchByUid: function(id, data) {
            let result = false

            if (_.isArray(data)) {
              _.each(data, d => {
                result = findNodeByProp(id, d, 'uid')

                // Return false to break loop
                if (result !== false) {
                  return false;
                }
              })
            } else {
              result = findNodeByProp(id, data, 'uid')
            }

            return result
          }
        }
      })

      function findNodeByProp(id, currentNode, prop = 'id') {
        var i,
          currentChild,
          result;

        if (id == currentNode[prop]) {
          return currentNode;
        } else {

          // Use a for loop instead of forEach to avoid nested functions
          // Otherwise "return" will not work properly
          for (i = 0; i < currentNode.children.length; i += 1) {
            currentChild = currentNode.children[i];

            // Search in the current child
            result = findNodeByProp(id, currentChild, prop);

            // Return the result if the node has been found
            if (result !== false) {
              return result;
            }
          }

          // The node has not been found and we have no more options
          return false;
        }
      }
    }

    return PlanTypesController;
  })();

  window.GobiertoPlans.plan_types_controller = new GobiertoPlans.PlanTypesController;
<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';
import ReactPlayer from 'react-player';

import {
    CustomScrollBarCSS,
    PreviewImage,
    PreviewWrapper,
} from '../../baseStyle';

const ReportPreviewWrapper = styled.div`
    font-family: "Microsoft JhengHei";
    margin: 3vw 15vw;
    max-height: 40vh;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-word;

    ${CustomScrollBarCSS}
`;

const VideoPreviewWrapper = PreviewWrapper.extend`
    margin: 10px;
`;

const ReportPreview = ({
    imagePreviewUrl,
    reportType,
    resizedHeight,
    resizedWidth,
    text,
    video,
}) => (
    <ReportPreviewWrapper>
        {
            reportType === 'image' && imagePreviewUrl ?
                <PreviewWrapper>
                    <PreviewImage
                        resizedHeight={resizedHeight}
                        resizedWidth={resizedWidth}
                        src={imagePreviewUrl}
                    />
                </PreviewWrapper>
            : null
        }
        {
            reportType === 'video' && video ?
                <VideoPreviewWrapper>
                    <ReactPlayer
                        height="100%"
                        url={video}
                        width="100%"
                    />
                </VideoPreviewWrapper>
            : null
        }
        {text}
    </ReportPreviewWrapper>
);

export default ReportPreview;
<commit_msg>[Style] modify mobile version of report preview<commit_after>import React from 'react';
import styled from 'styled-components';
import ReactPlayer from 'react-player';

import {
    CustomScrollBarCSS,
    PreviewImage,
    PreviewWrapper,
} from '../../baseStyle';

const ReportPreviewWrapper = styled.div`
    font-family: "Microsoft JhengHei";
    max-height: 40vh;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-word;

    @media (max-width: 768px) {
        margin: 3vw 5vw;
    }
    @media (min-width: 769px) {
        margin: 3vw 15vw;
    }

    ${CustomScrollBarCSS}
`;

const VideoPreviewWrapper = PreviewWrapper.extend`
    margin: 10px;
`;

const ReportPreview = ({
    imagePreviewUrl,
    reportType,
    resizedHeight,
    resizedWidth,
    text,
    video,
}) => (
    <ReportPreviewWrapper>
        {
            reportType === 'image' && imagePreviewUrl ?
                <PreviewWrapper>
                    <PreviewImage
                        resizedHeight={resizedHeight}
                        resizedWidth={resizedWidth}
                        src={imagePreviewUrl}
                    />
                </PreviewWrapper>
            : null
        }
        {
            reportType === 'video' && video ?
                <VideoPreviewWrapper>
                    <ReactPlayer
                        height="100%"
                        url={video}
                        width="100%"
                    />
                </VideoPreviewWrapper>
            : null
        }
        {text}
    </ReportPreviewWrapper>
);

export default ReportPreview;
<|endoftext|>


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

  angular.module('character-tracker.charactersheet')
  .service('InventoryService', InventoryService);

  function InventoryService() {
    var items = [
      {name: 'Longsword +1',
       img: 'https://s-media-cache-ak0.pinimg.com/564x/db/5f/d8/db5fd8f1ee5a8f18b70e433f9b026595.jpg',
       desc: 'Longsword with a faint magic aura',
       slot: ['weapon1', 'weapon2', '2h'],
       equipable: true,
       equipped: false,
       effects: [{abbr: 'Magic', value: 1, type: 'weapon'},
                {abbr: 'STR', value: 1}]
      },
      {name: 'Longsword',
       img: 'https://s-media-cache-ak0.pinimg.com/564x/db/5f/d8/db5fd8f1ee5a8f18b70e433f9b026595.jpg',
       desc: 'Longsword with a faint magic aura',
       slot: ['weapon1', 'weapon2', '2h'],
       equipable: true,
       equipped: false,
       effects: false
      },
      {name: 'Tunic +1',
       img: 'https://s-media-cache-ak0.pinimg.com/564x/a9/e8/3e/a9e83ebb9acc1c74128e0bcf50c57a8f.jpg',
       desc: 'Tunic with a faint magic aura',
       slot: ['torso'],
       equipable: true,
       equipped: false,
       effects: [{abbr: 'AC', value: 1, type: 'gear'}]
      },
      {name: 'Belt of Giant Strength',
       img: 'http://www.canonfire.com/wiki/images/2/2e/Belt_of_the_Champion01.jpg',
       desc: '+1 STR',
       slot: ['belt'],
       equipable: true,
       equipped: false,
       effects: [{abbr: 'STR', value: 1, type: 'abilityscore'}]
      },
      {name: 'Potion of Healing',
       img: 'https://s-media-cache-ak0.pinimg.com/236x/43/51/26/4351264b1d04301f59a12f6e167a9f15.jpg',
       desc: '+1 STR',
       slot: ['potion'],
       equipable: false,
       equipped: false,
       effects: [{abbr: 'HEAL', dice: 1, sides: 10, type: 'potion'}]}
    ];

    var armors = [

    ];

    return {
      equipItem: equipItem,
      getItems: getItems,
      getItemAtSlot: getItemAtSlot,
      unequipItem: unequipItem
    }

    function equipItem(item) {
      if (item.equipable) {
        item.equipped = true;
      }
    }

    function getItems() {
      return items;
    }

    function getItemAtSlot(slot){
      console.log(slot);
    }

    function unequipItem(item){
      item.equipped = false;
    }

  }
})<commit_msg>added armor and weapon data<commit_after>(function() {
  'use strict';

  angular.module('character-tracker.charactersheet')
  .service('InventoryService', InventoryService);

  function InventoryService() {
    var items = [
      {name: 'Longsword +1',
       img: 'https://s-media-cache-ak0.pinimg.com/564x/db/5f/d8/db5fd8f1ee5a8f18b70e433f9b026595.jpg',
       desc: 'Longsword with a faint magic aura',
       slot: ['weapon1', 'weapon2', '2h'],
       equipable: true,
       equipped: false,
       effects: [{abbr: 'Magic', value: 1, type: 'weapon'},
                {abbr: 'STR', value: 1}]
      },
      {name: 'Longsword',
       img: 'https://s-media-cache-ak0.pinimg.com/564x/db/5f/d8/db5fd8f1ee5a8f18b70e433f9b026595.jpg',
       desc: 'Longsword with a faint magic aura',
       slot: ['weapon1', 'weapon2', '2h'],
       equipable: true,
       equipped: false,
       effects: false
      },
      {name: 'Tunic +1',
       img: 'https://s-media-cache-ak0.pinimg.com/564x/a9/e8/3e/a9e83ebb9acc1c74128e0bcf50c57a8f.jpg',
       desc: 'Tunic with a faint magic aura',
       slot: ['torso'],
       equipable: true,
       equipped: false,
       effects: [{abbr: 'AC', value: 1, type: 'gear'}]
      },
      {name: 'Belt of Giant Strength',
       img: 'http://www.canonfire.com/wiki/images/2/2e/Belt_of_the_Champion01.jpg',
       desc: '+1 STR',
       slot: ['belt'],
       equipable: true,
       equipped: false,
       effects: [{abbr: 'STR', value: 1, type: 'abilityscore'}]
      },
      {name: 'Potion of Healing',
       img: 'https://s-media-cache-ak0.pinimg.com/236x/43/51/26/4351264b1d04301f59a12f6e167a9f15.jpg',
       desc: '+1 STR',
       slot: ['potion'],
       equipable: false,
       equipped: false,
       effects: [{abbr: 'HEAL', dice: 1, sides: 10, type: 'potion'}]}
    ];

    var armors = [
      {name: 'Padded', img: '', desc: '', slot: ['torso'], equipable: true, type: 'light', cost: 5, armor: 11, maxdex: 100, strreq: 0, weight: 8, stealthdis: true},
      {name: 'Leather', img: '', desc: '',  slot: ['torso'], equipable: true, type: 'light', cost: 10, armor: 11, maxdex: 100, strreq: 0, weight: 10, stealthdis: false},
      {name: 'Studded Leather', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'light', cost: 45, armor: 12, maxdex: 100, strreq: 0, weight: 13, stealthdis: false},
      {name: 'Hide', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'medium', cost: 10, armor: 12, maxdex: 2, strreq: 0, weight: 12, stealthdis: false},
      {name: 'Chain Shirt', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'medium', cost: 50, armor: 13, maxdex: 2, strreq: 0, weight: 20, stealthdis: false},
      {name: 'Scale Mail', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'medium', cost: 50, armor: 14, maxdex: 2, strreq: 0, weight: 45, stealthdis: true},
      {name: 'Breastplate', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'medium', cost: 400, armor: 14, maxdex: 2, strreq: 0, weight: 20, stealthdis: false},
      {name: 'Half Plate', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'medium', cost: 750, armor: 15, maxdex: 2, strreq: 0, weight: 40, stealthdis: true},
      {name: 'Ring Mail', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'heavy', cost: 30, armor: 14, maxdex: 0, strreq: 0, weight: 40, stealthdis: true},
      {name: 'Chain Mail', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'heavy', cost: 75, armor: 16, maxdex: 0, strreq: 13, weight: 55, stealthdis: true},
      {name: 'Splint', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'heavy', cost: 200, armor: 17, maxdex: 0, strreq: 15, weight: 60, stealthdis: true},
      {name: 'Plate', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'heavy', cost: 1500, armor: 18, maxdex: 0, strreq: 15, weight: 65, stealthdis: true},
      {name: 'shield', img: '', desc: '',  slot: ['torso'], equipable: true,  type: 'shield', cost: 10, armor: 2, maxdex: 0, strreq: 15, weight: 65, stealthdis: true},
    ];

    var weapons = [
      {name: 'Club', img: '', desc: '', slot: ['weapon1', 'weapon2'], equipable: true, type: 'simple', cost: 1, damage: 4, damagetype: 'bludgeoning', weight: 2, properties: ['light']},
      {name: 'Dagger', img: '', desc: '', slot: ['weapon1', 'weapon2', 'ranged'], equipable: true, type: 'simple', cost: 2, damage: 4, damagetype: 'piercing', weight: 1, properties: ['light', 'finesse', 'thrown']},
      {name: 'Greatclub', img: '', desc: '', slot: ['2h'], equipable: true, type: 'simple', cost: 2, damage: 8, damagetype: 'bludgeoning', weight: 10, properties: ['two-handed']},
      {name: 'Handaxe', img: '', desc: '', slot: ['weapon1', 'weapon2', 'ranged'], equipable: true, type: 'simple', cost: 5, damage: 6, damagetype: 'slashing', weight: 2, properties: ['light', 'thrown']},
      {name: 'Javelin', img: '', desc: '', slot: ['weapon1', 'weapon2', 'ranged'], equipable: true, type: 'simple', cost: 5, damage: 6, damagetype: 'piercing', weight: 2, properties: ['thrown']},
      {name: 'Light Hammer', img: '', desc: '', slot: ['weapon1', 'weapon2', 'ranged'], equipable: true, type: 'simple', cost: 2, damage: 4, damagetype: 'bludgeoning', weight: 2, properties: ['light', 'thrown']},
      {name: 'Mace', img: '', desc: '', slot: ['weapon1', 'weapon2'], equipable: true, type: 'simple', cost: 5, damage: 6, damagetype: 'bludgeoning', weight: 4, properties: []},
      {name: 'Quarterstaff', img: '', desc: '', slot: ['weapon1', 'weapon2'], equipable: true, type: 'simple', cost: 2, damage: 6, damagetype: 'bludgeoning', weight: 4, properties: ['versatile']},
      {name: 'Sickle', img: '', desc: '', slot: ['weapon1', 'weapon2'], equipable: true, type: 'simple', cost: 1, damage: 4, damagetype: 'slashing', weight: 2, properties: ['light']},
      {name: 'Spear', img: '', desc: '', slot: ['weapon1', 'weapon2', 'ranged'], equipable: true, type: 'simple', cost: 1, damage: 6, damagetype: 'piercing', weight: 3, properties: ['versatile', 'thrown']},
    ]

    return {
      equipItem: equipItem,
      getItems: getItems,
      getItemAtSlot: getItemAtSlot,
      unequipItem: unequipItem
    }

    function equipItem(item) {
      if (item.equipable) {
        item.equipped = true;
      }
    }

    function getItems() {
      return items;
    }

    function getItemAtSlot(slot){
      console.log(slot);
    }

    function unequipItem(item){
      item.equipped = false;
    }

  }
})<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('collectEmailController', function($scope, $state, $timeout, $stateParams, profileService, configService, walletService, platformInfo) {

  var isCordova = platformInfo.isCordova;
  var isWP = platformInfo.isWP;
  var usePushNotifications = isCordova && !isWP;
  var requiresOptIn = platformInfo.isIOS;

  var wallet = profileService.getWallet($stateParams.walletId);
  var walletId = wallet.credentials.walletId;

  $scope.save = function() {
    var opts = {
      emailFor: {}
    };
    opts.emailFor[walletId] = $scope.email;

    walletService.updateRemotePreferences(wallet, {
      email: $scope.email,
    }, function(err) {
      if (err) $log.warn(err);
      configService.set(opts, function(err) {
        if (err) $log.warn(err);
        goNextView();
      });
    });
  };

  var goNextView = function() {
    if (!usePushNotifications) {
      $state.go('onboarding.backupRequest', {
        walletId: walletId
      });
    }
    else if (requiresOptIn) {
      $state.go('onboarding.notifications', {
        walletId: walletId
      });
    } else {
      profileService.pushNotificationsInit();
      $state.go('onboarding.backupRequest', {
        walletId: walletId
      });
    }
  };

  $scope.confirm = function(emailForm) {
    if (emailForm.$invalid) return;
    $scope.confirmation = true;
    $scope.email = emailForm.email.$modelValue;
  };

  $scope.cancel = function() {
    $scope.confirmation = false;
    $timeout(function() {
      $scope.$digest();
    }, 1);
  };

});
<commit_msg>fix skip button on email view<commit_after>'use strict';

angular.module('copayApp.controllers').controller('collectEmailController', function($scope, $state, $timeout, $stateParams, profileService, configService, walletService, platformInfo) {

  var isCordova = platformInfo.isCordova;
  var isWP = platformInfo.isWP;
  var usePushNotifications = isCordova && !isWP;
  var requiresOptIn = platformInfo.isIOS;

  var wallet = profileService.getWallet($stateParams.walletId);
  var walletId = wallet.credentials.walletId;

  $scope.save = function() {
    var opts = {
      emailFor: {}
    };
    opts.emailFor[walletId] = $scope.email;

    walletService.updateRemotePreferences(wallet, {
      email: $scope.email,
    }, function(err) {
      if (err) $log.warn(err);
      configService.set(opts, function(err) {
        if (err) $log.warn(err);
        $scope.goNextView();
      });
    });
  };

  $scope.goNextView = function() {
    if (!usePushNotifications) {
      $state.go('onboarding.backupRequest', {
        walletId: walletId
      });
    }
    else if (requiresOptIn) {
      $state.go('onboarding.notifications', {
        walletId: walletId
      });
    } else {
      profileService.pushNotificationsInit();
      $state.go('onboarding.backupRequest', {
        walletId: walletId
      });
    }
  };

  $scope.confirm = function(emailForm) {
    if (emailForm.$invalid) return;
    $scope.confirmation = true;
    $scope.email = emailForm.email.$modelValue;
  };

  $scope.cancel = function() {
    $scope.confirmation = false;
    $timeout(function() {
      $scope.$digest();
    }, 1);
  };

});
<|endoftext|>


<commit_before>const path = require('path');
const fs   = require('fs');

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

function hsCamelCase(name) {
    if (name.indexOf('hs') === 0) {
        name = 'hs' + name.slice(2).charAt(0).toUpperCase() + name.slice(3);
    }
    return name;
}

const webpackExternals = {
    fs:             'fs',           // node.fs
    path:           'path',         // node.path
    url:            'url',          // node.url
    http:           'http',         // node.http
    crypto:         'crypto',       // node.crypto
    child_process:  'child_process' // node.child_process
};

module.exports = (grunt, dir, dependencies, type, lib) => {
    const devPath = dir.slice(0, dir.indexOf('/dev/')+5);
    const pkg = grunt.file.readJSON(dir+'/package.json');
    const slash = pkg.name.lastIndexOf('/');
    lib = lib || hsCamelCase(slash<0? pkg.name : pkg.name.slice(slash+1));
    const libPath = lib.toLowerCase();
    console.log(`${devPath} > ${lib}: ${type}`);

	// These plugins provide necessary tasks.
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-typedoc');
    grunt.loadNpmTasks('grunt-tslint');
    grunt.loadNpmTasks('grunt-ts');
    grunt.loadNpmTasks('grunt-webpack');
    grunt.loadNpmTasks('jest');
    grunt.loadNpmTasks('grunt-coveralls');

    //------ Add Doc Tasks
    grunt.registerTask('doc', ['clean:docs', 'copy:docs', 'typedoc', 'sourceCode', 'copy:docs2NPM']);

    //------ Add Staging Tasks
    grunt.registerTask('stage', [`${(type === 'app')? 'copy:app2NPM': 'copy:lib2NPM'}`]);

    //------ Add Test Tasks
    grunt.registerTask('ospec', () => { require('child_process').spawnSync('./node_modules/.bin/ospec', {stdio: 'inherit'}); });
    grunt.registerTask('jest',  () => { require('child_process').spawnSync('./node_modules/.bin/jest',  ['-c=jest.config.json', '-i'], {stdio: 'inherit'}); });
    grunt.registerTask('test', ['clean:cov', 'jest', 'copy:coverage', 'cleanupCoverage']);

    //------ Support Tasks
    grunt.registerTask('build-html',    ['copy:buildHTML']);
    grunt.registerTask('build-css',     ['less']);
    // grunt.registerTask('build-example', ['clean:example', 'copy:example', 'ts:example', 'less:example', 'webpack:exampleDev']);
    grunt.registerTask('build-js',      ['tslint:src', 'ts:src']);
    // grunt.registerTask('build-spec',    ['tslint:spec', 'ts:test']);
    grunt.registerTask('build-base',    ['clean:dist', 'build-html', 'build-css', 'copy:bin', 'copy:example']);
    grunt.registerTask('buildMin',      ['build-base', 'build-js', 'webpack:appDev', 'webpack:appProd', 'doc', 'test', 'coveralls']);
    grunt.registerTask('buildDev',      ['build-base', 'build-js', 'webpack:appDev']);

    //------ Entry-point MultiTasks
    grunt.registerTask('default',       ['product']);
    grunt.registerTask('dev',           ['buildDev', 'stage']);
    grunt.registerTask('product',       ['buildMin', 'stage']);
    grunt.registerTask('travis',        ['build-base', 'build-js', 'webpack:appDev', 'webpack:appProd', 'test']);
    grunt.registerTask('help',          ['h']);

    grunt.registerMultiTask('sourceCode', translateSourcesToHTML);
    grunt.registerMultiTask('cleanupCoverage', removeTimestampFromCoverage);

    //------ Add general help
    grunt.registerTask('h', 'help on grunt options', () => {
        grunt.log.writeln(`  grunt: \t make once, don't watch`);
        grunt.log.writeln(`  grunt watch: \t watch for changes, don't make yet`);
        grunt.log.writeln(`  grunt make: \t build, test, doc, and stage`);
        grunt.log.writeln(`  grunt product: make optimized, don't watch; relevant for apps only`);
    });

    //------ Add Task Configurations
    return {
        pkg: grunt.file.readJSON(dir+'/package.json'),
        lib: lib,
        libPath: grunt.config.process(lib).toLowerCase(),
        banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
				'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
				'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
				'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
                ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
        clean: {
			dist:   ['bin'],
            docs:   ['docs'],
            cov:    ['_coverage']
        },
        copy: {
            buildHTML:  { expand:true, cwd:'src/',
                src:['*.html'], dest:'bin/'
            },
            bin:{ files: [
                { expand:true, cwd: 'src/bin',              // if present, scaffolding for bin distribution
                    src:['**/*', '!**/*.ts'], dest:'bin'
                },
                { expand:true, cwd: './',                   // readme and package.json
                    src:['*.md', 'package.json'], dest:'bin'
                }
            ]},
            // create docs/html files
            docs: { files: [
                { expand:true, cwd: devPath+'/local/',  // default docs index.html from 'local' admin project
                    src:['index*.html'], dest:'docs'
                },
                { expand:true, cwd: './src/docs',       // project-specific docs index*.html
                    src:['index*.html'], dest:'docs'
                },
                { expand:true, cwd: './',               // project-specific docs css files
                    src:[`${lib}.css*`], dest:'docs'
                },
                { expand:true, cwd: './bin',            // project-specific docs css files
                    src:[`${lib}.js`, `${lib}.min.js`], dest:'docs'
                }
            ]},
            example:{ expand:true, cwd: 'src/example',
                src:['**/*', '!**/*.ts'], dest:'docs/example'
            },
            coverage: {files: [
                { expand:true, cwd: '_coverage',            // copy coverage into docs
                    src:['**/*'], dest:`docs/data/src/${lib}/coverage` },
                { expand:true, cwd: '_coverage',            // copy dummy file to docs/data/src to avoid 'src/lib' entry in github
                    src:['lcov.info'], dest:`docs/data/src` },
            ]},
            lib2NPM: { files: [
                { expand:true, cwd: 'bin',                  // copy everything from bin
                    src:['**/*'], dest:`node_modules/${libPath}/` },
                { expand:true, cwd: './',                  // copy css and map
                    src:['*.css*'], dest:`node_modules/${libPath}/` },
            ]},
            app2NPM: { files: [
                { expand:true, cwd: 'bin',                  // copy everything from bin
                    src:['**/*'], dest:`node_modules/${libPath}/` },
                { expand:true, cwd: 'bin',                  // copy everything from bin
                    src:[`**/${lib}.*`], dest:`docs` },
                { expand:true, cwd: devPath+'/staging/',    // index.html
                    src:['index.html'], dest:`node_modules/${libPath}/` }
            ]},
            docs2NPM:   { files: [                      // copy the module's docs to npm
                { expand:true, cwd: 'docs',
                    src:['**/*'], dest:`node_modules/${libPath}/docs`}
            ]}
        },
        less: {
            options: {
                sourceMap: true
            },
            css: {
                files: [{
                    cwd: './', src: './src/css/<%= pkg.name %>.less', dest: './<%= lib %>.css'
                }]
             },
            example: {
                files: {
                    'docs/example/<%= pkg.name %>.css': `src/example/${libPath}.less`
                }
            }
        },
        tslint: {
            options: {
                configuration: __dirname+'/tslint.json',
                force:  false,
                fix:    false
            },
            src: {
                src: ["src/**/*.ts"]
            },
            spec: {
                src: ["src/**/*.spec.ts", "src/**/*.jest.ts"]
            }
        },
        ts: {
            options: {
                target: "es6",
                module: "CommonJS",
                rootDir: "./src",
                moduleResolution: "node",
                inlineSourceMap: true,
                removeComments: true,
                noImplicitAny: true,
                declaration: true,
                suppressImplicitAnyIndexErrors: true
            },
            src : {
                outDir:     "bin",
                src: ["src/**/*.ts", "!src/**/*.spec.ts", "!src/**/*.jest.ts", "!src/example/*.ts"],
            },
            example : {
                outDir:     "docs/example",
                src: ["src/example/*.ts"],
            }
        },
        typedoc: {
            code: {
                options: {
                    target: 'es6',
                    module: 'commonjs',
                    moduleResolution: "node",
                    json:   `docs/data/${lib}.json`,
                    mode:   'modules',
                    name:   `${lib}`,
                },
                src: ['src/**/*.ts', '!src/**/*.*.ts', '!src/example/**/*'] // no specs, no example
            }
        },
        webpack: {
            options: {
                stats: !process.env.NODE_ENV || process.env.NODE_ENV === 'development'
            },
            appProd: {
                mode: 'production',
                entry: './bin/index.js',
                output: {
                    filename: `${lib}.min.js`,
                    // chunkFilename: '[name].bundle.js',
                    path: path.resolve(dir, './bin'),
                    library: lib,
                    libraryTarget: "this"
                },
                externals: webpackExternals,
                plugins: [
                    new UglifyJsPlugin({
                        uglifyOptions: {
                            ecma: 6,
                            mangle:false
                        }
                    })
                ]
            },
            appDev: {
                mode: 'development',
                entry: './bin/index.js',
                devtool: "inline-source-map",
                output: {
                    filename: `${lib}.js`,
                    path: path.resolve(dir, './bin'),
                    library: lib,
                    libraryTarget: "this"
                },
                externals: webpackExternals,
            // },
            // test: {
            //     entry: './bin/index.js',
            //     output: {
            //         filename: `${lib}.js`,
            //         path: path.resolve(dir, './bin')
            //     }
            }
        },
        sourceCode: {
            main: {  // translate all *.ts files in src *.htmlfilesin doc
                expand: true,
                cwd: 'src/',
                src: ['**/*.ts', '!**/*.jest.ts', '!**/*.test.ts', '!**/*.spec.ts'],
                dest: `docs/data/src/${lib}/`,
                rename: (dest, src) => dest + src.replace('.ts','.html')
            }
        },
        cleanupCoverage: {
            main: {  // translate all *.ts files in src *.html files in doc
                expand: true,
                cwd: `docs/data/src/${lib}/coverage`,
                src: ['**/*.html'],
                dest:''
            }
        },
        coveralls: {
            src: `docs/data/src/${lib}/coverage/lcov.info`,
            options: { force: true }
        },

        watch: {
            dependencies: {
                files: dependencies.map(d => `./node_modules/${d.toLowerCase()}/index.js`),
				tasks: ['dev']
            },
			gruntfile: {
                files: ['Gruntfile.js', __dirname+'/sharedGruntConfig.js'],
				tasks: ['dev']
			},
			js: {
				files: ['src/**/*.ts', '!src/**/*.spec.ts', '!src/**/*.jest.ts', '!src/**/*.less'],
				tasks: ['dev']
			},
			less: {
				files: ['src/**/*.less'],
				tasks: ['build-css', 'stage']
			},
			html: {
				files: ['src/**/*.html'],
				tasks: ['build-html', 'stage']
			},
			specs: {
				files: ['src/**/*.spec.ts'],
				tasks: ['test']
			},
			jest: {
				files: ['src/**/*.jest.ts'],
				tasks: ['jest']
			}
		}
    }

    function translateSourcesToHTML() {
        // returns a 4-character, right aligned. line number
        function lineNum(num) { return ('    '+(num)).substr(-4).replace(/( )/g, ' '); }
        function wrapLine(line, i) {
            return `<p id=${i+1} class="line"><span>${lineNum(i+1)}</span>${line}</p>`;
        }
        function quote(content) { return `<quote>${content}</quote>`; }
        function comment(content) {
            return content
                .split('\n')
                .map(l => `<comment>${l}</comment>`)
                .join('\n');
        }
        function module(content) { return `<module>${content}</module>`; }
        function processFile(srcFile, destDir) {
            let i = srcFile.lastIndexOf('/');
            let file = (i>=0)? srcFile.slice(i+1) : srcFile;
            let content = grunt.file.read(srcFile)
                .replace(/( )/g, ' ')              // preserve whitespaces
                .replace(/(\/\/.*?)<\/code>/g, comment) // color code // comments
                .replace(/\/\/.*?\n/g, comment)         // color code // comments
                .replace(/\/\*[\s\S]*?\*\//g, comment)  // color code /*...*/ comments
                .replace(/'[^']*?'/g, quote)            // color code '...' strings
                .replace(/"[^"]*?"/g, quote)            // color code "..." strings
                .split('\n')                            // array of lines
                .map(wrapLine)                          // wrap each line into some formatting
                .join('\n')                             // join lines into a complete string
                ;
            grunt.log.writeln(`   ${srcFile} --> ${destDir}`);
            grunt.file.write(destDir, `
                ${intro}

${file}

${content}

                ${extro}
            `);
        }

        const style = `
            body { overflow:hidden;}
            h1 { font-family: Arial, sans-serif; font-size: 24px; color: #44a; }
            p { margin:0; padding:0; }
            br  { margin:0; padding:0; }
            .line {
                white-space: nowrap;
                height:16px;
            }
            .line>span {
                display:inline-block; background-color:#eef; height:100%;
                margin: 0 5px 0 0; padding-right: 5px; color:#999;
            }
            comment {color: #080;} module {color: #804;}
            quote {color: #008;} comment>quote {color: #080;}
            .listing { margin: 10px; border: 1px solid #ccc;
                    font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, Courier, monospace;
                    font-size: 14px;
                    overflow:scroll;
                    height:90%;
            }
            code { padding: 5px 0;}
        `;
        const intro = `<html><style>${style.trim()}</style></html><body>`;
        const extro = `</body>`;
        let files = this.files;
        files.map(file => processFile(file.src, file.dest));
        writeIndexJson();
        grunt.log.writeln(`converted ${files.length} files`);
    }

    function removeTimestampFromCoverage() {
        const replaceFooter = content => content.replace(/<div class='footer[\s\S]*?<\/div>/, '');
        const addLibName    = content => content.replace(/All files/g, `${lib}: All files`);

        this.files.map(f => {
            let content = ''+fs.readFileSync(f.src[0]);
            // console.log(`${lib}: ${f.src[0]}`);
            content = replaceFooter(content);
            content = addLibName(content);
            fs.writeFileSync(f.src[0], content);
        });
        console.log(`cleaned ${this.files.length} files`);
        }

    function writeIndexJson() {
        grunt.file.write('docs/data/index.json', `{"docs": ["${lib}.json"], "title": "HS Libraries"}`);
    }
};
<commit_msg>fixed travis config<commit_after>const path = require('path');
const fs   = require('fs');

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

function hsCamelCase(name) {
    if (name.indexOf('hs') === 0) {
        name = 'hs' + name.slice(2).charAt(0).toUpperCase() + name.slice(3);
    }
    return name;
}

const webpackExternals = {
    fs:             'fs',           // node.fs
    path:           'path',         // node.path
    url:            'url',          // node.url
    http:           'http',         // node.http
    crypto:         'crypto',       // node.crypto
    child_process:  'child_process' // node.child_process
};

module.exports = (grunt, dir, dependencies, type, lib) => {
    const devPath = dir.slice(0, dir.indexOf('/dev/')+5);
    const pkg = grunt.file.readJSON(dir+'/package.json');
    const slash = pkg.name.lastIndexOf('/');
    lib = lib || hsCamelCase(slash<0? pkg.name : pkg.name.slice(slash+1));
    const libPath = lib.toLowerCase();
    console.log(`${devPath} > ${lib}: ${type}`);

	// These plugins provide necessary tasks.
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-typedoc');
    grunt.loadNpmTasks('grunt-tslint');
    grunt.loadNpmTasks('grunt-ts');
    grunt.loadNpmTasks('grunt-webpack');
    grunt.loadNpmTasks('jest');
    grunt.loadNpmTasks('grunt-coveralls');

    //------ Add Doc Tasks
    grunt.registerTask('doc', ['clean:docs', 'copy:docs', 'typedoc', 'sourceCode', 'copy:docs2NPM']);

    //------ Add Staging Tasks
    grunt.registerTask('stage', [`${(type === 'app')? 'copy:app2NPM': 'copy:lib2NPM'}`]);

    //------ Add Test Tasks
    grunt.registerTask('ospec', () => { require('child_process').spawnSync('./node_modules/.bin/ospec', {stdio: 'inherit'}); });
    grunt.registerTask('jest',  () => { require('child_process').spawnSync('./node_modules/.bin/jest',  ['-c=jest.config.json', '-i'], {stdio: 'inherit'}); });
    grunt.registerTask('test', ['clean:cov', 'jest', 'copy:coverage', 'cleanupCoverage']);

    //------ Support Tasks
    grunt.registerTask('build-html',    ['copy:buildHTML']);
    grunt.registerTask('build-css',     ['less']);
    // grunt.registerTask('build-example', ['clean:example', 'copy:example', 'ts:example', 'less:example', 'webpack:exampleDev']);
    grunt.registerTask('build-js',      ['tslint:src', 'ts:src']);
    // grunt.registerTask('build-spec',    ['tslint:spec', 'ts:test']);
    grunt.registerTask('build-base',    ['clean:dist', 'build-html', 'build-css', 'copy:bin', 'copy:example']);
    grunt.registerTask('buildMin',      ['build-base', 'build-js', 'webpack:appDev', 'webpack:appProd', 'doc', 'test', 'coveralls']);
    grunt.registerTask('buildDev',      ['build-base', 'build-js', 'webpack:appDev']);

    //------ Entry-point MultiTasks
    grunt.registerTask('default',       ['product']);
    grunt.registerTask('dev',           ['buildDev', 'stage']);
    grunt.registerTask('product',       ['buildMin', 'stage']);
    grunt.registerTask('travis',        ['build-base', 'build-js', (type === 'node')?'':'webpack:appProd', 'test']); // exlude node-apps from webPack to avoid webpack error
    grunt.registerTask('help',          ['h']);

    grunt.registerMultiTask('sourceCode', translateSourcesToHTML);
    grunt.registerMultiTask('cleanupCoverage', removeTimestampFromCoverage);

    //------ Add general help
    grunt.registerTask('h', 'help on grunt options', () => {
        grunt.log.writeln(`  grunt: \t make once, don't watch`);
        grunt.log.writeln(`  grunt watch: \t watch for changes, don't make yet`);
        grunt.log.writeln(`  grunt make: \t build, test, doc, and stage`);
        grunt.log.writeln(`  grunt product: make optimized, don't watch; relevant for apps only`);
    });

    //------ Add Task Configurations
    return {
        pkg: grunt.file.readJSON(dir+'/package.json'),
        lib: lib,
        libPath: grunt.config.process(lib).toLowerCase(),
        banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
				'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
				'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
				'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
                ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
        clean: {
			dist:   ['bin'],
            docs:   ['docs'],
            cov:    ['_coverage']
        },
        copy: {
            buildHTML:  { expand:true, cwd:'src/',
                src:['*.html'], dest:'bin/'
            },
            bin:{ files: [
                { expand:true, cwd: 'src/bin',              // if present, scaffolding for bin distribution
                    src:['**/*', '!**/*.ts'], dest:'bin'
                },
                { expand:true, cwd: './',                   // readme and package.json
                    src:['*.md', 'package.json'], dest:'bin'
                }
            ]},
            // create docs/html files
            docs: { files: [
                { expand:true, cwd: devPath+'/local/',  // default docs index.html from 'local' admin project
                    src:['index*.html'], dest:'docs'
                },
                { expand:true, cwd: './src/docs',       // project-specific docs index*.html
                    src:['index*.html'], dest:'docs'
                },
                { expand:true, cwd: './',               // project-specific docs css files
                    src:[`${lib}.css*`], dest:'docs'
                },
                { expand:true, cwd: './bin',            // project-specific docs css files
                    src:[`${lib}.js`, `${lib}.min.js`], dest:'docs'
                }
            ]},
            example:{ expand:true, cwd: 'src/example',
                src:['**/*', '!**/*.ts'], dest:'docs/example'
            },
            coverage: {files: [
                { expand:true, cwd: '_coverage',            // copy coverage into docs
                    src:['**/*'], dest:`docs/data/src/${lib}/coverage` },
                { expand:true, cwd: '_coverage',            // copy dummy file to docs/data/src to avoid 'src/lib' entry in github
                    src:['lcov.info'], dest:`docs/data/src` },
            ]},
            lib2NPM: { files: [
                { expand:true, cwd: 'bin',                  // copy everything from bin
                    src:['**/*'], dest:`node_modules/${libPath}/` },
                { expand:true, cwd: './',                  // copy css and map
                    src:['*.css*'], dest:`node_modules/${libPath}/` },
            ]},
            app2NPM: { files: [
                { expand:true, cwd: 'bin',                  // copy everything from bin
                    src:['**/*'], dest:`node_modules/${libPath}/` },
                { expand:true, cwd: 'bin',                  // copy everything from bin
                    src:[`**/${lib}.*`], dest:`docs` },
                { expand:true, cwd: devPath+'/staging/',    // index.html
                    src:['index.html'], dest:`node_modules/${libPath}/` }
            ]},
            docs2NPM:   { files: [                      // copy the module's docs to npm
                { expand:true, cwd: 'docs',
                    src:['**/*'], dest:`node_modules/${libPath}/docs`}
            ]}
        },
        less: {
            options: {
                sourceMap: true
            },
            css: {
                files: [{
                    cwd: './', src: './src/css/<%= pkg.name %>.less', dest: './<%= lib %>.css'
                }]
             },
            example: {
                files: {
                    'docs/example/<%= pkg.name %>.css': `src/example/${libPath}.less`
                }
            }
        },
        tslint: {
            options: {
                configuration: __dirname+'/tslint.json',
                force:  false,
                fix:    false
            },
            src: {
                src: ["src/**/*.ts"]
            },
            spec: {
                src: ["src/**/*.spec.ts", "src/**/*.jest.ts"]
            }
        },
        ts: {
            options: {
                target: "es6",
                module: "CommonJS",
                rootDir: "./src",
                moduleResolution: "node",
                inlineSourceMap: true,
                removeComments: true,
                noImplicitAny: true,
                declaration: true,
                suppressImplicitAnyIndexErrors: true
            },
            src : {
                outDir:     "bin",
                src: ["src/**/*.ts", "!src/**/*.spec.ts", "!src/**/*.jest.ts", "!src/example/*.ts"],
            },
            example : {
                outDir:     "docs/example",
                src: ["src/example/*.ts"],
            }
        },
        typedoc: {
            code: {
                options: {
                    target: 'es6',
                    module: 'commonjs',
                    moduleResolution: "node",
                    json:   `docs/data/${lib}.json`,
                    mode:   'modules',
                    name:   `${lib}`,
                },
                src: ['src/**/*.ts', '!src/**/*.*.ts', '!src/example/**/*'] // no specs, no example
            }
        },
        webpack: {
            options: {
                stats: !process.env.NODE_ENV || process.env.NODE_ENV === 'development'
            },
            appProd: {
                mode: 'production',
                entry: './bin/index.js',
                output: {
                    filename: `${lib}.min.js`,
                    // chunkFilename: '[name].bundle.js',
                    path: path.resolve(dir, './bin'),
                    library: lib,
                    libraryTarget: "this"
                },
                externals: webpackExternals,
                plugins: [
                    new UglifyJsPlugin({
                        uglifyOptions: {
                            ecma: 6,
                            mangle:false
                        }
                    })
                ]
            },
            appDev: {
                mode: 'development',
                entry: './bin/index.js',
                devtool: "inline-source-map",
                output: {
                    filename: `${lib}.js`,
                    path: path.resolve(dir, './bin'),
                    library: lib,
                    libraryTarget: "this"
                },
                externals: webpackExternals,
            // },
            // test: {
            //     entry: './bin/index.js',
            //     output: {
            //         filename: `${lib}.js`,
            //         path: path.resolve(dir, './bin')
            //     }
            }
        },
        sourceCode: {
            main: {  // translate all *.ts files in src *.htmlfilesin doc
                expand: true,
                cwd: 'src/',
                src: ['**/*.ts', '!**/*.jest.ts', '!**/*.test.ts', '!**/*.spec.ts'],
                dest: `docs/data/src/${lib}/`,
                rename: (dest, src) => dest + src.replace('.ts','.html')
            }
        },
        cleanupCoverage: {
            main: {  // translate all *.ts files in src *.html files in doc
                expand: true,
                cwd: `docs/data/src/${lib}/coverage`,
                src: ['**/*.html'],
                dest:''
            }
        },
        coveralls: {
            src: `docs/data/src/${lib}/coverage/lcov.info`,
            options: { force: true }
        },

        watch: {
            dependencies: {
                files: dependencies.map(d => `./node_modules/${d.toLowerCase()}/index.js`),
				tasks: ['dev']
            },
			gruntfile: {
                files: ['Gruntfile.js', __dirname+'/sharedGruntConfig.js'],
				tasks: ['dev']
			},
			js: {
				files: ['src/**/*.ts', '!src/**/*.spec.ts', '!src/**/*.jest.ts', '!src/**/*.less'],
				tasks: ['dev']
			},
			less: {
				files: ['src/**/*.less'],
				tasks: ['build-css', 'stage']
			},
			html: {
				files: ['src/**/*.html'],
				tasks: ['build-html', 'stage']
			},
			specs: {
				files: ['src/**/*.spec.ts'],
				tasks: ['test']
			},
			jest: {
				files: ['src/**/*.jest.ts'],
				tasks: ['jest']
			}
		}
    }

    function translateSourcesToHTML() {
        // returns a 4-character, right aligned. line number
        function lineNum(num) { return ('    '+(num)).substr(-4).replace(/( )/g, ' '); }
        function wrapLine(line, i) {
            return `<p id=${i+1} class="line"><span>${lineNum(i+1)}</span>${line}</p>`;
        }
        function quote(content) { return `<quote>${content}</quote>`; }
        function comment(content) {
            return content
                .split('\n')
                .map(l => `<comment>${l}</comment>`)
                .join('\n');
        }
        function module(content) { return `<module>${content}</module>`; }
        function processFile(srcFile, destDir) {
            let i = srcFile.lastIndexOf('/');
            let file = (i>=0)? srcFile.slice(i+1) : srcFile;
            let content = grunt.file.read(srcFile)
                .replace(/( )/g, ' ')              // preserve whitespaces
                .replace(/(\/\/.*?)<\/code>/g, comment) // color code // comments
                .replace(/\/\/.*?\n/g, comment)         // color code // comments
                .replace(/\/\*[\s\S]*?\*\//g, comment)  // color code /*...*/ comments
                .replace(/'[^']*?'/g, quote)            // color code '...' strings
                .replace(/"[^"]*?"/g, quote)            // color code "..." strings
                .split('\n')                            // array of lines
                .map(wrapLine)                          // wrap each line into some formatting
                .join('\n')                             // join lines into a complete string
                ;
            grunt.log.writeln(`   ${srcFile} --> ${destDir}`);
            grunt.file.write(destDir, `
                ${intro}

${file}

${content}

                ${extro}
            `);
        }

        const style = `
            body { overflow:hidden;}
            h1 { font-family: Arial, sans-serif; font-size: 24px; color: #44a; }
            p { margin:0; padding:0; }
            br  { margin:0; padding:0; }
            .line {
                white-space: nowrap;
                height:16px;
            }
            .line>span {
                display:inline-block; background-color:#eef; height:100%;
                margin: 0 5px 0 0; padding-right: 5px; color:#999;
            }
            comment {color: #080;} module {color: #804;}
            quote {color: #008;} comment>quote {color: #080;}
            .listing { margin: 10px; border: 1px solid #ccc;
                    font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, Courier, monospace;
                    font-size: 14px;
                    overflow:scroll;
                    height:90%;
            }
            code { padding: 5px 0;}
        `;
        const intro = `<html><style>${style.trim()}</style></html><body>`;
        const extro = `</body>`;
        let files = this.files;
        files.map(file => processFile(file.src, file.dest));
        writeIndexJson();
        grunt.log.writeln(`converted ${files.length} files`);
    }

    function removeTimestampFromCoverage() {
        const replaceFooter = content => content.replace(/<div class='footer[\s\S]*?<\/div>/, '');
        const addLibName    = content => content.replace(/All files/g, `${lib}: All files`);

        this.files.map(f => {
            let content = ''+fs.readFileSync(f.src[0]);
            // console.log(`${lib}: ${f.src[0]}`);
            content = replaceFooter(content);
            content = addLibName(content);
            fs.writeFileSync(f.src[0], content);
        });
        console.log(`cleaned ${this.files.length} files`);
        }

    function writeIndexJson() {
        grunt.file.write('docs/data/index.json', `{"docs": ["${lib}.json"], "title": "HS Libraries"}`);
    }
};
<|endoftext|>


<commit_before>describe('lazyload(elt, cb) is an alias for in-viewport ', function() {
  var called;

  var test = createTest({
    tagName: 'div',
    style: {
      position: 'relative',
      top: '10000px',
      left: 0,
      width: '1px',
      height: '1px'
    }
  });

  before(function() {
    insertTest(test);
    lazyload(test, {
      offset: 1000
    }, function() {
      called = true;
    })
  });

  describe('scrolling 5000px', function() {
    before(scroller(0, 5000));

    it('callback not called', function() {
      assert(called === undefined);
    });
  });

  describe('scrolling 9000px', function() {
    before(scroller(0, 9000));

    it('callback called', function() {
      assert(called === true);
    });
  });

  // after(clean(test));

});<commit_msg>clean after watch alias test<commit_after>describe('lazyload(elt, cb) is an alias for in-viewport ', function() {
  var called;

  var test = createTest({
    tagName: 'div',
    style: {
      position: 'relative',
      top: '10000px',
      left: 0,
      width: '1px',
      height: '1px'
    }
  });

  before(function() {
    insertTest(test);
    lazyload(test, {
      offset: 1000
    }, function() {
      called = true;
    })
  });

  describe('scrolling 5000px', function() {
    before(scroller(0, 5000));

    it('callback not called', function() {
      assert(called === undefined);
    });
  });

  describe('scrolling 9000px', function() {
    before(scroller(0, 9000));

    it('callback called', function() {
      assert(called === true);
    });
  });

  after(clean(test));

});<|endoftext|>


<commit_before>const Cookies                = require('js-cookie');
const Client                 = require('./client');
const Clock                  = require('./clock');
const Footer                 = require('./footer');
const Header                 = require('./header');
const BinarySocket           = require('./socket');
const Dialog                 = require('../common/attach_dom/dialog');
const createLanguageDropDown = require('../common/attach_dom/language_dropdown');
const showPopup              = require('../common/attach_dom/popup');
const setCurrencies          = require('../common/currency').setCurrencies;
const SessionDurationLimit   = require('../common/session_duration_limit');
const updateBalance          = require('../pages/user/update_balance');
const GTM                    = require('../../_common/base/gtm');
const SubscriptionManager    = require('../../_common/base/subscription_manager').default;
const Crowdin                = require('../../_common/crowdin');
const localize               = require('../../_common/localize').localize;
const LocalStore             = require('../../_common/storage').LocalStore;
const State                  = require('../../_common/storage').State;
const urlFor                 = require('../../_common/url').urlFor;
const getPropertyValue       = require('../../_common/utility').getPropertyValue;
const isLoginPages           = require('../../_common/utility').isLoginPages;

const BinarySocketGeneral = (() => {
    const onOpen = (is_ready) => {
        Header.hideNotification();
        if (is_ready) {
            if (!isLoginPages()) {
                if (!Client.isValidLoginid()) {
                    Client.sendLogoutRequest();
                    return;
                }
                BinarySocket.send({ website_status: 1, subscribe: 1 });
            }
            Clock.startClock();
        }
    };

    const onMessage = (response) => {
        handleError(response);
        Header.hideNotification('CONNECTION_ERROR');
        let is_available = false;
        switch (response.msg_type) {
            case 'website_status':
                if (response.website_status) {
                    is_available = /^up$/i.test(response.website_status.site_status);
                    if (is_available && !BinarySocket.availability()) {
                        window.location.reload();
                        return;
                    }
                    if (!Crowdin.isInContext()) {
                        createLanguageDropDown(response.website_status);
                    }
                    if (response.website_status.message) {
                        Footer.displayNotification(response.website_status.message);
                    } else {
                        Footer.clearNotification();
                    }
                    BinarySocket.availability(is_available);
                    setCurrencies(response.website_status);
                    // for logged out clients send landing company with IP address as residence
                    if (!Client.isLoggedIn() && !State.getResponse('landing_company')) {
                        BinarySocket.send({ landing_company: response.website_status.clients_country });
                    }
                    if (!Client.isLoggedIn() && !Cookies.get('CookieConsent')) {
                        Footer.displayDialogMessage();
                    } else {
                        Footer.clearDialogMessage();
                    }
                }
                break;
            case 'authorize':
                if (response.error) {
                    const is_active_tab = sessionStorage.getItem('active_tab') === '1';
                    if (getPropertyValue(response, ['error', 'code']) === 'SelfExclusion' && is_active_tab) {
                        sessionStorage.removeItem('active_tab');
                        Dialog.alert({ id: 'authorize_error_alert', localized_message: response.error.message });
                    }
                    Client.sendLogoutRequest(is_active_tab);
                } else if (!isLoginPages() && !/authorize/.test(State.get('skip_response'))) {
                    if (response.authorize.loginid !== Client.get('loginid')) {
                        Client.sendLogoutRequest(true);
                    } else {
                        Client.responseAuthorize(response);
                        BinarySocket.send({ balance: 1, subscribe: 1 });
                        BinarySocket.send({ get_settings: 1 });
                        BinarySocket.send({ get_account_status: 1 });
                        BinarySocket.send({ payout_currencies: 1 });
                        BinarySocket.send({ mt5_login_list: 1 });
                        SubscriptionManager.subscribe('transaction', { transaction: 1, subscribe: 1 }, () => false);
                        const clients_country = response.authorize.country || Client.get('residence');
                        setResidence(clients_country);
                        // for logged in clients send landing company with IP address as residence
                        if (!clients_country) {
                            BinarySocket.send({ landing_company: State.getResponse('website_status.clients_country') });
                        }
                        if (!Client.get('is_virtual')) {
                            BinarySocket.send({ get_self_exclusion: 1 });
                        }
                        BinarySocket.sendBuffered();
                        LocalStore.remove('date_first_contact');
                        LocalStore.remove('signup_device');
                    }
                }
                break;
            case 'balance':
                updateBalance(response);
                break;
            case 'logout':
                Client.doLogout(response);
                break;
            case 'landing_company':
                Header.upgradeMessageVisibility();
                if (!response.error) {
                    Header.metatraderMenuItemVisibility();
                }
                break;
            case 'get_self_exclusion':
                SessionDurationLimit.exclusionResponseHandler(response);
                break;
            case 'get_settings':
                if (response.get_settings) {
                    setResidence(response.get_settings.country_code);
                    Client.set('email', response.get_settings.email);
                    GTM.eventHandler(response.get_settings);
                    if (response.get_settings.is_authenticated_payment_agent) {
                        $('#topMenuPaymentAgent').setVisibility(1);
                    }
                }
                break;
            case 'transaction':
                GTM.pushTransactionData(response, { bom_ui: 'new' });
                break;
            // no default
        }
    };

    const setResidence = (residence) => {
        if (residence) {
            Client.set('residence', residence);
            BinarySocket.send({ landing_company: residence });
        }
    };

    const handleError = (response) => {
        const msg_type   = response.msg_type;
        const error_code = getPropertyValue(response, ['error', 'code']);
        switch (error_code) {
            case 'WrongResponse':
            case 'InternalServerError':
            case 'OutputValidationFailed': {
                if (msg_type !== 'mt5_login_list') {
                    showNoticeMessage(response.error.message);
                }
                break;
            }
            case 'RateLimit':
                if (msg_type !== 'cashier_password') {
                    Header.displayNotification(localize('You have reached the rate limit of requests per second. Please try later.'), true, 'RATE_LIMIT');
                }
                break;
            case 'InvalidAppID':
                Header.displayNotification(response.error.message, true, 'INVALID_APP_ID');
                break;
            case 'DisabledClient':
                showNoticeMessage(response.error.message);
                break;
            // no default
        }
    };

    const showNoticeMessage = (text) => {
        $('#content').empty().html($('<div/>', { class: 'container' }).append($('<p/>', { class: 'notice-msg center-text', text })));
    };

    return {
        onOpen,
        onMessage,
    };
})();

module.exports = BinarySocketGeneral;
<commit_msg>remove import<commit_after>const Cookies                = require('js-cookie');
const Client                 = require('./client');
const Clock                  = require('./clock');
const Footer                 = require('./footer');
const Header                 = require('./header');
const BinarySocket           = require('./socket');
const Dialog                 = require('../common/attach_dom/dialog');
const createLanguageDropDown = require('../common/attach_dom/language_dropdown');
const setCurrencies          = require('../common/currency').setCurrencies;
const SessionDurationLimit   = require('../common/session_duration_limit');
const updateBalance          = require('../pages/user/update_balance');
const GTM                    = require('../../_common/base/gtm');
const SubscriptionManager    = require('../../_common/base/subscription_manager').default;
const Crowdin                = require('../../_common/crowdin');
const localize               = require('../../_common/localize').localize;
const LocalStore             = require('../../_common/storage').LocalStore;
const State                  = require('../../_common/storage').State;
const getPropertyValue       = require('../../_common/utility').getPropertyValue;
const isLoginPages           = require('../../_common/utility').isLoginPages;

const BinarySocketGeneral = (() => {
    const onOpen = (is_ready) => {
        Header.hideNotification();
        if (is_ready) {
            if (!isLoginPages()) {
                if (!Client.isValidLoginid()) {
                    Client.sendLogoutRequest();
                    return;
                }
                BinarySocket.send({ website_status: 1, subscribe: 1 });
            }
            Clock.startClock();
        }
    };

    const onMessage = (response) => {
        handleError(response);
        Header.hideNotification('CONNECTION_ERROR');
        let is_available = false;
        switch (response.msg_type) {
            case 'website_status':
                if (response.website_status) {
                    is_available = /^up$/i.test(response.website_status.site_status);
                    if (is_available && !BinarySocket.availability()) {
                        window.location.reload();
                        return;
                    }
                    if (!Crowdin.isInContext()) {
                        createLanguageDropDown(response.website_status);
                    }
                    if (response.website_status.message) {
                        Footer.displayNotification(response.website_status.message);
                    } else {
                        Footer.clearNotification();
                    }
                    BinarySocket.availability(is_available);
                    setCurrencies(response.website_status);
                    // for logged out clients send landing company with IP address as residence
                    if (!Client.isLoggedIn() && !State.getResponse('landing_company')) {
                        BinarySocket.send({ landing_company: response.website_status.clients_country });
                    }
                    if (!Client.isLoggedIn() && !Cookies.get('CookieConsent')) {
                        Footer.displayDialogMessage();
                    } else {
                        Footer.clearDialogMessage();
                    }
                }
                break;
            case 'authorize':
                if (response.error) {
                    const is_active_tab = sessionStorage.getItem('active_tab') === '1';
                    if (getPropertyValue(response, ['error', 'code']) === 'SelfExclusion' && is_active_tab) {
                        sessionStorage.removeItem('active_tab');
                        Dialog.alert({ id: 'authorize_error_alert', localized_message: response.error.message });
                    }
                    Client.sendLogoutRequest(is_active_tab);
                } else if (!isLoginPages() && !/authorize/.test(State.get('skip_response'))) {
                    if (response.authorize.loginid !== Client.get('loginid')) {
                        Client.sendLogoutRequest(true);
                    } else {
                        Client.responseAuthorize(response);
                        BinarySocket.send({ balance: 1, subscribe: 1 });
                        BinarySocket.send({ get_settings: 1 });
                        BinarySocket.send({ get_account_status: 1 });
                        BinarySocket.send({ payout_currencies: 1 });
                        BinarySocket.send({ mt5_login_list: 1 });
                        SubscriptionManager.subscribe('transaction', { transaction: 1, subscribe: 1 }, () => false);
                        const clients_country = response.authorize.country || Client.get('residence');
                        setResidence(clients_country);
                        // for logged in clients send landing company with IP address as residence
                        if (!clients_country) {
                            BinarySocket.send({ landing_company: State.getResponse('website_status.clients_country') });
                        }
                        if (!Client.get('is_virtual')) {
                            BinarySocket.send({ get_self_exclusion: 1 });
                        }
                        BinarySocket.sendBuffered();
                        LocalStore.remove('date_first_contact');
                        LocalStore.remove('signup_device');
                    }
                }
                break;
            case 'balance':
                updateBalance(response);
                break;
            case 'logout':
                Client.doLogout(response);
                break;
            case 'landing_company':
                Header.upgradeMessageVisibility();
                if (!response.error) {
                    Header.metatraderMenuItemVisibility();
                }
                break;
            case 'get_self_exclusion':
                SessionDurationLimit.exclusionResponseHandler(response);
                break;
            case 'get_settings':
                if (response.get_settings) {
                    setResidence(response.get_settings.country_code);
                    Client.set('email', response.get_settings.email);
                    GTM.eventHandler(response.get_settings);
                    if (response.get_settings.is_authenticated_payment_agent) {
                        $('#topMenuPaymentAgent').setVisibility(1);
                    }
                }
                break;
            case 'transaction':
                GTM.pushTransactionData(response, { bom_ui: 'new' });
                break;
            // no default
        }
    };

    const setResidence = (residence) => {
        if (residence) {
            Client.set('residence', residence);
            BinarySocket.send({ landing_company: residence });
        }
    };

    const handleError = (response) => {
        const msg_type   = response.msg_type;
        const error_code = getPropertyValue(response, ['error', 'code']);
        switch (error_code) {
            case 'WrongResponse':
            case 'InternalServerError':
            case 'OutputValidationFailed': {
                if (msg_type !== 'mt5_login_list') {
                    showNoticeMessage(response.error.message);
                }
                break;
            }
            case 'RateLimit':
                if (msg_type !== 'cashier_password') {
                    Header.displayNotification(localize('You have reached the rate limit of requests per second. Please try later.'), true, 'RATE_LIMIT');
                }
                break;
            case 'InvalidAppID':
                Header.displayNotification(response.error.message, true, 'INVALID_APP_ID');
                break;
            case 'DisabledClient':
                showNoticeMessage(response.error.message);
                break;
            // no default
        }
    };

    const showNoticeMessage = (text) => {
        $('#content').empty().html($('<div/>', { class: 'container' }).append($('<p/>', { class: 'notice-msg center-text', text })));
    };

    return {
        onOpen,
        onMessage,
    };
})();

module.exports = BinarySocketGeneral;
<|endoftext|>


<commit_before>function creditToken() {
  var cylinderFn = 32, // 128 for printing
  sphereFn = 96, // 256 for printing
  maskSphere = sphere({r: 180, center: true, fn: sphereFn, type: "geodesic"}),
  dome = cylinder({r: 16, h: 3, center: true, fn: cylinderFn})
    .subtract(
      maskSphere
        .translate([0, 0, -180])
        .setColor(0.2, 0.2, 0.2)
    )
    .intersect(
      maskSphere
        .translate([0, 0, -178.5])
        .setColor(0.8, 0.8, 0.9)
    )
    .translate([0, 0, 0]),
  ring = cylinder({r: 20, h: 3, center: true, fn: cylinderFn})
    .subtract(cylinder({r: 16, h: 3, center: true, fn: cylinderFn}))
    .setColor(0.2, 0.2, 0.2),
  protrudingRing = cylinder({r: 15.9, h: 1.8, center: true, fn: cylinderFn})
    .subtract(cylinder({r: 14.9, h: 1.8, center: true, fn: cylinderFn}))
    .translate([0, 0, 1])
    .setColor(1, 1, 1),
  ringFix = cylinder({r: 17, h: 1, center: true, fn: cylinderFn})
    .subtract(cylinder({r: 15.8, h: 1, center: true, fn: cylinderFn}))
    .translate([0, 0, 1])
    .setColor(0.2, 0.2, 0.2),
  icon = 	creditIcon()
    .translate([0, 0, -1]),
  token = ring
    .union(dome)
    .union(protrudingRing)
    .union(ringFix)
    .union(icon)
    .rotateX(180);
  return token.scale(0.9);
}

function virus() {
  var	bhCentreCircle = centeredDisc(6.2, 0.3)
    .subtract(centeredDisc(5.2, 0.3))
    .translate([0, 0, 0.65]),
  bhTendril1 = centeredDisc(7, 0.5)
    .subtract(
      centeredDisc(6.5, 0.5)
        .translate([0.75, 0, 0])
    )
    .translate([7.5, 0, 0.75]),
  bhTendril2 = bhTendril1.rotateZ(120),
  bhTendril3 = bhTendril1.rotateZ(240),
  bhFillCentre = centeredDisc(1.5, 0.5)
    .translate([0, 0, 0.75]),
  biohazard = bhCentreCircle
    .union(bhTendril1)
    .union(bhTendril2)
    .union(bhTendril3)
    .union(bhFillCentre)
    .setColor(1, 0, 0);
  return biohazard;
}

function power() {
  var coreBorder = centeredDisc(4.1, 0.6)
    .translate([0, 0, -0.3]),
  rim = centeredDisc(14, 0.7)
    .subtract(centeredDisc(13, 0.7))
    .translate([0, 0, -0.35])
    .setColor(0.2, 0.2, 0.2),
  shield = centeredDisc(12.9, 0.6)
    .translate([0, 0, -0.3])
    .setColor(0.7,0.7, 0.7),
  glow = centeredDisc(12.5, 0.4)
    .subtract(coreBorder)
    .translate([0, 0, -0.2])
    .setColor(0.9, 0.9, 1),
  core = centeredDisc(4, 0.6)
    .translate([0, 0, -0.3])
    .setColor(0.3, 0.4, 1),
  powerHoleS = centeredDisc(0.4, 0.6)
    .translate([0, 0, -0.3]),
  powerHoleM = centeredDisc(0.7, 0.6)
    .translate([0, 0, -0.3]),
  powerHoleL = centeredDisc(1, 0.6)
    .translate([0, 0, -0.3]),
  smallHoles = powerHoleS,
  mediumHoles = powerHoleM,
  largeHoles = powerHoleL,
  smallHoleCenters = [ [-4, -5], [-5, 10], [-7, -3], [-3, 5], [-1, 8], [2, 7], [4, 4.5], [10, 3], [10, -3.3], [8, -8.5], [1.3, -6], [-8, -6] ],
  mediumHoleCenters = [ [2, -10], [-2, -6], [3, 10], [5.2, -8], [6.6, 2], [9, -5], [11, 0], [-9, 0], [2, 5], [-10, 4], [-1, 11], [-6, 1], [-6, -9], [7, -2.2] ],
  largeHoleCenters = [ [-6, 6], [5, 8], [9, 5.8], [4, -5], [-10, -4], [-1, -9] ],
  makeHoles = function(centers, object, template) {
    var i;
    for (i = 0, l = centers.length; i < l; i++) {
      object = object.union(template.translate([centers[i][0], centers[i][1], 0]));
    }
    return object;
  };
  return shield
    .subtract(coreBorder)
    .subtract(makeHoles(smallHoleCenters, smallHoles, powerHoleS))
    .subtract(makeHoles(mediumHoleCenters, mediumHoles, powerHoleM))
    .subtract(makeHoles(largeHoleCenters, largeHoles, powerHoleL))
    .setColor(0.7, 0.7, 0.7)
    .union(glow)
    .union(core)
    .union(rim);
}

function virusPowerToken() {
  var disk = centeredDisc(14, 0.5)
    .translate([0, 0, 0.25]);
  return disk
    .setColor(0.2, 0.2, 0.2)
    .union(virus())
    .union(power());
}

function centeredDisc(radius, height) {
  var resolution = 32; // 128 for printing
  return linear_extrude({height: height}, CAG.circle({center: [0,0], radius: radius, resolution: resolution}))
    .translate([0, 0, -height / 2]);
}

function creditIcon() {
  var hex = rectangular_extrude(
    [ [10, 11], [-10, 11], [-20, 0], [-10, -11], [10, -11], [20, 0] ],
    { w: 1.5, h: 2, closed: true }
  ),
  pip2 = linear_extrude({height: 2}, new CSG.Polygon2D([ [10, -11], [0, 0], [-6, 0], [4, -11] ]));
  return hex
    .union(pip2)
    .scale(0.5)
    .setColor(1, 1, 1);
}

function main() {
  var credit = creditToken().scale([0.4, 0.4, 0.8]).translate([-20, 0, 0]),
      virusPower = virusPowerToken().scale([0.5, 0.5, 1]).translate([20, 0, 0]),
      tokens = [credit, virusPower];
  return tokens;
  // return [virusPower];
}
<commit_msg>Switch to using cylinder function<commit_after>function creditToken() {
  sphereFn = 96, // 256 for printing
  maskSphere = sphere({r: 180, center: true, fn: sphereFn, type: "geodesic"}),
  dome = centeredDisc(16, 3)
    .subtract(
      maskSphere
        .translate([0, 0, -180])
        .setColor(0.2, 0.2, 0.2)
    )
    .intersect(
      maskSphere
        .translate([0, 0, -178.5])
        .setColor(0.8, 0.8, 0.9)
    )
    .translate([0, 0, 0]),
  ring = centeredDisc(20, 3)
    .subtract(centeredDisc(16, 3))
    .setColor(0.2, 0.2, 0.2),
  protrudingRing = centeredDisc(15.9, 1.8)
    .subtract(centeredDisc(14.9, 1.8))
    .translate([0, 0, 1])
    .setColor(1, 1, 1),
  ringFix = centeredDisc(17, 1)
    .subtract(centeredDisc(15.8, 1))
    .translate([0, 0, 1])
    .setColor(0.2, 0.2, 0.2),
  icon = 	creditIcon()
    .translate([0, 0, -1]),
  token = ring
    .union(dome)
    .union(protrudingRing)
    .union(ringFix)
    .union(icon)
    .rotateX(180);
  return token.scale(0.9);
}

function virus() {
  var	bhCentreCircle = centeredDisc(6.2, 0.3)
    .subtract(centeredDisc(5.2, 0.3))
    .translate([0, 0, 0.65]),
  bhTendril1 = centeredDisc(7, 0.5)
    .subtract(
      centeredDisc(6.5, 0.5)
        .translate([0.75, 0, 0])
    )
    .translate([7.5, 0, 0.75]),
  bhTendril2 = bhTendril1.rotateZ(120),
  bhTendril3 = bhTendril1.rotateZ(240),
  bhFillCentre = centeredDisc(1.5, 0.5)
    .translate([0, 0, 0.75]),
  biohazard = bhCentreCircle
    .union(bhTendril1)
    .union(bhTendril2)
    .union(bhTendril3)
    .union(bhFillCentre)
    .setColor(1, 0, 0);
  return biohazard;
}

function power() {
  var coreBorder = centeredDisc(4.1, 0.6)
    .translate([0, 0, -0.3]),
  rim = centeredDisc(14, 0.7)
    .subtract(centeredDisc(13, 0.7))
    .translate([0, 0, -0.35])
    .setColor(0.2, 0.2, 0.2),
  shield = centeredDisc(12.9, 0.6)
    .translate([0, 0, -0.3])
    .setColor(0.7,0.7, 0.7),
  glow = centeredDisc(12.5, 0.4)
    .subtract(coreBorder)
    .translate([0, 0, -0.2])
    .setColor(0.9, 0.9, 1),
  core = centeredDisc(4, 0.6)
    .translate([0, 0, -0.3])
    .setColor(0.3, 0.4, 1),
  powerHoleS = centeredDisc(0.4, 0.6)
    .translate([0, 0, -0.3]),
  powerHoleM = centeredDisc(0.7, 0.6)
    .translate([0, 0, -0.3]),
  powerHoleL = centeredDisc(1, 0.6)
    .translate([0, 0, -0.3]),
  smallHoles = powerHoleS,
  mediumHoles = powerHoleM,
  largeHoles = powerHoleL,
  smallHoleCenters = [ [-4, -5], [-5, 10], [-7, -3], [-3, 5], [-1, 8], [2, 7], [4, 4.5], [10, 3], [10, -3.3], [8, -8.5], [1.3, -6], [-8, -6] ],
  mediumHoleCenters = [ [2, -10], [-2, -6], [3, 10], [5.2, -8], [6.6, 2], [9, -5], [11, 0], [-9, 0], [2, 5], [-10, 4], [-1, 11], [-6, 1], [-6, -9], [7, -2.2] ],
  largeHoleCenters = [ [-6, 6], [5, 8], [9, 5.8], [4, -5], [-10, -4], [-1, -9] ],
  makeHoles = function(centers, object, template) {
    var i;
    for (i = 0, l = centers.length; i < l; i++) {
      object = object.union(template.translate([centers[i][0], centers[i][1], 0]));
    }
    return object;
  };
  return shield
    .subtract(coreBorder)
    .subtract(makeHoles(smallHoleCenters, smallHoles, powerHoleS))
    .subtract(makeHoles(mediumHoleCenters, mediumHoles, powerHoleM))
    .subtract(makeHoles(largeHoleCenters, largeHoles, powerHoleL))
    .setColor(0.7, 0.7, 0.7)
    .union(glow)
    .union(core)
    .union(rim);
}

function virusPowerToken() {
  var disk = centeredDisc(14, 0.5)
    .translate([0, 0, 0.25]);
  return disk
    .setColor(0.2, 0.2, 0.2)
    .union(virus())
    .union(power());
}

function centeredDisc(radius, height) {
  var resolution = 32; // 128 for printing
  return linear_extrude({height: height}, CAG.circle({center: [0,0], radius: radius, resolution: resolution}))
    .translate([0, 0, -height / 2]);
}

function creditIcon() {
  var hex = rectangular_extrude(
    [ [10, 11], [-10, 11], [-20, 0], [-10, -11], [10, -11], [20, 0] ],
    { w: 1.5, h: 2, closed: true }
  ),
  pip2 = linear_extrude({height: 2}, new CSG.Polygon2D([ [10, -11], [0, 0], [-6, 0], [4, -11] ]));
  return hex
    .union(pip2)
    .scale(0.5)
    .setColor(1, 1, 1);
}

function main() {
  var credit = creditToken().scale([0.4, 0.4, 0.8]).translate([-20, 0, 0]),
      virusPower = virusPowerToken().scale([0.5, 0.5, 1]).translate([20, 0, 0]),
      tokens = [credit, virusPower];
  return tokens;
}
<|endoftext|>


<commit_before>/*global browser:false, element:false, by:false */
'use strict';

function Formula(reportId, conceptName){
    this.reportId = reportId;
    this.conceptName = conceptName;
    this.form = {
        conceptLabel: element(by.model('conceptCopy.Label')),
        isAbstract: element(by.model('conceptCopy.IsAbstract'))
    };
}

Formula.prototype.visitPage = function(){
    browser.get('/' + this.reportId + '/concept/' + this.conceptName);
};

Formula.prototype.toggleAbstract = function(){
    this.form.isAbstract.click();
    //We wait for the report to be saved (no http requests pending)
    browser.waitForAngular();
};

Formula.prototype.deleteConcept = function(){
    element(by.css('.btn-danger')).click();
    //We wait for the report to be saved (no http requests pending)
    browser.waitForAngular();
};

Formula.prototype.changeLabel = function(label){
    this.form.conceptLabel.clear();
    this.form.conceptLabel.sendKeys(label);
    //We wait for the report to be saved (no http requests pending)
    browser.waitForAngular();
};

module.exports = Formula;
<commit_msg>fixed accidental renaming<commit_after>/*global browser:false, element:false, by:false */
'use strict';

function Overview(reportId, conceptName){
    this.reportId = reportId;
    this.conceptName = conceptName;
    this.form = {
        conceptLabel: element(by.model('conceptCopy.Label')),
        isAbstract: element(by.model('conceptCopy.IsAbstract'))
    };
}

Overview.prototype.visitPage = function(){
    browser.get('/' + this.reportId + '/concept/' + this.conceptName);
};

Overview.prototype.toggleAbstract = function(){
    this.form.isAbstract.click();
    //We wait for the report to be saved (no http requests pending)
    browser.waitForAngular();
};

Overview.prototype.deleteConcept = function(){
    element(by.css('.btn-danger')).click();
    //We wait for the report to be saved (no http requests pending)
    browser.waitForAngular();
};

Overview.prototype.changeLabel = function(label){
    this.form.conceptLabel.clear();
    this.form.conceptLabel.sendKeys(label);
    //We wait for the report to be saved (no http requests pending)
    browser.waitForAngular();
};

module.exports = Overview;
<|endoftext|>