<commit_before>/*
 * vim_binding.js
 *
 * A vim key binding plugin for Jupyter/IPython
 *
 * @author    Alisue <lambdalisue@hashnote.net>
 * @version   0.1.0
 * @license   MIT license
 * @see       http://github.com/lambdalisue/jupyter-vim-binding
 * @copyright 2015, Alisue, hashnote.net
 *
 * Refs:
 *  - https://github.com/ivanov/ipython-vimception
 *  - http://stackoverflow.com/questions/25730516/vi-shortcuts-in-ipython-notebook
 *  - http://mindtrove.info/#nb-server-exts
 *  - http://akuederle.com/customize-ipython-keymap/
 */
"use strict";

define(['base/js/namespace', 'notebook/js/cell', 'codemirror/keymap/vim'], function(namespace, cell) {
  var extend = function(destination, source) {
    for (var property in source) {
      if (source.hasOwnProperty(property)) {
        destination[property] = source[property];
      }
    }
    return destination;
  };
  var leaveInsert = function(cm) {
    CodeMirror.Vim.handleKey(cm, '<Esc>');
  };
  var leaveInsertOrNormal = function(cm) {
    if (cm.state.vim.insertMode || cm.state.vim.visualMode) {
      CodeMirror.Vim.handleKey(cm, '<Esc>');
    } else {
      namespace.notebook.command_mode();
      namespace.notebook.focus_cell();
    }
  };
  var insertSoftTab = function(cm) {
    cm.execCommand('insertSoftTab');
  }

  // Override save method of CodeMirror to save a checkpoint
  CodeMirror.prototype.save = function() {
    namespace.notebook.save_checkpoint();
  };

  // Override default config of CodeMirror to enable Vim binding
  var options = cell.Cell.options_default;
  options.cm_config.keyMap = 'vim';
  options.cm_config.extraKeys = extend(options.cm_config.extraKeys || {}, {
    'Esc': leaveInsertOrNormal,
    'Tab': insertSoftTab,
  });

  // Override 'bind_events' to ensure 'Normal' mode on blur
  var original_bind_events = cell.Cell.prototype.bind_events;
  cell.Cell.prototype.bind_events = function() {
    original_bind_events.apply(this);
    if (this.code_mirror) {
      this.code_mirror.on('blur', leaveInsert);
    }
  };

  // Register custom actions
  var km = namespace.keyboard_manager;
  km.actions.register({
    'help': 'focus the first cell',
    'help_index': 'zz',
    'handler': function(env) {
      var cells = env.notebook.get_cells();
      if (cells.length > 0) {
        cells[0].focus_cell();
      }
      return false;
    }
  }, 'focus_first_cell', 'vim_binding');
  km.actions.register({
    'help': 'focus the last cell',
    'help_index': 'zz',
    'handler': function(env) {
      var cells = env.notebook.get_cells();
      if (cells.length > 0) {
        cells[cells.length - 1].focus_cell();
      }
      return false;
    }
  }, 'focus_last_cell', 'vim_binding');

  // Assign custom Vim-like mappings
  km.edit_shortcuts.clear_shortcuts();
  km.edit_shortcuts.add_shortcut('ctrl-shift--', 'ipython.split-cell-at-cursor');
  km.edit_shortcuts.add_shortcut('ctrl-shift-subtract', 'ipython.split-cell-at-cursor');
  km.edit_shortcuts.add_shortcut('ctrl-j', 'ipython.select-next-cell');
  km.edit_shortcuts.add_shortcut('ctrl-k', 'ipython.select-previous-cell');
  km.edit_shortcuts.add_shortcut('alt-enter', 'ipython.execute-and-insert-after');
  km.edit_shortcuts.add_shortcut('ctrl-enter', 'ipython.execute-in-place');
  km.edit_shortcuts.add_shortcut('shift-enter', 'ipython.run-select-next');
  km.edit_shortcuts.add_shortcut('shift', 'ipython.ignore');
  km.edit_shortcuts.add_shortcut('ctrl-s', 'ipython.save-notebook');

  km.command_shortcuts.clear_shortcuts();
  km.command_shortcuts.add_shortcut('ctrl-c', 'ipython.interrupt-kernel');
  km.command_shortcuts.add_shortcut('shift-o', 'ipython.insert-cell-before');
  km.command_shortcuts.add_shortcut('o', 'ipython.insert-cell-after');
  km.command_shortcuts.add_shortcut('y,y', 'ipython.copy-selected-cell');
  km.command_shortcuts.add_shortcut('d,d', 'ipython.cut-selected-cell');
  km.command_shortcuts.add_shortcut('shift-p', 'ipython.paste-cell-before');
  km.command_shortcuts.add_shortcut('p', 'ipython.paste-cell-after');
  km.command_shortcuts.add_shortcut('esc', 'ipython.close-pager');
  km.command_shortcuts.add_shortcut('q', 'ipython.close-pager');
  km.command_shortcuts.add_shortcut('enter', 'ipython.enter-edit-mode');
  km.command_shortcuts.add_shortcut('i', 'ipython.enter-edit-mode');
  km.command_shortcuts.add_shortcut('j', 'ipython.select-next-cell');
  km.command_shortcuts.add_shortcut('k', 'ipython.select-previous-cell');
  km.command_shortcuts.add_shortcut('ctrl-j', 'ipython.select-next-cell');
  km.command_shortcuts.add_shortcut('ctrl-k', 'ipython.select-previous-cell');
  km.command_shortcuts.add_shortcut('shift-j', 'ipython.extend-selection-next');
  km.command_shortcuts.add_shortcut('shift-k', 'ipython.extend-selection-previous');
  km.command_shortcuts.add_shortcut('shift-m', 'ipython.merge-selected-cells');
  km.command_shortcuts.add_shortcut('g,g', 'vim_binding.focus_first_cell');
  km.command_shortcuts.add_shortcut('shift-g', 'vim_binding.focus_last_cell');
  km.command_shortcuts.add_shortcut('ctrl-u', 'ipython.scroll-up');
  km.command_shortcuts.add_shortcut('ctrl-d', 'ipython.scroll-down');
  km.command_shortcuts.add_shortcut('u', 'ipython.undo-last-cell-deletion');
  km.command_shortcuts.add_shortcut('ctrl-1', 'ipython.change-selected-cell-to-code-cell');
  km.command_shortcuts.add_shortcut('ctrl-2', 'ipython.change-selected-cell-to-markdown-cell');
  km.command_shortcuts.add_shortcut('ctrl-3', 'ipython.change-selected-cell-to-raw-cell');
  km.command_shortcuts.add_shortcut('shift-h', 'ipython.show-keyboard-shortcut-help-dialog');
  km.command_shortcuts.add_shortcut('shift-l', 'ipython.toggle-line-number-selected-cell');
  km.command_shortcuts.add_shortcut('shift-v', 'ipython.toggle-output-visibility-selected-cell');
  km.command_shortcuts.add_shortcut('shift-s', 'ipython.toggle-output-scrolling-selected-cell');
  km.command_shortcuts.add_shortcut('ctrl-s', 'ipython.save-notebook');
  km.command_shortcuts.add_shortcut('alt-enter', 'ipython.execute-and-insert-after');
  km.command_shortcuts.add_shortcut('ctrl-enter', 'ipython.execute-in-place');
  km.command_shortcuts.add_shortcut('shift-enter', 'ipython.run-select-next');

  // Keys defined to 'command_shortcuts' would steal pressed keys in CodeMirror's Vim command mode
  // Thus the following shortcuts, which is not often used, are not defined even it is defined in
  // normal IPython/Jupyter.
  // See https://github.com/lambdalisue/jupyter-vim-binding/issues/2
  //km.command_shortcuts.add_shortcut('0,0', 'ipython.restart-kernel');
  //km.command_shortcuts.add_shortcut('1', 'ipython.change-selected-cell-to-heading-1');
  //km.command_shortcuts.add_shortcut('2', 'ipython.change-selected-cell-to-heading-2');
  //km.command_shortcuts.add_shortcut('3', 'ipython.change-selected-cell-to-heading-3');
  //km.command_shortcuts.add_shortcut('4', 'ipython.change-selected-cell-to-heading-4');
  //km.command_shortcuts.add_shortcut('5', 'ipython.change-selected-cell-to-heading-5');
  //km.command_shortcuts.add_shortcut('6', 'ipython.change-selected-cell-to-heading-6');

  var exports = {
    'load_ipython_extension': function() {
      var options = cell.Cell.options_default;
      // apply options and events on existing CodeMirror instances
      namespace.notebook.get_cells().map(function(cell) {
        var cm = cell.code_mirror;
        if (cm) {
          cm.setOption('keyMap', options.cm_config.keyMap);
          cm.setOption('extraKeys', options.cm_config.extraKeys);
          cm.on('blur', leaveInsert);
        }
      });
    },
    'leaveInsert': leaveInsert,
    'leaveInsertOrNormal': leaveInsertOrNormal,
    'insertSoftTab': insertSoftTab,
  };
  return exports;
});
<commit_msg>Squashed 'nbextensions/usability/vim_binding/' changes from 589c6c4..9c94f78<commit_after>/*
 * vim_binding.js
 *
 * A vim key binding plugin for Jupyter/IPython
 *
 * @author    Alisue <lambdalisue@hashnote.net>
 * @version   0.1.0
 * @license   MIT license
 * @see       http://github.com/lambdalisue/jupyter-vim-binding
 * @copyright 2015, Alisue, hashnote.net
 *
 * Refs:
 *  - https://github.com/ivanov/ipython-vimception
 *  - http://stackoverflow.com/questions/25730516/vi-shortcuts-in-ipython-notebook
 *  - http://mindtrove.info/#nb-server-exts
 *  - http://akuederle.com/customize-ipython-keymap/
 */
"use strict";

define(['base/js/namespace', 'notebook/js/cell', 'codemirror/keymap/vim'], function(namespace, cell) {
  var extend = function(destination, source) {
    for (var property in source) {
      if (source.hasOwnProperty(property)) {
        destination[property] = source[property];
      }
    }
    return destination;
  };
  var leaveInsert = function(cm) {
    CodeMirror.Vim.handleKey(cm, '<Esc>');
  };
  var leaveInsertOrNormal = function(cm) {
    if (cm.state.vim.insertMode || cm.state.vim.visualMode) {
      CodeMirror.Vim.handleKey(cm, '<Esc>');
    } else {
      namespace.notebook.command_mode();
      namespace.notebook.focus_cell();
    }
  };
  var insertSoftTab = function(cm) {
    cm.execCommand('insertSoftTab');
  }

  // Override save method of CodeMirror to save a checkpoint
  CodeMirror.prototype.save = function() {
    namespace.notebook.save_checkpoint();
  };

  // Override default config of CodeMirror to enable Vim binding
  var options = cell.Cell.options_default;
  options.cm_config.keyMap = 'vim';
  options.cm_config.extraKeys = extend(options.cm_config.extraKeys || {}, {
    'Esc': leaveInsertOrNormal,
    'Tab': insertSoftTab,
    'Ctrl-C': false,
  });

  // Override 'bind_events' to ensure 'Normal' mode on blur
  var original_bind_events = cell.Cell.prototype.bind_events;
  cell.Cell.prototype.bind_events = function() {
    original_bind_events.apply(this);
    if (this.code_mirror) {
      this.code_mirror.on('blur', leaveInsert);
    }
  };

  // Register custom actions
  var km = namespace.keyboard_manager;
  km.actions.register({
    'help': 'focus the first cell',
    'help_index': 'zz',
    'handler': function(env) {
      var cells = env.notebook.get_cells();
      if (cells.length > 0) {
        cells[0].focus_cell();
      }
      return false;
    }
  }, 'focus_first_cell', 'vim_binding');
  km.actions.register({
    'help': 'focus the last cell',
    'help_index': 'zz',
    'handler': function(env) {
      var cells = env.notebook.get_cells();
      if (cells.length > 0) {
        cells[cells.length - 1].focus_cell();
      }
      return false;
    }
  }, 'focus_last_cell', 'vim_binding');

  // Assign custom Vim-like mappings
  km.edit_shortcuts.clear_shortcuts();
  km.edit_shortcuts.add_shortcut('ctrl-shift--', 'ipython.split-cell-at-cursor');
  km.edit_shortcuts.add_shortcut('ctrl-shift-subtract', 'ipython.split-cell-at-cursor');
  km.edit_shortcuts.add_shortcut('ctrl-j', 'ipython.select-next-cell');
  km.edit_shortcuts.add_shortcut('ctrl-k', 'ipython.select-previous-cell');
  km.edit_shortcuts.add_shortcut('alt-enter', 'ipython.execute-and-insert-after');
  km.edit_shortcuts.add_shortcut('ctrl-enter', 'ipython.execute-in-place');
  km.edit_shortcuts.add_shortcut('shift-enter', 'ipython.run-select-next');
  km.edit_shortcuts.add_shortcut('shift', 'ipython.ignore');
  km.edit_shortcuts.add_shortcut('ctrl-s', 'ipython.save-notebook');
  km.edit_shortcuts.add_shortcut('ctrl-1', 'ipython.change-selected-cell-to-code-cell');
  km.edit_shortcuts.add_shortcut('ctrl-2', 'ipython.change-selected-cell-to-markdown-cell');
  km.edit_shortcuts.add_shortcut('ctrl-3', 'ipython.change-selected-cell-to-raw-cell');

  km.command_shortcuts.clear_shortcuts();
  km.command_shortcuts.add_shortcut('ctrl-c', 'ipython.interrupt-kernel');
  km.command_shortcuts.add_shortcut('shift-o', 'ipython.insert-cell-before');
  km.command_shortcuts.add_shortcut('o', 'ipython.insert-cell-after');
  km.command_shortcuts.add_shortcut('y,y', 'ipython.copy-selected-cell');
  km.command_shortcuts.add_shortcut('d,d', 'ipython.cut-selected-cell');
  km.command_shortcuts.add_shortcut('shift-p', 'ipython.paste-cell-before');
  km.command_shortcuts.add_shortcut('p', 'ipython.paste-cell-after');
  km.command_shortcuts.add_shortcut('esc', 'ipython.close-pager');
  km.command_shortcuts.add_shortcut('q', 'ipython.close-pager');
  km.command_shortcuts.add_shortcut('enter', 'ipython.enter-edit-mode');
  km.command_shortcuts.add_shortcut('i', 'ipython.enter-edit-mode');
  km.command_shortcuts.add_shortcut('j', 'ipython.select-next-cell');
  km.command_shortcuts.add_shortcut('k', 'ipython.select-previous-cell');
  km.command_shortcuts.add_shortcut('ctrl-j', 'ipython.select-next-cell');
  km.command_shortcuts.add_shortcut('ctrl-k', 'ipython.select-previous-cell');
  km.command_shortcuts.add_shortcut('shift-j', 'ipython.extend-selection-next');
  km.command_shortcuts.add_shortcut('shift-k', 'ipython.extend-selection-previous');
  km.command_shortcuts.add_shortcut('shift-m', 'ipython.merge-selected-cells');
  km.command_shortcuts.add_shortcut('g,g', 'vim_binding.focus_first_cell');
  km.command_shortcuts.add_shortcut('shift-g', 'vim_binding.focus_last_cell');
  km.command_shortcuts.add_shortcut('ctrl-u', 'ipython.scroll-up');
  km.command_shortcuts.add_shortcut('ctrl-d', 'ipython.scroll-down');
  km.command_shortcuts.add_shortcut('u', 'ipython.undo-last-cell-deletion');
  km.command_shortcuts.add_shortcut('ctrl-1', 'ipython.change-selected-cell-to-code-cell');
  km.command_shortcuts.add_shortcut('ctrl-2', 'ipython.change-selected-cell-to-markdown-cell');
  km.command_shortcuts.add_shortcut('ctrl-3', 'ipython.change-selected-cell-to-raw-cell');
  km.command_shortcuts.add_shortcut('shift-h', 'ipython.show-keyboard-shortcut-help-dialog');
  km.command_shortcuts.add_shortcut('shift-l', 'ipython.toggle-line-number-selected-cell');
  km.command_shortcuts.add_shortcut('shift-v', 'ipython.toggle-output-visibility-selected-cell');
  km.command_shortcuts.add_shortcut('shift-s', 'ipython.toggle-output-scrolling-selected-cell');
  km.command_shortcuts.add_shortcut('ctrl-s', 'ipython.save-notebook');
  km.command_shortcuts.add_shortcut('alt-enter', 'ipython.execute-and-insert-after');
  km.command_shortcuts.add_shortcut('ctrl-enter', 'ipython.execute-in-place');
  km.command_shortcuts.add_shortcut('shift-enter', 'ipython.run-select-next');

  // Keys defined to 'command_shortcuts' would steal pressed keys in CodeMirror's Vim command mode
  // Thus the following shortcuts, which is not often used, are not defined even it is defined in
  // normal IPython/Jupyter.
  // See https://github.com/lambdalisue/jupyter-vim-binding/issues/2
  //km.command_shortcuts.add_shortcut('0,0', 'ipython.restart-kernel');
  //km.command_shortcuts.add_shortcut('1', 'ipython.change-selected-cell-to-heading-1');
  //km.command_shortcuts.add_shortcut('2', 'ipython.change-selected-cell-to-heading-2');
  //km.command_shortcuts.add_shortcut('3', 'ipython.change-selected-cell-to-heading-3');
  //km.command_shortcuts.add_shortcut('4', 'ipython.change-selected-cell-to-heading-4');
  //km.command_shortcuts.add_shortcut('5', 'ipython.change-selected-cell-to-heading-5');
  //km.command_shortcuts.add_shortcut('6', 'ipython.change-selected-cell-to-heading-6');

  var exports = {
    'load_ipython_extension': function() {
      var options = cell.Cell.options_default;
      // apply options and events on existing CodeMirror instances
      namespace.notebook.get_cells().map(function(cell) {
        var cm = cell.code_mirror;
        if (cm) {
          cm.setOption('keyMap', options.cm_config.keyMap);
          cm.setOption('extraKeys', options.cm_config.extraKeys);
          cm.on('blur', leaveInsert);
        }
      });
    },
    'leaveInsert': leaveInsert,
    'leaveInsertOrNormal': leaveInsertOrNormal,
    'insertSoftTab': insertSoftTab,
  };
  return exports;
});
<|endoftext|>


<commit_before>/* global THREE */

/* exported BODY_STATIC, BODY_DYNAMIC */
const BODY_STATIC = 1;
const BODY_DYNAMIC = 2;

// Hacky naïve physics.
/* exported Collision */
const Collision = {
  normal: new THREE.Vector3(),
  penetration: new THREE.Vector3(),

  boxA: new THREE.Box3(),
  boxB: new THREE.Box3(),

  centerA: new THREE.Vector3(),
  centerB: new THREE.Vector3(),

  update(bodies) {
    for (let i = 0; i < bodies.length; i++) {
      const bodyA = bodies[i];

      for (let j = i + 1; j < bodies.length; j++) {
        const bodyB = bodies[j];

        if (!bodyA.physics || !bodyB.physics) {
          continue;
        }

        // Both bodies can't move.
        if (bodyA.physics === BODY_STATIC &&
            bodyB.physics === BODY_STATIC) {
          continue;
        }

        const boxA = Collision.boxA.copy(bodyA.boundingBox).translate(bodyA.position);
        const boxB = Collision.boxB.copy(bodyB.boundingBox).translate(bodyB.position);

        if (boxA.intersectsBox(boxB)) {
          // Resolve collision.
          boxA.getCenter(Collision.centerA);
          boxB.getCenter(Collision.centerB);

          Collision.normal.subVectors(Collision.centerA, Collision.centerB);

          // Determine overlap.
          // d0 is negative side or 'left' side.
          // d1 is positive or 'right' side.
          const d0x = boxB.max.x - boxA.min.x;
          const d1x = boxA.max.x - boxB.min.x;

          const d0y = boxB.max.y - boxA.min.y;
          const d1y = boxA.max.y - boxB.min.y;

          const d0z = boxB.max.z - boxA.min.z;
          const d1z = boxA.max.z - boxB.min.z;

          // Only overlapping on an axis if both ranges intersect.
          let dx = 0;
          if (d0x > 0 && d1x > 0) {
            dx = d0x < d1x ? d0x : -d1x;
          }

          let dy = 0;
          if (d0y > 0 && d1y > 0) {
            dy = d0y < d1y ? d0y : -d1y;
          }

          let dz = 0;
          if (d0z > 0 && d1z > 0) {
            dz = d0z < d1z ? d0z : -d1z;
          }

          // Determine minimum axis of separation.
          const adx = Math.abs(dx);
          const ady = Math.abs(dy);
          const adz = Math.abs(dz);

          if (adx <= ady && adx <= adz) {
            Collision.penetration.set(dx, 0, 0);
          } else if (ady <= adx && ady <= adz) {
            Collision.penetration.set(0, dy, 0);
          } else {
            Collision.penetration.set(0, 0, dz);
          }

          if (bodyA.physics === BODY_STATIC) {
            bodyB.position.sub(Collision.penetration);
          } else if (bodyB.physics === BODY_STATIC) {
            bodyA.position.add(Collision.penetration);
          } else {
            Collision.penetration.multiplyScalar(0.5);
            bodyA.position.add(Collision.penetration);
            bodyB.position.sub(Collision.penetration);
          }
        }
      }
    }
  },
};
<commit_msg>collision: Simplify conditionals.<commit_after>/* global THREE */

/* exported BODY_STATIC, BODY_DYNAMIC */
const BODY_STATIC = 1;
const BODY_DYNAMIC = 2;

// Hacky naïve physics.
/* exported Collision */
const Collision = {
  normal: new THREE.Vector3(),
  penetration: new THREE.Vector3(),

  boxA: new THREE.Box3(),
  boxB: new THREE.Box3(),

  centerA: new THREE.Vector3(),
  centerB: new THREE.Vector3(),

  update(bodies) {
    for (let i = 0; i < bodies.length; i++) {
      const bodyA = bodies[i];

      if (!bodyA.physics) {
        continue;
      }

      for (let j = i + 1; j < bodies.length; j++) {
        const bodyB = bodies[j];

        if (!bodyB.physics) {
          continue;
        }

        // Both bodies can't move.
        if (bodyA.physics === BODY_STATIC && bodyB.physics === BODY_STATIC) {
          continue;
        }

        const boxA = Collision.boxA.copy(bodyA.boundingBox).translate(bodyA.position);
        const boxB = Collision.boxB.copy(bodyB.boundingBox).translate(bodyB.position);

        if (boxA.intersectsBox(boxB)) {
          // Resolve collision.
          boxA.getCenter(Collision.centerA);
          boxB.getCenter(Collision.centerB);

          Collision.normal.subVectors(Collision.centerA, Collision.centerB);

          // Determine overlap.
          // d0 is negative side or 'left' side.
          // d1 is positive or 'right' side.
          const d0x = boxB.max.x - boxA.min.x;
          const d1x = boxA.max.x - boxB.min.x;

          const d0y = boxB.max.y - boxA.min.y;
          const d1y = boxA.max.y - boxB.min.y;

          const d0z = boxB.max.z - boxA.min.z;
          const d1z = boxA.max.z - boxB.min.z;

          // Only overlapping on an axis if both ranges intersect.
          let dx = 0;
          if (d0x > 0 && d1x > 0) {
            dx = d0x < d1x ? d0x : -d1x;
          }

          let dy = 0;
          if (d0y > 0 && d1y > 0) {
            dy = d0y < d1y ? d0y : -d1y;
          }

          let dz = 0;
          if (d0z > 0 && d1z > 0) {
            dz = d0z < d1z ? d0z : -d1z;
          }

          // Determine minimum axis of separation.
          const adx = Math.abs(dx);
          const ady = Math.abs(dy);
          const adz = Math.abs(dz);

          if (adx < ady && adx < adz) {
            Collision.penetration.set(dx, 0, 0);
          } else if (ady < adz) {
            Collision.penetration.set(0, dy, 0);
          } else {
            Collision.penetration.set(0, 0, dz);
          }

          if (bodyA.physics === BODY_STATIC) {
            bodyB.position.sub(Collision.penetration);
          } else if (bodyB.physics === BODY_STATIC) {
            bodyA.position.add(Collision.penetration);
          } else {
            Collision.penetration.multiplyScalar(0.5);
            bodyA.position.add(Collision.penetration);
            bodyB.position.sub(Collision.penetration);
          }
        }
      }
    }
  },
};
<|endoftext|>


<commit_before>/* globals define, $ */
/* eslint-env browser */

define([
    'deepforge/storage/index'
], function (
    Storage
) {
    const SECTION_HEADER = $('
');
    const CUSTOM_WIDGET_TYPES = ['dict', 'section', 'group', 'userAsset'];

    class CustomConfigEntries {
        section(configEntry) {
            const sectionHeader = SECTION_HEADER.clone();
            sectionHeader.text(configEntry.displayName);
            return {el: sectionHeader};
        }

        group(configEntry, config) {
            const widget = {el: null};
            widget.el = $('
', {class: configEntry.name});
            const entries = configEntry.valueItems.map(item => {
                return this.getEntryForProperty(item, config);
            });
            widget.getValue = () => {
                const config = {};
                entries.forEach(entry => {
                    if (entry.widget) {
                        config[entry.id || entry.name] = entry.widget.getValue();
                    }
                });
                return config;
            };

            widget.setValue = config => {
                entries.forEach(entry => {
                    const value = config[entry.id || entry.name];
                    if (entry.widget && value !== undefined) {
                        entry.widget.setValue(value);
                    }
                });
                return config;
            };

            return {widget, el: widget.el};
        }

        dict(configEntry, config) {
            const widget = {el: null, active: null};
            widget.el = $('
', {class: configEntry.name});

            const entriesForItem = {};
            const valueItemsDict = {};
            for (let i = 0; i < configEntry.valueItems.length; i++) {
                const valueItem = configEntry.valueItems[i];
                const entries = valueItem.configStructure
                    .map(item => {
                        const entry = this.getEntryForProperty(item, config);
                        return entry;
                    });

                entries.forEach(entry => {
                    if (i > 0) {
                        entry.el.css('display', 'none');
                    }
                    widget.el.append(entry.el);
                });

                const displayName = valueItem.displayName || valueItem.name;
                entriesForItem[displayName] = entries;
                valueItemsDict[displayName] = valueItem;
            }

            const itemNames = Object.keys(valueItemsDict);
            const defaultValue = itemNames[0];
            const configForKeys = {
                name: configEntry.name,
                displayName: configEntry.displayName,
                value: defaultValue,
                valueType: 'string',
                valueItems: itemNames
            };
            const selector = this.getEntryForProperty(configForKeys);

            widget.active = defaultValue;
            widget.onSetSelector = value => {
                const oldEntries = entriesForItem[widget.active];
                oldEntries.forEach(entry => entry.el.css('display', 'none'));
                widget.active = value;
                entriesForItem[widget.active]
                    .forEach(entry => entry.el.css('display', ''));
            };

            selector.el.find('select').on('change', event => {
                const {value} = event.target;
                widget.onSetSelector(value);
            });

            widget.getValue = () => {
                const displayName = widget.active;
                const name = valueItemsDict[displayName].name;
                const config = {};
                entriesForItem[name].forEach(entry => {
                    if (entry.widget) {
                        config[entry.id] = entry.widget.getValue();
                    }
                });
                return {name, config};
            };

            widget.setValue = value => {
                const {name, config} = value;
                selector.widget.setValue(name);
                widget.onSetSelector(name);
                entriesForItem[name].forEach(entry => {
                    if (entry.widget) {
                        entry.widget.setValue(config[entry.id]);
                    }
                });
                return {name, config};
            };

            widget.el.prepend(selector.el);

            return {widget, el: widget.el};
        }

        userAsset(configEntry, config) {
            const widget = {el: null, active: null};
            const storageOpts = this._getStorageOpts();
            widget.el = $('
', {class: configEntry.name});
            const browserAssetConfig = {
                name: configEntry.name,
                displayName: configEntry.displayName,
                valueType: 'file'
            };
            const browserAssetWidget = this.getEntryForProperty(browserAssetConfig, config);
            const storageWidget = this.getEntryForProperty(storageOpts, config);
            widget.el.append(browserAssetWidget.el);
            widget.el.append(storageWidget.el);

            widget.getValue = async () => {
                const {name, config} = storageWidget.widget.getValue();
                const backendId = this._getStorageBackendId(name);
                const basedir = this.getBaseStorageDir();
                const storageClient = await Storage
                    .getClient(backendId, browserAssetWidget.widget.logger, config);
                const file = browserAssetWidget.widget.getValue();
                const dataInfo = await storageClient.putFile(`${basedir}/${file.name}`, file);
                return {
                    name: file.name,
                    dataInfo: dataInfo,
                    storageAssetWidgetValue: storageWidget.widget.getValue()
                };
            };

            widget.setValue = value => {
                const {storageAssetWidgetValue} = value;
                if(storageAssetWidgetValue) {
                    storageWidget.widget.setValue(storageAssetWidgetValue);
                }
            };

            return {widget, el: widget.el};
        }

        _getStorageOpts() {
            const backends = Storage.getAvailableBackends();
            const storageMetadata = backends.map(id => Storage.getStorageMetadata(id));
            return {
                name: 'storage',
                displayName: 'Storage',
                description: 'Location to store intermediate/generated data.',
                valueType: 'dict',
                value: Storage.getBackend(backends[0]).name,
                valueItems: storageMetadata
            };
        }

        _getStorageBackendId(backendName) {
            const backends = Storage.getAvailableBackends();
            const storageMetadata = backends.map(id => Storage.getStorageMetadata(id));
            return storageMetadata.find(metadata => metadata.name === backendName).id;
        }

        static isCustomEntryValueType(valueType) {
            return CUSTOM_WIDGET_TYPES.includes(valueType);
        }
    }

    return CustomConfigEntries;
});
<commit_msg>Fix element append for group in CustomConfigEntires (#1837)<commit_after>/* globals define, $ */
/* eslint-env browser */

define([
    'deepforge/storage/index'
], function (
    Storage
) {
    const SECTION_HEADER = $('
');
    const CUSTOM_WIDGET_TYPES = ['dict', 'section', 'group', 'userAsset'];

    class CustomConfigEntries {
        section(configEntry) {
            const sectionHeader = SECTION_HEADER.clone();
            sectionHeader.text(configEntry.displayName);
            return {el: sectionHeader};
        }

        group(configEntry, config) {
            const widget = {el: null};
            widget.el = $('
', {class: configEntry.name});
            const entries = configEntry.valueItems.map(item => {
                return this.getEntryForProperty(item, config);
            });

            entries.forEach(entry => widget.el.append(entry.el));

            widget.getValue = () => {
                const config = {};
                entries.forEach(entry => {
                    if (entry.widget) {
                        config[entry.id || entry.name] = entry.widget.getValue();
                    }
                });
                return config;
            };

            widget.setValue = config => {
                entries.forEach(entry => {
                    const value = config[entry.id || entry.name];
                    if (entry.widget && value !== undefined) {
                        entry.widget.setValue(value);
                    }
                });
                return config;
            };

            return {widget, el: widget.el};
        }

        dict(configEntry, config) {
            const widget = {el: null, active: null};
            widget.el = $('
', {class: configEntry.name});

            const entriesForItem = {};
            const valueItemsDict = {};
            for (let i = 0; i < configEntry.valueItems.length; i++) {
                const valueItem = configEntry.valueItems[i];
                const entries = valueItem.configStructure
                    .map(item => {
                        const entry = this.getEntryForProperty(item, config);
                        return entry;
                    });

                entries.forEach(entry => {
                    if (i > 0) {
                        entry.el.css('display', 'none');
                    }
                    widget.el.append(entry.el);
                });

                const displayName = valueItem.displayName || valueItem.name;
                entriesForItem[displayName] = entries;
                valueItemsDict[displayName] = valueItem;
            }

            const itemNames = Object.keys(valueItemsDict);
            const defaultValue = itemNames[0];
            const configForKeys = {
                name: configEntry.name,
                displayName: configEntry.displayName,
                value: defaultValue,
                valueType: 'string',
                valueItems: itemNames
            };
            const selector = this.getEntryForProperty(configForKeys);

            widget.active = defaultValue;
            widget.onSetSelector = value => {
                const oldEntries = entriesForItem[widget.active];
                oldEntries.forEach(entry => entry.el.css('display', 'none'));
                widget.active = value;
                entriesForItem[widget.active]
                    .forEach(entry => entry.el.css('display', ''));
            };

            selector.el.find('select').on('change', event => {
                const {value} = event.target;
                widget.onSetSelector(value);
            });

            widget.getValue = () => {
                const displayName = widget.active;
                const name = valueItemsDict[displayName].name;
                const config = {};
                entriesForItem[name].forEach(entry => {
                    if (entry.widget) {
                        config[entry.id] = entry.widget.getValue();
                    }
                });
                return {name, config};
            };

            widget.setValue = value => {
                const {name, config} = value;
                selector.widget.setValue(name);
                widget.onSetSelector(name);
                entriesForItem[name].forEach(entry => {
                    if (entry.widget) {
                        entry.widget.setValue(config[entry.id]);
                    }
                });
                return {name, config};
            };

            widget.el.prepend(selector.el);

            return {widget, el: widget.el};
        }

        userAsset(configEntry, config) {
            const widget = {el: null, active: null};
            const storageOpts = this._getStorageOpts();
            widget.el = $('
', {class: configEntry.name});
            const browserAssetConfig = {
                name: configEntry.name,
                displayName: configEntry.displayName,
                valueType: 'file'
            };
            const browserAssetWidget = this.getEntryForProperty(browserAssetConfig, config);
            const storageWidget = this.getEntryForProperty(storageOpts, config);
            widget.el.append(browserAssetWidget.el);
            widget.el.append(storageWidget.el);

            widget.getValue = async () => {
                const {name, config} = storageWidget.widget.getValue();
                const backendId = this._getStorageBackendId(name);
                const basedir = this.getBaseStorageDir();
                const storageClient = await Storage
                    .getClient(backendId, browserAssetWidget.widget.logger, config);
                const file = browserAssetWidget.widget.getValue();
                const dataInfo = await storageClient.putFile(`${basedir}/${file.name}`, file);
                return {
                    name: file.name,
                    dataInfo: dataInfo,
                    storageAssetWidgetValue: storageWidget.widget.getValue()
                };
            };

            widget.setValue = value => {
                const {storageAssetWidgetValue} = value;
                if(storageAssetWidgetValue) {
                    storageWidget.widget.setValue(storageAssetWidgetValue);
                }
            };

            return {widget, el: widget.el};
        }

        _getStorageOpts() {
            const backends = Storage.getAvailableBackends();
            const storageMetadata = backends.map(id => Storage.getStorageMetadata(id));
            return {
                name: 'storage',
                displayName: 'Storage',
                description: 'Location to store intermediate/generated data.',
                valueType: 'dict',
                value: Storage.getBackend(backends[0]).name,
                valueItems: storageMetadata
            };
        }

        _getStorageBackendId(backendName) {
            const backends = Storage.getAvailableBackends();
            const storageMetadata = backends.map(id => Storage.getStorageMetadata(id));
            return storageMetadata.find(metadata => metadata.name === backendName).id;
        }

        static isCustomEntryValueType(valueType) {
            return CUSTOM_WIDGET_TYPES.includes(valueType);
        }
    }

    return CustomConfigEntries;
});
<|endoftext|>


<commit_before>L.Polyline.polylineEditor = L.Polyline.extend({
    /**
     * This function must be explicitly called when the polyline is ready to
     * be edited.
     */
    edit: function(options) {
        if(!this._map) {
            alert('Not added to map!');
            return;
        }
        /**
         * Since all point editing is done by marker events, markers
         * will be the main holder of the polyline points locations.
         * Every marker contains a reference to the newPointMarker
         * *before* him (=> the first marker has newPointMarker=null).
         */
        this._parseOptions(options);

        this._markers = [];
        var that = this;
        var points = this.getLatLngs();
        var length = points.length;
        for(var i = 0; i < length; i++) {
            this._addMarkers(i, points[i]);
        }

        var map = this._map;
        this._map.on("zoomend", function(e) {
            console.log("zoom level is " + map.getZoom())
            that._showBoundMarkers();
        });
        this._map.on("moveend", function(e) {
            console.log("zoom level is " + map.getZoom())
            that._showBoundMarkers();
        });

        return this;
    },
    _parseOptions: function(options) {
        if(!options)
            options = {};

        // Do not show edit markers if more than maxMarkers would be shown:
        if(!('maxMarkers' in options)) {
            options.maxMarkers = 100;
        }
        this.maxMarkers = options.maxMarkers;
        console.log("maxMarkers=" + this.maxMarkers);

        // Icons:
        if(options.pointIcon) {
            this.pointIcon = options.pointIcon;
        } else {
            this.pointIcon = L.icon({ iconUrl: 'editmarker.png', iconSize: [11, 11], iconAnchor: [6, 6], });
        }
        if(options.newPointIcon) {
            this.newPointIcon = options.newPointIcon;
        } else {
            this.newPointIcon = L.icon({ iconUrl: 'editmarker2.png', iconSize: [11, 11], iconAnchor: [6, 6], });
        }
    },
    /**
     * Show only markers in current map bounds *is* there are only a certain
     * number of markers. This method is called on eventy that change map
     * bounds.
     */
    _showBoundMarkers: function() {
        var that = this;
        var bounds = this._map.getBounds();
        var found = 0;
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(bounds.contains(marker.getLatLng()))
                found += 1;
        }

        console.log("found=" + found);
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(found < that.maxMarkers) {
                that._setMarkerVisible(marker, bounds.contains(marker.getLatLng()));
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, bounds.contains(marker.getLatLng()));
            } else {
                that._setMarkerVisible(marker, false);
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, false);
            }
        }
    },
    /**
     * Show/hide marker.
     */
    _setMarkerVisible: function(marker, show) {
        if(!marker)
            return;

        var map = this._map;
        if(show) {
            if(!marker._map) { // First show fo this marker:
                marker.addTo(map);
            } else { // Marker was already shown and hidden:
                map.addLayer(marker);
            }
            marker._visible = true;
            marker._map = map;
        } else {
            map.removeLayer(marker);
            marker._visible = false;
        }
    },
    /**
     * Add two markers (a point marker and his newPointMarker) for a
     * single point.
     *
     * Markers are not added on the map here, the marker.addTo(map) is called
     * only later when needed first time because of performance issues.
     */
    _addMarkers: function(pointNo, latLng, fixNeighbourPositions) {
        var that = this;
        var points = this.getLatLngs();
        var marker = L.marker(latLng, {draggable: true, icon: this.pointIcon});

        marker.newPointMarker = null;
        marker.on('dragend', function(event) {
            var marker = event.target;
            var pointNo = that._getPointNo(event.target);
            that.setLatLngs(that._getMarkerLatLngs());
            that._fixNeighbourPositions(pointNo);
            that._showBoundMarkers();
        });
        marker.on('contextmenu', function(event) {
            console.log('rightclick');
        });

        if(pointNo > 0) {
            var previousPoint = points[pointNo - 1];
            var newPointMarker = L.marker([(latLng.lat + previousPoint.lat) / 2.,
                                           (latLng.lng + previousPoint.lng) / 2.],
                                          {draggable: true, icon: this.newPointIcon});
            marker.newPointMarker = newPointMarker;
            newPointMarker.on('dragend', function(event) {
                var marker = event.target;
                var pointNo = that._getPointNo(event.target);
                that._addMarkers(pointNo, marker.getLatLng(), true);
                that.setLatLngs(that._getMarkerLatLngs());
                that._showBoundMarkers();
            });
        }

        this._markers.splice(pointNo, 0, marker);

        if(fixNeighbourPositions) {
            this._fixNeighbourPositions(pointNo);
        }
    },
    /**
     * Fix nearby new point markers when the new point is created.
     */
    _fixNeighbourPositions: function(pointNo) {
        var previousMarker = pointNo == 0 ? null : this._markers[pointNo - 1];
        var marker = this._markers[pointNo];
        var nextMarker = pointNo < this._markers.length - 1 ? this._markers[pointNo + 1] : null;
        if(marker && previousMarker) {
            marker.newPointMarker.setLatLng([(previousMarker.getLatLng().lat + marker.getLatLng().lat) / 2.,
                                             (previousMarker.getLatLng().lng + marker.getLatLng().lng) / 2.]);
        }
        if(marker && nextMarker) {
            nextMarker.newPointMarker.setLatLng([(marker.getLatLng().lat + nextMarker.getLatLng().lat) / 2.,
                                                 (marker.getLatLng().lng + nextMarker.getLatLng().lng) / 2.]);
        }
    },
    _getPointNo: function(marker) {
        for(var i = 0; i < this._markers.length; i++) {
            if(marker == this._markers[i] || marker == this._markers[i].newPointMarker) {
                console.log("Found:" + i);
                return i;
            }
        }
        console.log("Nothing found for:" + marker);
        return -1;
    },
    /**
     * Get polyline latLngs based on marker positions.
     */
    _getMarkerLatLngs: function() {
        var result = [];
        for(var i = 0; i < this._markers.length; i++)
            result.push(this._markers[i].getLatLng());
        return result;
    },
});

L.Polyline.polylineEditor.addInitHook(function () {
    //this._initMarkers();
});

L.Polyline.PolylineEditor = function(latlngs, options){
    return new L.Polyline.polylineEditor(latlngs, options);
};

<commit_msg>Marker contexts<commit_after>L.Polyline.polylineEditor = L.Polyline.extend({
    /**
     * This function must be explicitly called when the polyline is ready to
     * be edited.
     *
     * If contexts is not null then this is just a shortcut for the contexts
     * method.
     */
    edit: function(options, contexts) {
        if(!this._map) {
            alert('Not added to map!');
            return;
        }

        /**
         * Since all point editing is done by marker events, markers
         * will be the main holder of the polyline points locations.
         * Every marker contains a reference to the newPointMarker
         * *before* him (=> the first marker has newPointMarker=null).
         */
        this._parseOptions(options);

        this._markers = [];
        var that = this;
        var points = this.getLatLngs();
        var length = points.length;
        for(var i = 0; i < length; i++) {
            this._addMarkers(i, points[i]);
        }

        var map = this._map;
        this._map.on("zoomend", function(e) {
            console.log("zoom level is " + map.getZoom())
            that._showBoundMarkers();
        });
        this._map.on("moveend", function(e) {
            console.log("zoom level is " + map.getZoom())
            that._showBoundMarkers();
        });

        this.contexts(contexts);

        return this;
    },
    /**
     * This is an array of objects that will be kept as "context" for every
     * point. Marker will keep this value as marker.context. New markers will
     * have context set to null.
     *
     * Contexts must be the same size as the polyline size!
     *
     * By default, even without calling this method -- every marker will have
     * context with one value: marker.context.originalPointNo with the
     * original order number of this point. The order may change if some
     * markers before this one are delted or new added.
     */
    contexts: function(contexts) {
        if(contexts != null && contexts.length != this._markers.length)
            throw new Exception('Invalid contexts size (' + contexts.length + '), should be:' + this._markers.length);

        for(var i = 0; i < this._markers.length; i++)
            this._markers.context = { originalPointNo: i };

        if(contexts != null) {
            for(var i = 0; i < contexts.length; i++) {
                var context = contexts[i];
                for(var j in context) { // Copy user-defined context properties to marker context:
                    this._markers[i].context[j] = context[j];
                }
            }
        }
    },
    _parseOptions: function(options) {
        if(!options)
            options = {};

        // Do not show edit markers if more than maxMarkers would be shown:
        if(!('maxMarkers' in options)) {
            options.maxMarkers = 100;
        }
        this.maxMarkers = options.maxMarkers;
        console.log("maxMarkers=" + this.maxMarkers);

        // Icons:
        if(options.pointIcon) {
            this.pointIcon = options.pointIcon;
        } else {
            this.pointIcon = L.icon({ iconUrl: 'editmarker.png', iconSize: [11, 11], iconAnchor: [6, 6], });
        }
        if(options.newPointIcon) {
            this.newPointIcon = options.newPointIcon;
        } else {
            this.newPointIcon = L.icon({ iconUrl: 'editmarker2.png', iconSize: [11, 11], iconAnchor: [6, 6], });
        }
    },
    /**
     * Show only markers in current map bounds *is* there are only a certain
     * number of markers. This method is called on eventy that change map
     * bounds.
     */
    _showBoundMarkers: function() {
        var that = this;
        var bounds = this._map.getBounds();
        var found = 0;
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(bounds.contains(marker.getLatLng()))
                found += 1;
        }

        console.log("found=" + found);
        for(var markerNo in this._markers) {
            var marker = this._markers[markerNo];
            if(found < that.maxMarkers) {
                that._setMarkerVisible(marker, bounds.contains(marker.getLatLng()));
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, bounds.contains(marker.getLatLng()));
            } else {
                that._setMarkerVisible(marker, false);
                if(marker.newPointMarker)
                    that._setMarkerVisible(marker.newPointMarker, false);
            }
        }
    },
    /**
     * Show/hide marker.
     */
    _setMarkerVisible: function(marker, show) {
        if(!marker)
            return;

        var map = this._map;
        if(show) {
            if(!marker._map) { // First show fo this marker:
                marker.addTo(map);
            } else { // Marker was already shown and hidden:
                map.addLayer(marker);
            }
            marker._visible = true;
            marker._map = map;
        } else {
            map.removeLayer(marker);
            marker._visible = false;
        }
    },
    /**
     * Add two markers (a point marker and his newPointMarker) for a
     * single point.
     *
     * Markers are not added on the map here, the marker.addTo(map) is called
     * only later when needed first time because of performance issues.
     */
    _addMarkers: function(pointNo, latLng, fixNeighbourPositions) {
        var that = this;
        var points = this.getLatLngs();
        var marker = L.marker(latLng, {draggable: true, icon: this.pointIcon});

        marker.newPointMarker = null;
        marker.on('dragend', function(event) {
            var marker = event.target;
            var pointNo = that._getPointNo(event.target);
            that.setLatLngs(that._getMarkerLatLngs());
            that._fixNeighbourPositions(pointNo);
            that._showBoundMarkers();
        });
        marker.on('contextmenu', function(event) {
            console.log('rightclick');
        });

        if(pointNo > 0) {
            var previousPoint = points[pointNo - 1];
            var newPointMarker = L.marker([(latLng.lat + previousPoint.lat) / 2.,
                                           (latLng.lng + previousPoint.lng) / 2.],
                                          {draggable: true, icon: this.newPointIcon});
            marker.newPointMarker = newPointMarker;
            newPointMarker.on('dragend', function(event) {
                var marker = event.target;
                var pointNo = that._getPointNo(event.target);
                that._addMarkers(pointNo, marker.getLatLng(), true);
                that.setLatLngs(that._getMarkerLatLngs());
                that._showBoundMarkers();
            });
        }

        this._markers.splice(pointNo, 0, marker);

        if(fixNeighbourPositions) {
            this._fixNeighbourPositions(pointNo);
        }
    },
    /**
     * Fix nearby new point markers when the new point is created.
     */
    _fixNeighbourPositions: function(pointNo) {
        var previousMarker = pointNo == 0 ? null : this._markers[pointNo - 1];
        var marker = this._markers[pointNo];
        var nextMarker = pointNo < this._markers.length - 1 ? this._markers[pointNo + 1] : null;
        if(marker && previousMarker) {
            marker.newPointMarker.setLatLng([(previousMarker.getLatLng().lat + marker.getLatLng().lat) / 2.,
                                             (previousMarker.getLatLng().lng + marker.getLatLng().lng) / 2.]);
        }
        if(marker && nextMarker) {
            nextMarker.newPointMarker.setLatLng([(marker.getLatLng().lat + nextMarker.getLatLng().lat) / 2.,
                                                 (marker.getLatLng().lng + nextMarker.getLatLng().lng) / 2.]);
        }
    },
    _getPointNo: function(marker) {
        for(var i = 0; i < this._markers.length; i++) {
            if(marker == this._markers[i] || marker == this._markers[i].newPointMarker) {
                console.log("Found:" + i);
                return i;
            }
        }
        console.log("Nothing found for:" + marker);
        return -1;
    },
    /**
     * Get polyline latLngs based on marker positions.
     */
    _getMarkerLatLngs: function() {
        var result = [];
        for(var i = 0; i < this._markers.length; i++)
            result.push(this._markers[i].getLatLng());
        return result;
    },
});

L.Polyline.polylineEditor.addInitHook(function () {
    //this._initMarkers();
});

L.Polyline.PolylineEditor = function(latlngs, options){
    return new L.Polyline.polylineEditor(latlngs, options);
};

<|endoftext|>


<commit_before>var fedoras = [],
	removalMethod = 'hide',
	showReportButton = true,
	banned = [],
	bannedWords = [];

chrome.storage.sync.get(["removalMethod", "showReportButton"], function(items) {
	if(_.has(items, "removalMethod")) {
		removalMethod = items.removalMethod;
	}
	if(_.has(items, "showReportButton")) {
		showReportButton = items.showReportButton;
	}
});

chrome.storage.local.get(["fedoras", "banned", "bannedWords"], function(items) {
	if(_.has(items, "fedoras")) {
		fedoras = items.fedoras;
	}
	if(_.has(items, "banned")) {
		banned = items.banned;
	}
	if(_.has(items, "bannedWords")) {
		bannedWords = items.bannedWords;
	}
});

var randomInt = function(min, max) {
    return Math.floor(Math.random()*(max-min+1)+min);
};

var localBan = function(profileId) {
	if(!_.contains(banned, profileId)) {
		chrome.storage.local.get("banned", function(items) {
			if(_.has(items, "banned")) {
				banned = items.banned;
			}
			banned.push(profileId);
		    chrome.storage.local.set({
		      banned: banned
		    });
		});
	}
};

var getParentUrl = function() {
	var isInIFrame = (parent !== window),
        parentUrl = null;

    if(isInIFrame) {
        parentUrl = _.escape(document.referrer);
    }

    return parentUrl;
};

var submitReport = function(profileId, comment) {
	$.ajax({
		url: 'https://jhvisser.com/hidefedora/html/submit/submit.php',
		type: 'POST',
		data: {
			submit: 1,
			profileUrl: profileId,
			comment: comment,
			youtubeUrl: getParentUrl()
		}
	});
};

var onReportClick = function(e) {
	if(confirm('Are you sure you want to report and ban fedora profile?')) {
		var profileId = $(this).data("profileId"),
			comment = $(this).data("comment");

		localBan(profileId);
		submitReport(profileId, comment);

		$(this).prop('disabled', true).html('Reported').addClass('hide-fedora-reported');

		setTimeout(function() {
			execute();
		}, 1000);
	}
};

var process = function(outerSelector, innerSelector) {
	$(outerSelector).each(function(index, element) {
		var el = $(element),
			profileId = el.find('[oid]').first().attr('oid'),
			comment = el.find('div.Ct').first().text(),
			thisEl = $(this);

		if(!thisEl.hasClass("hide-fedora-tagged")) {

			if(_.contains(fedoras, profileId) ||
				_.contains(banned, profileId) ||
				_.some(bannedWords, function(word) {
					return comment.toLowerCase().indexOf(_.unescape(word.toLowerCase())) > -1;
				})) {

				switch(removalMethod) {
					// Hide
					case "hide":
						thisEl.remove();
						break;
					// Replace
					case "replace-fedora-cat":
						if(!thisEl.hasClass("hide-fedora-found")) {

							thisEl.addClass("hide-fedora-found");

							var fileUrl = chrome.extension.getURL('resources/pics/fedora-cats/' + randomInt(1,22) + '.jpg');

							// Title
							el.find(".Ub.gna")
								.html("Replaced with a cat")
								.parent()
								.removeAttr('oid')
								.attr("href", fileUrl);
							// Text
							el.find(".Ct").html("Meow meow");
							// Img
							el.find(".Uk.vKa")
								.removeAttr('oid')
								.attr("src", "")
								.attr("src", fileUrl)
								.parent()
								.attr("href", fileUrl);
							// Controls
							el.find(".REa.Sea").remove();
							// Replies
							el.find(".Cx.fr").remove();
						}
						break;
				}
			}
			else if(showReportButton) {
				thisEl
					.find('.RN.f8b')
					.first()
					.after('<button type="button" class="hide-fedora-report-btn">HF</button>');

				thisEl.find('.hide-fedora-report-btn')
					.data('profileId', profileId)
					.data('comment', comment)
					.click(onReportClick);
			}

			thisEl.addClass("hide-fedora-tagged");
		}
	});
};

var execute = function() {
	process(".Yp.yt.Xa", ".ve.oba.HPa > a");
	process(".Ik.Wv", ".fR > a");
};

$.getJSON("https://jhvisser.com/hidefedora/getJSON.php", function(res) {
	fedoras = res.fedoras;
    chrome.storage.local.set({
      fedoras: res.fedoras
    });
});

$(function() {

	var target = document.querySelector('.yJa');

	if(target !== null) {

		// Set MutationObserver
		var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
		var observer = new MutationObserver(function() {
			execute();
		});

		var config = { childList: true, subtree: true };

		observer.observe(target, config);

		// Execute removal a couple of times before MutationObserver kicks in
		var counter = 0;
		var interval = setInterval(function() {
			execute();

	    	counter++;
	    	if(counter === 24) {
	        	clearInterval(interval);
	    	}
		}, 250);
	}

});
<commit_msg>Remove obsolete code<commit_after>var fedoras = [],
	removalMethod = 'hide',
	showReportButton = true,
	banned = [],
	bannedWords = [];

chrome.storage.sync.get(["removalMethod", "showReportButton"], function(items) {
	if(_.has(items, "removalMethod")) {
		removalMethod = items.removalMethod;
	}
	if(_.has(items, "showReportButton")) {
		showReportButton = items.showReportButton;
	}
});

chrome.storage.local.get(["fedoras", "banned", "bannedWords"], function(items) {
	if(_.has(items, "fedoras")) {
		fedoras = items.fedoras;
	}
	if(_.has(items, "banned")) {
		banned = items.banned;
	}
	if(_.has(items, "bannedWords")) {
		bannedWords = items.bannedWords;
	}
});

var randomInt = function(min, max) {
    return Math.floor(Math.random()*(max-min+1)+min);
};

var localBan = function(profileId) {
	if(!_.contains(banned, profileId)) {
		chrome.storage.local.get("banned", function(items) {
			if(_.has(items, "banned")) {
				banned = items.banned;
			}
			banned.push(profileId);
		    chrome.storage.local.set({
		      banned: banned
		    });
		});
	}
};

var getParentUrl = function() {
	var isInIFrame = (parent !== window),
        parentUrl = null;

    if(isInIFrame) {
        parentUrl = _.escape(document.referrer);
    }

    return parentUrl;
};

var submitReport = function(profileId, comment) {
	$.ajax({
		url: 'https://jhvisser.com/hidefedora/html/submit/submit.php',
		type: 'POST',
		data: {
			submit: 1,
			profileUrl: profileId,
			comment: comment,
			youtubeUrl: getParentUrl()
		}
	});
};

var onReportClick = function(e) {
	if(confirm('Are you sure you want to report and ban fedora profile?')) {
		var profileId = $(this).data("profileId"),
			comment = $(this).data("comment");

		localBan(profileId);
		submitReport(profileId, comment);

		$(this).prop('disabled', true).html('Reported').addClass('hide-fedora-reported');

		setTimeout(function() {
			execute();
		}, 1000);
	}
};

var process = function(outerSelector, innerSelector) {
	$(outerSelector).each(function(index, element) {
		var el = $(element),
			profileId = el.find('[oid]').first().attr('oid'),
			comment = el.find('div.Ct').first().text(),
			thisEl = $(this);

		if(!thisEl.hasClass("hide-fedora-tagged")) {
			thisEl.addClass("hide-fedora-tagged");

			if(_.contains(fedoras, profileId) ||
				_.contains(banned, profileId) ||
				_.some(bannedWords, function(word) {
					return comment.toLowerCase().indexOf(_.unescape(word.toLowerCase())) > -1;
				})) {

				switch(removalMethod) {
					// Hide
					case "hide":
						thisEl.remove();
						break;
					// Replace
					case "replace-fedora-cat":
						var fileUrl = chrome.extension.getURL('resources/pics/fedora-cats/' + randomInt(1,22) + '.jpg');

						// Title
						el.find(".Ub.gna")
							.html("Replaced with a cat")
							.parent()
							.removeAttr('oid')
							.attr("href", fileUrl);
						// Text
						el.find(".Ct").html("Meow meow");
						// Img
						el.find(".Uk.vKa")
							.removeAttr('oid')
							.attr("src", "")
							.attr("src", fileUrl)
							.parent()
							.attr("href", fileUrl);
						// Controls
						el.find(".REa.Sea").remove();
						// Replies
						el.find(".Cx.fr").remove();
						break;
				}
			}
			else if(showReportButton) {
				thisEl
					.find('.RN.f8b')
					.first()
					.after('<button type="button" class="hide-fedora-report-btn">HF</button>');

				thisEl.find('.hide-fedora-report-btn')
					.data('profileId', profileId)
					.data('comment', comment)
					.click(onReportClick);
			}
		}
	});
};

var execute = function() {
	process(".Yp.yt.Xa", ".ve.oba.HPa > a");
	process(".Ik.Wv", ".fR > a");
};

$.getJSON("https://jhvisser.com/hidefedora/getJSON.php", function(res) {
	fedoras = res.fedoras;
    chrome.storage.local.set({
      fedoras: res.fedoras
    });
});

$(function() {

	var target = document.querySelector('.yJa');

	if(target !== null) {

		// Set MutationObserver
		var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
		var observer = new MutationObserver(function() {
			execute();
		});

		var config = { childList: true, subtree: true };

		observer.observe(target, config);

		// Execute removal a couple of times before MutationObserver kicks in
		var counter = 0;
		var interval = setInterval(function() {
			execute();

	    	counter++;
	    	if(counter === 24) {
	        	clearInterval(interval);
	    	}
		}, 250);
	}

});
<|endoftext|>


<commit_before>/* Special logs */

const DATA_LOGS_PATH = "./logs/data-bot/";

function checkDir (dir) {
	try {
		if (!fs.existsSync(dir))
			fs.mkdirSync(dir);
	} catch (e) {}
}

function writeFile (file, data) {
	fs.writeFileSync(DATA_LOGS_PATH + file, data);
}

function getDynCmds () {
	var list = Object.keys(CommandParser.dynCommands).sort();
	if (!list.length) return "No hay comandos";
	var text = "Lista de comandos dinámicos" + ':\n\n';
	for (var i in CommandParser.dynCommands) {
		if (CommandParser.dynCommands[i].substr(0, 4) === "/ref") {
			text += i + ' ~ ' + toId(CommandParser.dynCommands[i].substr(5)) + '\n';
			continue;
		}
		text += i + ' -> "' + CommandParser.dynCommands[i] + '"' + '\n';
	}
	return text;
}

function getZeroTol () {
	var ztList = [];
	if (Settings.settings['zerotol']) {
		for (var i in Settings.settings['zerotol']) {
			var level = ztLevels[Settings.settings['zerotol'][i]] ? ztLevels[Settings.settings['zerotol'][i]].name : Settings.settings['zerotol'][i];
			ztList.push("Usuario" + ': ' + i + ' | ' + "Nivel" + ': ' + level);
		}
	}
	if (ztList.length) {
		return "Usuarios en la lista de toletancia 0" + ':\n\n' + ztList.join('\n');
	} else {
		return "La lista de tolerancia 0 esta vacía"
	}
}

function getAutoBan (tarRoom) {
	var nBans = 0;
	var text = "";
	if (Settings.settings['autoban'] && Settings.settings['autoban'][tarRoom]) {
		text += "Usuarios baneados permanentemente en" + ' ' + tarRoom + ':\n\n';
		for (var i in Settings.settings['autoban'][tarRoom]) {
			text += i + "\n";
			nBans++;
		}
	}
	if (Settings.settings['regexautoban'] && Settings.settings['regexautoban'][tarRoom]) {
		text += '\n' + "Expresiones regulares baneadas en" + ' ' + tarRoom + ':\n\n';
		for (var i in Settings.settings['regexautoban'][tarRoom]) {
			text += i + "\n";
			nBans++;
		}
	}
	if (nBans) {
		return text;
	} else {
		return "No hay usuarios en la lista negra de esta sala";
	}
}

function getBanWords (tarRoom) {
	if (!Settings.settings['bannedphrases']) return "(Empty list)";
	var bannedPhrases = Settings.settings['bannedphrases'][tarRoom];
	if (!bannedPhrases) return "(Empty list)";
	var banList = Object.keys(bannedPhrases);
	if (!banList.length) return "(Empty list)";
	return "Frases prohibidas en " + tarRoom + ":\n\n" + banList.join('\n');
}

exports.commands = {
	setlogslink: function (arg, by, room, cmd) {
		if (!this.isExcepted) return false;
		Settings.settings['prlogslink'] = arg;
		Settings.save();
		this.reply("Enlace para los logs del chat modificado: " + Settings.settings['prlogslink']);
	},
	logslink: 'getlogs',
	logs: 'getlogs',
	getlogs: function (arg, by, room, cmd) {
		if (!this.isExcepted && (room !== 'salastaff' || !this.isRanked('@'))) return false;
		this.reply("Logs del chat: " + Settings.settings['prlogslink']);
	},
	udl: 'updatedatalogs',
	updatedatalogs: function (arg, by, room, cmd) {
		if (!this.isRanked('~')) return false;
		checkDir(DATA_LOGS_PATH);
		writeFile("commands.log", getDynCmds());
		writeFile("zerotlerance.log", getZeroTol());
		writeFile("autoban-espaol.log", getAutoBan("espaol"));
		writeFile("autoban-eventos.log", getAutoBan("eventos"));
		writeFile("banwords-espaol.log", getBanWords("espaol"));
		writeFile("banwords-eventos.log", getBanWords("eventos"));
		this.reply("Archivos de datos actualizados");
	}
};
<commit_msg>Fix crash<commit_after>/* Special logs */

const DATA_LOGS_PATH = "./logs/data-bot/";

function checkDir (dir) {
	try {
		if (!fs.existsSync(dir))
			fs.mkdirSync(dir);
	} catch (e) {}
}

function writeFile (file, data) {
	fs.writeFileSync(DATA_LOGS_PATH + file, data);
}

function getDynCmds () {
	var list = Object.keys(CommandParser.dynCommands).sort();
	if (!list.length) return "No hay comandos";
	var text = "Lista de comandos dinámicos" + ':\n\n';
	for (var i in CommandParser.dynCommands) {
		if (CommandParser.dynCommands[i].substr(0, 4) === "/ref") {
			text += i + ' ~ ' + toId(CommandParser.dynCommands[i].substr(5)) + '\n';
			continue;
		}
		text += i + ' -> "' + CommandParser.dynCommands[i] + '"' + '\n';
	}
	return text;
}

function getZeroTol () {
	var ztLevels, defaultLevel, aliases;
	if (Config.moderation && Config.moderation.zeroToleranceLevels && Config.moderation.zeroToleranceDefaultLevel) {
		ztLevels = Config.moderation.zeroToleranceLevels;
		defaultLevel = Config.moderation.zeroToleranceDefaultLevel;
		aliases = {};
		for (var l in ztLevels) {
			if (ztLevels[l].name) aliases[toId(ztLevels[l].name)] = l;
		}
	} else {
		return "La lista de tolerancia 0 esta deshabilitada";
	}
	var ztList = [];
	if (Settings.settings['zerotol']) {
		for (var i in Settings.settings['zerotol']) {
			var level = ztLevels[Settings.settings['zerotol'][i]] ? ztLevels[Settings.settings['zerotol'][i]].name : Settings.settings['zerotol'][i];
			ztList.push("Usuario" + ': ' + i + ' | ' + "Nivel" + ': ' + level);
		}
	}
	if (ztList.length) {
		return "Usuarios en la lista de toletancia 0" + ':\n\n' + ztList.join('\n');
	} else {
		return "La lista de tolerancia 0 esta vacía"
	}
}

function getAutoBan (tarRoom) {
	var nBans = 0;
	var text = "";
	if (Settings.settings['autoban'] && Settings.settings['autoban'][tarRoom]) {
		text += "Usuarios baneados permanentemente en" + ' ' + tarRoom + ':\n\n';
		for (var i in Settings.settings['autoban'][tarRoom]) {
			text += i + "\n";
			nBans++;
		}
	}
	if (Settings.settings['regexautoban'] && Settings.settings['regexautoban'][tarRoom]) {
		text += '\n' + "Expresiones regulares baneadas en" + ' ' + tarRoom + ':\n\n';
		for (var i in Settings.settings['regexautoban'][tarRoom]) {
			text += i + "\n";
			nBans++;
		}
	}
	if (nBans) {
		return text;
	} else {
		return "No hay usuarios en la lista negra de esta sala";
	}
}

function getBanWords (tarRoom) {
	if (!Settings.settings['bannedphrases']) return "(Empty list)";
	var bannedPhrases = Settings.settings['bannedphrases'][tarRoom];
	if (!bannedPhrases) return "(Empty list)";
	var banList = Object.keys(bannedPhrases);
	if (!banList.length) return "(Empty list)";
	return "Frases prohibidas en " + tarRoom + ":\n\n" + banList.join('\n');
}

exports.commands = {
	setlogslink: function (arg, by, room, cmd) {
		if (!this.isExcepted) return false;
		Settings.settings['prlogslink'] = arg;
		Settings.save();
		this.reply("Enlace para los logs del chat modificado: " + Settings.settings['prlogslink']);
	},
	logslink: 'getlogs',
	logs: 'getlogs',
	getlogs: function (arg, by, room, cmd) {
		if (!this.isExcepted && (room !== 'salastaff' || !this.isRanked('@'))) return false;
		this.reply("Logs del chat: " + Settings.settings['prlogslink']);
	},
	udl: 'updatedatalogs',
	updatedatalogs: function (arg, by, room, cmd) {
		if (!this.isRanked('~')) return false;
		checkDir(DATA_LOGS_PATH);
		writeFile("commands.log", getDynCmds());
		writeFile("zerotlerance.log", getZeroTol());
		writeFile("autoban-espaol.log", getAutoBan("espaol"));
		writeFile("autoban-eventos.log", getAutoBan("eventos"));
		writeFile("banwords-espaol.log", getBanWords("espaol"));
		writeFile("banwords-eventos.log", getBanWords("eventos"));
		this.reply("Archivos de datos actualizados");
	}
};
<|endoftext|>


<commit_before>'use strict';

const _         = require('lodash');
const events    = require('events');
const Immutable = require('immutable');

const combineHandlers = require('./combineHandlers');
const ParseContext    = require('./ParseContext');

/**
 * Maps incoming top-level object events to
 * context instances and fire deeper events
 */
class EventParser extends events.EventEmitter {

    constructor() {
        super();
        this.contexts = {};
        this.handlers = [];

        /*  Number of handlers that are to remain at the end of the stack regardless of whether new handlers
         Are inserted "last" */
        this.finalHandlers = 0;
    }

    /**
     * Read incoming top-level object
     * @param obj
     */
    receive(obj) {
        if (obj.begin) this.begin(obj);
        this.fire(obj);
    }

    /**
     * Invoked for incoming "begin" objects
     * @param obj
     */
    begin(obj) {
        let id        = obj.context;
        let timestamp = obj.timestamp;
        let context   = new ParseContext(id, timestamp);
        _.extend(context, obj.begin);
        // e.g. "begin":{"parent":"507d8410-b172-11e6-a36f-7f298ebb314a","scope":{"action":"land"}}
        // Translate context to actual object
        if (context.parent && context.parent !== null)
            context.parent = this.getContext(context.parent);
        this.contexts[id] = context;
        this.emit('begin', context);
    }

    /**
     * Invoke event handlers for the given event object
     * @param obj
     */
    fire(obj) {

        let context   = this.getContext(obj.context);
        let timestamp = obj.timestamp;
        let data      = Immutable.fromJS(_.omit(obj, 'context', 'timestamp'));

        let info = {context, timestamp};

        _(this.handlers)
            .concat((data, info) => this.emit('uncaught', data, info))
            .forEach(handler => {
                data = handler(data, info, obj);
                if (data === null || data === undefined) return false;
            });
    }

    /**
     * Add the given function to the end of the handler stack, and make sure handlers that are subsequently added
     * will be inserted before the given one (unless added via `useFinal`)
     *
     * @param {Function} fn
     */
    useFinal(fn) {
        this.finalHandlers++;
        this.handlers.push(fn);
    }

    /**
     * Push the given function onto the event handler stack.
     * The function must return either true (consumed) or false (not consumed) in order to propagate the event
     * to the next handler if appropriate.
     *
     * Event handlers will be invoked with two arguments:
     * 1. An immutable data structure containing the event object with "context" and "timestamp" omitted
     * 2. An object containing {timestamp, context} where context is an instance of ParserContext
     * 3. The raw incoming object
     *
     * @param {Function} fn
     * @param {Boolean} [first = false] Whether to push the handler to the front of the stack
     */
    use(fn, first = false) {
        if (first) this.handlers.unshift(fn);
        else this.handlers.splice(this.handlers.length - this.finalHandlers, 0, fn);
    }

    /**
     * Same as `use` but expects an object of handlers that will be combined using `combineHandlers`
     *
     * @param {Object} fns
     * @param {Boolean} [first = false] Whether to push the handlers to the front of the stack
     */
    useCombine(fns, first = false) {
        this.use(combineHandlers(fns), first);
    }

    /**
     * By enabling this, an error will be thrown for any event
     * that is not handled by the handler stack.
     *
     * @param {boolean} [on = true]
     */
    setStrict(on = true) {
        if (!on && this.uncaughtEventListener) {
            this.removeListener('uncaught', this.uncaughtEventListener);
            this.uncaughtEventListener = null;
        }
        if (on) {
            this.uncaughtEventListener = (data, info) => {
                throw new Error(`Unhandled event in EventParser: ${JSON.stringify(data)}`);
            };
            this.addListener('uncaught', this.uncaughtEventListener);
        }
    }

    /**
     * Get the context associated with the given id
     * @param {String} id
     * @returns {Context}
     */
    getContext(id) {
        return this.contexts[id];
    }
}

module.exports = EventParser;<commit_msg>let EventParser include the full event as the second argument when firing the “begin” event<commit_after>'use strict';

const _         = require('lodash');
const events    = require('events');
const Immutable = require('immutable');

const combineHandlers = require('./combineHandlers');
const ParseContext    = require('./ParseContext');

/**
 * Maps incoming top-level object events to
 * context instances and fire deeper events
 */
class EventParser extends events.EventEmitter {

    constructor() {
        super();
        this.contexts = {};
        this.handlers = [];

        /*  Number of handlers that are to remain at the end of the stack regardless of whether new handlers
         Are inserted "last" */
        this.finalHandlers = 0;
    }

    /**
     * Read incoming top-level object
     * @param obj
     */
    receive(obj) {
        if (obj.begin) this.begin(obj);
        this.fire(obj);
    }

    /**
     * Invoked for incoming "begin" objects
     * @param obj
     */
    begin(obj) {
        let id        = obj.context;
        let timestamp = obj.timestamp;
        let context   = new ParseContext(id, timestamp);
        _.extend(context, obj.begin);
        // e.g. "begin":{"parent":"507d8410-b172-11e6-a36f-7f298ebb314a","scope":{"action":"land"}}
        // Translate context to actual object
        if (context.parent && context.parent !== null)
            context.parent = this.getContext(context.parent);
        this.contexts[id] = context;
        this.emit('begin', context, obj);
    }

    /**
     * Invoke event handlers for the given event object
     * @param obj
     */
    fire(obj) {

        let context   = this.getContext(obj.context);
        let timestamp = obj.timestamp;
        let data      = Immutable.fromJS(_.omit(obj, 'context', 'timestamp'));

        let info = {context, timestamp};

        _(this.handlers)
            .concat((data, info) => this.emit('uncaught', data, info))
            .forEach(handler => {
                data = handler(data, info, obj);
                if (data === null || data === undefined) return false;
            });
    }

    /**
     * Add the given function to the end of the handler stack, and make sure handlers that are subsequently added
     * will be inserted before the given one (unless added via `useFinal`)
     *
     * @param {Function} fn
     */
    useFinal(fn) {
        this.finalHandlers++;
        this.handlers.push(fn);
    }

    /**
     * Push the given function onto the event handler stack.
     * The function must return either true (consumed) or false (not consumed) in order to propagate the event
     * to the next handler if appropriate.
     *
     * Event handlers will be invoked with two arguments:
     * 1. An immutable data structure containing the event object with "context" and "timestamp" omitted
     * 2. An object containing {timestamp, context} where context is an instance of ParserContext
     * 3. The raw incoming object
     *
     * @param {Function} fn
     * @param {Boolean} [first = false] Whether to push the handler to the front of the stack
     */
    use(fn, first = false) {
        if (first) this.handlers.unshift(fn);
        else this.handlers.splice(this.handlers.length - this.finalHandlers, 0, fn);
    }

    /**
     * Same as `use` but expects an object of handlers that will be combined using `combineHandlers`
     *
     * @param {Object} fns
     * @param {Boolean} [first = false] Whether to push the handlers to the front of the stack
     */
    useCombine(fns, first = false) {
        this.use(combineHandlers(fns), first);
    }

    /**
     * By enabling this, an error will be thrown for any event
     * that is not handled by the handler stack.
     *
     * @param {boolean} [on = true]
     */
    setStrict(on = true) {
        if (!on && this.uncaughtEventListener) {
            this.removeListener('uncaught', this.uncaughtEventListener);
            this.uncaughtEventListener = null;
        }
        if (on) {
            this.uncaughtEventListener = (data, info) => {
                throw new Error(`Unhandled event in EventParser: ${JSON.stringify(data)}`);
            };
            this.addListener('uncaught', this.uncaughtEventListener);
        }
    }

    /**
     * Get the context associated with the given id
     * @param {String} id
     * @returns {Context}
     */
    getContext(id) {
        return this.contexts[id];
    }
}

module.exports = EventParser;<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

App.HighAvailabilityWizardController = App.WizardController.extend({

  name: 'highAvailabilityWizardController',

  totalSteps: 9,

  /**
   * @type {string}
   */
  displayName: Em.I18n.t('admin.highAvailability.wizard.header'),

  /**
   * Used for hiding back button in wizard
   */
  hideBackButton: true,

  content: Em.Object.create({
    controllerName: 'highAvailabilityWizardController',
    cluster: null,
    hosts: null,
    services: null,
    slaveComponentHosts: null,
    masterComponentHosts: null,
    serviceConfigProperties: [],
    serviceName: 'MISC',
    hdfsUser:"hdfs",
    nameServiceId: '',
    failedTask : null,
    requestIds: null
  }),

  setCurrentStep: function (currentStep, completed) {
    this._super(currentStep, completed);
    App.clusterStatus.setClusterStatus({
      clusterName: this.get('content.cluster.name'),
      clusterState: 'HIGH_AVAILABILITY_DEPLOY',
      wizardControllerName: 'highAvailabilityWizardController',
      localdb: App.db.data
    });
  },

  /**
   * return new object extended from clusterStatusTemplate
   * @return Object
   */
  getCluster: function(){
    return jQuery.extend({}, this.get('clusterStatusTemplate'), {name: App.router.getClusterName()});
  },

  /**
   * save status of the cluster.
   * @param clusterStatus object with status,requestId fields.
   */
  saveClusterStatus: function (clusterStatus) {
    var oldStatus = this.toObject(this.get('content.cluster'));
    clusterStatus = jQuery.extend(oldStatus, clusterStatus);
    if (clusterStatus.requestId) {
      clusterStatus.requestId.forEach(function (requestId) {
        if (clusterStatus.oldRequestsId.indexOf(requestId) === -1) {
          clusterStatus.oldRequestsId.push(requestId)
        }
      }, this);
    }
    this.set('content.cluster', clusterStatus);
    this.save('cluster');
  },

  saveHdfsUser: function () {
    App.db.setHighAvailabilityWizardHdfsUser(this.get('content.hdfsUser'));
  },

  saveTasksStatuses: function(statuses){
    App.db.setHighAvailabilityWizardTasksStatuses(statuses);
    this.set('content.tasksStatuses', statuses);
  },

  saveConfigTag: function(tag){
    App.db.setHighAvailabilityWizardConfigTag(tag);
    this.set('content.'+[tag.name], tag.value);
  },

  saveHdfsClientHosts: function(hostNames){
    App.db.setHighAvailabilityWizardHdfsClientHosts(hostNames);
    this.set('content.hdfsClientHostNames', hostNames);
  },

    /**
     * Save config properties
     * @param stepController HighAvailabilityWizardStep3Controller
     */
  saveServiceConfigProperties: function(stepController) {
    var serviceConfigProperties = [];
    var data = stepController.get('serverConfigData');

    var _content = stepController.get('stepConfigs')[0];
    _content.get('configs').forEach(function (_configProperties) {
      var siteObj = data.items.findProperty('type', _configProperties.get('filename'));
      if (siteObj) {
        siteObj.properties[_configProperties.get('name')] = _configProperties.get('value');
      }
    }, this);
    this.setDBProperty('serviceConfigProperties', data);
    this.set('content.serviceConfigProperties', data);
  },

  loadHdfsClientHosts: function(){
    var hostNames = App.db.getHighAvailabilityWizardHdfsClientHosts();
    if (!(hostNames instanceof Array)) {
      hostNames = [hostNames];
    }
    this.set('content.hdfsClientHostNames', hostNames);
  },

  loadConfigTag: function(tag){
    var tagVal = App.db.getHighAvailabilityWizardConfigTag(tag);
    this.set('content.'+tag, tagVal);
  },

  loadHdfsUser: function(){
    var hdfsUser = App.db.getHighAvailabilityWizardHdfsUser();
    this.set('content.hdfsUser', hdfsUser);
  },

  loadTasksStatuses: function(){
    var statuses = App.db.getHighAvailabilityWizardTasksStatuses();
    this.set('content.tasksStatuses', statuses);
  },

  /**
   * Load serviceConfigProperties to model
   */
  loadServiceConfigProperties: function () {
    var serviceConfigProperties = this.getDBProperty('serviceConfigProperties');
    this.set('content.serviceConfigProperties', serviceConfigProperties);
  },

  saveRequestIds: function(requestIds){
    App.db.setHighAvailabilityWizardRequestIds(requestIds);
    this.set('content.requestIds', requestIds);
  },

  loadRequestIds: function(){
    var requestIds = App.db.getHighAvailabilityWizardRequestIds();
    this.set('content.requestIds', requestIds);
  },

  saveNameServiceId: function(nameServiceId){
    App.db.setHighAvailabilityWizardNameServiceId(nameServiceId);
    this.set('content.nameServiceId', nameServiceId);
  },

  loadNameServiceId: function(){
    var nameServiceId = App.db.getHighAvailabilityWizardNameServiceId();
    this.set('content.nameServiceId', nameServiceId);
  },

  saveTasksRequestIds: function (requestIds) {
    App.db.setHighAvailabilityWizardTasksRequestIds(requestIds);
    this.set('content.tasksRequestIds', requestIds);
  },

  loadTasksRequestIds: function () {
    var requestIds = App.db.getHighAvailabilityWizardTasksRequestIds();
    this.set('content.tasksRequestIds', requestIds);
  },

  loadMap: {
    '1': [
      {
        type: 'async',
        callback: function () {
          var dfd = $.Deferred(),
            self = this,
            usersLoadingCallback = function () {
              self.saveHdfsUser();
              self.load('cluster');
              dfd.resolve();
            };
          if (App.db.getHighAvailabilityWizardHdfsUser()) {
            usersLoadingCallback();
          } else {
            this.usersLoading().done(function () {
              usersLoadingCallback();
            });
          }
          return dfd.promise();
        }
      }
    ],
    '2': [
      {
        type: 'async',
        callback: function () {
          var dfd = $.Deferred();
          var self = this;
          this.loadHosts().done(function () {
            self.loadServicesFromServer();
            self.loadMasterComponentHosts().done(function () {
              self.loadHdfsUser();
              dfd.resolve();
            });
          });
          return dfd.promise();
        }
      }
    ],
    '3': [
      {
        type: 'sync',
        callback: function () {
          this.loadNameServiceId();
          this.loadServiceConfigProperties();
        }
      }
    ],
    '5': [
      {
        type: 'sync',
        callback: function () {
          this.loadTasksStatuses();
          this.loadTasksRequestIds();
          this.loadRequestIds();
        }
      }
    ]
  },

  /**
   * Remove all loaded data.
   * Created as copy for App.router.clearAllSteps
   */
  clearAllSteps: function () {
    this.clearInstallOptions();
    // clear temporary information stored during the install
    this.set('content.cluster', this.getCluster());
  },

  clearTasksData: function () {
    this.saveTasksStatuses(undefined);
    this.saveRequestIds(undefined);
    this.saveTasksRequestIds(undefined);
  },

  /**
   * Clear all temporary data
   */
  finish: function () {
    App.db.data.Installer = {};
    this.resetDbNamespace();
    App.router.get('updateController').updateAll();
  }
});
<commit_msg>AMBARI-17657 Ambari uses default hdfs user on NNHA wizard. (ababiichuk)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

App.HighAvailabilityWizardController = App.WizardController.extend({

  name: 'highAvailabilityWizardController',

  totalSteps: 9,

  /**
   * @type {string}
   */
  displayName: Em.I18n.t('admin.highAvailability.wizard.header'),

  /**
   * Used for hiding back button in wizard
   */
  hideBackButton: true,

  content: Em.Object.create({
    controllerName: 'highAvailabilityWizardController',
    cluster: null,
    hosts: null,
    services: null,
    slaveComponentHosts: null,
    masterComponentHosts: null,
    serviceConfigProperties: [],
    serviceName: 'MISC',
    hdfsUser:"hdfs",
    nameServiceId: '',
    failedTask : null,
    requestIds: null
  }),

  setCurrentStep: function (currentStep, completed) {
    this._super(currentStep, completed);
    App.clusterStatus.setClusterStatus({
      clusterName: this.get('content.cluster.name'),
      clusterState: 'HIGH_AVAILABILITY_DEPLOY',
      wizardControllerName: 'highAvailabilityWizardController',
      localdb: App.db.data
    });
  },

  /**
   * return new object extended from clusterStatusTemplate
   * @return Object
   */
  getCluster: function(){
    return jQuery.extend({}, this.get('clusterStatusTemplate'), {name: App.router.getClusterName()});
  },

  /**
   * save status of the cluster.
   * @param clusterStatus object with status,requestId fields.
   */
  saveClusterStatus: function (clusterStatus) {
    var oldStatus = this.toObject(this.get('content.cluster'));
    clusterStatus = jQuery.extend(oldStatus, clusterStatus);
    if (clusterStatus.requestId) {
      clusterStatus.requestId.forEach(function (requestId) {
        if (clusterStatus.oldRequestsId.indexOf(requestId) === -1) {
          clusterStatus.oldRequestsId.push(requestId)
        }
      }, this);
    }
    this.set('content.cluster', clusterStatus);
    this.save('cluster');
  },

  saveHdfsUser: function () {
    App.db.setHighAvailabilityWizardHdfsUser(this.get('content.hdfsUser'));
  },

  saveTasksStatuses: function(statuses){
    App.db.setHighAvailabilityWizardTasksStatuses(statuses);
    this.set('content.tasksStatuses', statuses);
  },

  saveConfigTag: function(tag){
    App.db.setHighAvailabilityWizardConfigTag(tag);
    this.set('content.'+[tag.name], tag.value);
  },

  saveHdfsClientHosts: function(hostNames){
    App.db.setHighAvailabilityWizardHdfsClientHosts(hostNames);
    this.set('content.hdfsClientHostNames', hostNames);
  },

    /**
     * Save config properties
     * @param stepController HighAvailabilityWizardStep3Controller
     */
  saveServiceConfigProperties: function(stepController) {
    var serviceConfigProperties = [];
    var data = stepController.get('serverConfigData');

    var _content = stepController.get('stepConfigs')[0];
    _content.get('configs').forEach(function (_configProperties) {
      var siteObj = data.items.findProperty('type', _configProperties.get('filename'));
      if (siteObj) {
        siteObj.properties[_configProperties.get('name')] = _configProperties.get('value');
      }
    }, this);
    this.setDBProperty('serviceConfigProperties', data);
    this.set('content.serviceConfigProperties', data);
  },

  loadHdfsClientHosts: function(){
    var hostNames = App.db.getHighAvailabilityWizardHdfsClientHosts();
    if (!(hostNames instanceof Array)) {
      hostNames = [hostNames];
    }
    this.set('content.hdfsClientHostNames', hostNames);
  },

  loadConfigTag: function(tag){
    var tagVal = App.db.getHighAvailabilityWizardConfigTag(tag);
    this.set('content.'+tag, tagVal);
  },

  loadHdfsUser: function(){
    var hdfsUser = App.db.getHighAvailabilityWizardHdfsUser();
    this.set('content.hdfsUser', hdfsUser);
  },

  loadTasksStatuses: function(){
    var statuses = App.db.getHighAvailabilityWizardTasksStatuses();
    this.set('content.tasksStatuses', statuses);
  },

  /**
   * Load serviceConfigProperties to model
   */
  loadServiceConfigProperties: function () {
    var serviceConfigProperties = this.getDBProperty('serviceConfigProperties');
    this.set('content.serviceConfigProperties', serviceConfigProperties);
  },

  saveRequestIds: function(requestIds){
    App.db.setHighAvailabilityWizardRequestIds(requestIds);
    this.set('content.requestIds', requestIds);
  },

  loadRequestIds: function(){
    var requestIds = App.db.getHighAvailabilityWizardRequestIds();
    this.set('content.requestIds', requestIds);
  },

  saveNameServiceId: function(nameServiceId){
    App.db.setHighAvailabilityWizardNameServiceId(nameServiceId);
    this.set('content.nameServiceId', nameServiceId);
  },

  loadNameServiceId: function(){
    var nameServiceId = App.db.getHighAvailabilityWizardNameServiceId();
    this.set('content.nameServiceId', nameServiceId);
  },

  saveTasksRequestIds: function (requestIds) {
    App.db.setHighAvailabilityWizardTasksRequestIds(requestIds);
    this.set('content.tasksRequestIds', requestIds);
  },

  loadTasksRequestIds: function () {
    var requestIds = App.db.getHighAvailabilityWizardTasksRequestIds();
    this.set('content.tasksRequestIds', requestIds);
  },

  loadHdfsUserFromServer: function () {
    return App.get('router.configurationController').loadFromServer([{'siteName': 'hadoop-env'}]);
  },

  loadMap: {
    '1': [
      {
        type: 'async',
        callback: function () {
          var dfd = $.Deferred(),
            self = this,
            usersLoadingCallback = function () {
              self.saveHdfsUser();
              self.load('cluster');
              dfd.resolve();
            };
          if (App.db.getHighAvailabilityWizardHdfsUser()) {
            usersLoadingCallback();
          } else {
            this.loadHdfsUserFromServer().done(function (data) {
              self.set('content.hdfsUser', Em.get(data, '0.properties.hdfs_user'));
              usersLoadingCallback();
            });
          }
          return dfd.promise();
        }
      }
    ],
    '2': [
      {
        type: 'async',
        callback: function () {
          var dfd = $.Deferred();
          var self = this;
          this.loadHosts().done(function () {
            self.loadServicesFromServer();
            self.loadMasterComponentHosts().done(function () {
              self.loadHdfsUser();
              dfd.resolve();
            });
          });
          return dfd.promise();
        }
      }
    ],
    '3': [
      {
        type: 'sync',
        callback: function () {
          this.loadNameServiceId();
          this.loadServiceConfigProperties();
        }
      }
    ],
    '5': [
      {
        type: 'sync',
        callback: function () {
          this.loadTasksStatuses();
          this.loadTasksRequestIds();
          this.loadRequestIds();
        }
      }
    ]
  },

  /**
   * Remove all loaded data.
   * Created as copy for App.router.clearAllSteps
   */
  clearAllSteps: function () {
    this.clearInstallOptions();
    // clear temporary information stored during the install
    this.set('content.cluster', this.getCluster());
  },

  clearTasksData: function () {
    this.saveTasksStatuses(undefined);
    this.saveRequestIds(undefined);
    this.saveTasksRequestIds(undefined);
  },

  /**
   * Clear all temporary data
   */
  finish: function () {
    App.db.data.Installer = {};
    this.resetDbNamespace();
    App.router.get('updateController').updateAll();
  }
});
<|endoftext|>