<commit_before>/*
    newT
        a JavaScript template library

    author: jeffrey tierney | https://twitter.com/jeffreytierney
    project home: https://github.com/jeffreytierney/newT
    liscense: (see author)

    Usage:

        Create a new 'newT' -- a JS represention of DOM Template w/ event capabilities

            newT.save("id_name", function( data ) {
                // use the () for multiline return of DOM elements via newT.
                // the second param is the 'contents' of the element
                // this sample is a simple string derived from data when newT.render() is called
                return (
                    newT.div({clss : "my_css_class"}, data.foo)
                )
            });

        Converter syntax for Element CSS Class Attribute: "clss"

        Render DOM Elements
            @param string "id_name" template name
            @param (any) the data to pass to the method used in the second parameter of newT.save("name", func);
            newT.render("id_name", { foo : "hello world bars" } );

        Render DOM with options and scope

            newT.render("id_name", {}, {
                scope : obj_scope || this
                data : { } // will be overriden completely - not extended
                preData : func // execute w/ scope passed in
                pre : func // excuted w/ scope passed in
            })

        On Script Load
            On script load, the newT (or temp name is assigned) is initialized.
                This single instance allows convience referrals to complex structures through the
                newT iterface

        Use with innerHTML
            newT.renderToString("id_name", {
                foo : "I come back as a string, no a DOM node"
            });

        Iteration
            newT.each(["one", "two"], function( data, idx ) {
                console.log("data", data);
                console.log("index position", idx);
            })

        Innerards:
            newT.templates.global will provide current "templates"

*/

(function (temp) {
  // Default global var name will be newT
  // can be overridden by passing something different
  // into the self executing wrapper function
  temp = temp || "newT";

  // internally refer to it as T for brevity sake
  var T = function(options) {
    this.init(options || {});
  }, regex_pattern=/\<[^\>]+\>|\&[^ ]+;/;

  T.prototype = {
    constructor: T.prototype.constructor,
    version : "1.1.1.1",
    init: function(options) {
      this.options = options;
      this.templates = {};
      this.__createMethods();
      return this;
    },
    // simple function to save the passed in template
    save: function(name, template) {
      var name_parts = name.split("."),
          ns = "global";
      name = name_parts[0];
      if(name_parts.length > 1) {
        ns = name_parts[1];
      }
      if(!this.templates.hasOwnProperty(ns)) { this.templates[ns] = {}; }
      this.templates[ns][name] = template;
      return this;
    },
    // create the elements for the template
    // and if an exisiting root el was passed in, append it to that root
    // either way, return the newly created element(s)
    render: function(name, data, opts) {
      var name_parts = name.split("."),
          ns = "global",
          new_el;
      name = name_parts[0];
      if(name_parts.length > 1) {
        ns = name_parts[1];
      }

      opts = opts || {};
      opts.scope = opts.scope || null;
      opts.data = data;

      // if a preprocessing function is specified in the options, call it
      // use either the specified scope, or the default of null (set earlier)
      // params
      if (opts.preData) { opts.data = opts.preData.call(opts.scope, opts.data); }
      if (opts.pre) { var ret = opts.pre.call(opts.scope, opts.data); }

      new_el = this.templates[ns][name](opts.data);
      if(typeof new_el === "object" && new_el.length > 0) {
        var _new_el=new_el.slice(0);
        new_el=document.createDocumentFragment();
        for(var i in _new_el) {
            new_el.appendChild( _new_el[i] );
        }
      }

      if(opts.el) {
        opts.el.appendChild(new_el);
      }

      // if a posprocessing function is specified in the options, call it
      // use either the specified scope, or the default of null (set earlier)
      if (opts.post) { opts.post.call(opts.scope, new_el, opts.data); }
      return new_el;
    },
    renderToString: function(name, data, opts) {
      opts = opts || {};
      delete opts.el;

      var el = document.createElement("div");
      el.appendChild(this.render(name, data, opts));

      return el.innerHTML;

    },
    // function to iterate over a collection and render a template
    // for each item in the collection
    // uses a document fragment to collect each element and pass it back
    eachRender: function(data, template_name, opts) {
      opts = opts || {};
      var frag = document.createDocumentFragment();
      opts.el = frag;
      for(var i in data) {
        if(data.hasOwnProperty(i)) {
          this.render(template_name, data[i], opts);
        }
      }
      return frag;
    },
    // more free form iterator function that allows passing an ad-hoc
    // rendering function to be evaluated for each item in the collection
    // uses a document fragment to collect each element and pass it back
    each: function(data, func) {
      var frag = document.createDocumentFragment(), child, idx=0;
      for(var i in data) {
        if(data.hasOwnProperty(i)) {
          child = func(data[i], idx);
          if(child) {
            frag.appendChild(child);
          }
          idx+=1;
        }
      }
      return frag;
    },
    // function that gets called in initializing the class... loops through
    // list of allowed html elements, and creates a helper function on the prototype
    // to allow easy creation of that element simply by calling its name as a function
    __createMethods: function() {
      //var el_list = "a abbr acronym address applet area b base basefont bdo bgsound big blockquote body br button caption center cite code col colgroup comment custom dd del dfn dir div dl dt em embed fieldset font form frame frameset head h1 h2 h3 h4 h5 h6 hn hr html i iframe img input input ins isindex kbd label legend li link listing map marquee menu meta nobr noframes noscript object ol optgroup option p param plaintext pre q rt ruby s samp script select small span strike strong style sub sup table tbody td textarea tfoot th thead title tr tt u ul var wbr xml xmp video audio";
      var el_list = "a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup command datalist dd del details device dfn div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li link map mark menu meta meter nav noscript object ol optgroup option output p param pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td textarea tfoot th thead time title tr track ul var video wbr",
          els = el_list.split(" "),
          prefix = this.options.prefix || "", _this = this;

      // extra helper for just grouping a bunch together without a specific parent
      els.push("frag");

      for(var i=0, len=els.length; i<len; i++) (function(el) {
        T.prototype[prefix+el] = function() {
          var args = Array.prototype.slice.call(arguments);
          args.unshift(el);
          return T.prototype.element.apply(_this, args);
        }
      })(els[i]);
      return this;
    },
    // generic version of the function used to build the element specific creation functions
    // type -> name of element to create
    // attributes (optional) -> object with key/value pairs for attributes to be added to the element
    //                          to avoid silliness with using class as an object key
    //                          you must use "clss" to set class.  yuck
    // content (optional) -> arbitrarily many pieces of content to be added within the element
    //                       can be strings, domElements, or anything that evaluates to either of those
    element: function(type, attributes, content) {
      var args = Array.prototype.slice.call(arguments).slice(1),
          el = (type==="frag" ? document.createDocumentFragment() : document.createElement(type));
      if(args.length) {
        content = args;
      }
      else {
        return el;
      }

      if (args[0].toString() === "[object Object]") {
        attributes = content.shift();
      }
      else {
        attributes = null;
      }

      if(attributes) {
        // when is not an attribute... but can accept a test case that can be used for conditional rendering
        // if it evaluates to true, the node will be rendered... if not, rendering will be short-circuited and an empty string will be returned
        if("when" in attributes && !attributes.when) { el = null; return ""; }

        for(attr in attributes) {
          switch(attr.toLowerCase()) {
            case "clss":
            case "classname":
              el.className = (attributes[attr].join ? attributes[attr].join(" ") : attributes[attr]);
              break;
            case "style":
              el.cssText = el.style.cssText = attributes[attr];
              break;
            default:
              if(attr.charAt(0) === "_") {
                var attr_name = attr.substring(1);
                if(attributes[attr]) {
                  el.setAttribute(attr_name, attr_name);
                }
              }
              else{
                el.setAttribute(attr, attributes[attr]);
              }
          }
        }
      }

      for(var i=0, len=content.length; i<len; i++) {
        // if the content is a string, create a Text Node to hold it and append
        // unless (for now) there are html tags or entities in it... then just innerHTML it
        switch(typeof content[i]) {
            case "string":
                this.addText(el, content[i]);
            break;

            case "number":
                el.appendChild(document.createTextNode(content[i]));
            break;

            case "function":
                var result = content[i]();
                if(typeof result == "string") {
                  this.addText(el, result);
                }
                else {
                  el.appendChild(result);
                }
            break;

            default:
                el.appendChild(content[i]);
            break;

        }
      }
      return el;
    },
    addText: function(el, text) {
      if(text.match(regex_pattern)) {
        el.innerHTML += (this.options.safe_mode ? this.escapeHTML(text) : text);
      }
      else {
        el.appendChild(document.createTextNode((this.options.safe_mode ? this.escapeHTML(text) : text)));
      }
      return this;
    },
    // method to escape potentially unsafe_html.. will convert any chars that may enable script injection to their
    // html entity equivalent
    escapeHTML: function( unsafe_html ) {
        return (unsafe_html && unsafe_html.replace(/&/mg, "&").replace(/"/mg, """).replace(/'/mg, "'")
                     .replace(/>/mg, ">").replace(/</mg, "<") ) || "";
    },
    setOption: function(key, val){
      if (typeof key === "object") {
        for (var _key in key) { this.options[_key] = key[_key]; }
      }
      else {
        this.options[key] = val;
      }
      return this;
    },
    // when safe mode is set to on, any strings
    safeMode: function(on) {
      if(typeof on == "undefined") { on = true; }
      this.options["safe_mode"] = !!on;
      return this;
    },
    // If you want another separate instance of newT, perhaps to keep its own template management
    // call newT.clone() and it will return another freshly initialized copy (with a clear templates object)
    clone: function() {
      return new T();
    },
    // want to write plugin elements that can do more than just render dom elements?
    // such as dom elements that have some extra processing or ajax requests related to their rendering
    // extend the core newT prototype with this method.
    extend: function(name, func, force) {
      if(!(name in T.prototype) || force) {
        T.prototype[name] = func;
        return true;
      }
      return false;
    }
  }
  window[temp] = new T();
})();
<commit_msg>update comment to also clarify param name change<commit_after>/*
    newT
        a JavaScript template library

    author: jeffrey tierney | https://twitter.com/jeffreytierney
    project home: https://github.com/jeffreytierney/newT
    liscense: (see author)

    Usage:

        Create a new 'newT' -- a JS represention of DOM Template w/ event capabilities

            newT.save("id_name", function( data ) {
                // use the () for multiline return of DOM elements via newT.
                // the second param is the 'contents' of the element
                // this sample is a simple string derived from data when newT.render() is called
                return (
                    newT.div({clss : "my_css_class"}, data.foo)
                )
            });

        Converter syntax for Element CSS Class Attribute: "clss"

        Render DOM Elements
            @param string "id_name" template name
            @param (any) the data to pass to the method used in the second parameter of newT.save("name", func);
            newT.render("id_name", { foo : "hello world bars" } );

        Render DOM with options and scope

            newT.render("id_name", {}, {
                scope : obj_scope || this
                data : { } // will be overriden completely - not extended
                preData : func // execute w/ scope passed in
                pre : func // excuted w/ scope passed in
            })

        On Script Load
            On script load, the newT (or temp name is assigned) is initialized.
                This single instance allows convience referrals to complex structures through the
                newT iterface

        Use with innerHTML
            newT.renderToString("id_name", {
                foo : "I come back as a string, no a DOM node"
            });

        Iteration
            newT.each(["one", "two"], function( data, idx ) {
                console.log("data", data);
                console.log("index position", idx);
            })

        Innerards:
            newT.templates.global will provide current "templates"

*/

(function (temp) {
  // Default global var name will be newT
  // can be overridden by passing something different
  // into the self executing wrapper function
  temp = temp || "newT";

  // internally refer to it as T for brevity sake
  var T = function(options) {
    this.init(options || {});
  }, regex_pattern=/\<[^\>]+\>|\&[^ ]+;/;

  T.prototype = {
    constructor: T.prototype.constructor,
    version : "1.1.1.1",
    init: function(options) {
      this.options = options;
      this.templates = {};
      this.__createMethods();
      return this;
    },
    // simple function to save the passed in template
    save: function(name, template) {
      var name_parts = name.split("."),
          ns = "global";
      name = name_parts[0];
      if(name_parts.length > 1) {
        ns = name_parts[1];
      }
      if(!this.templates.hasOwnProperty(ns)) { this.templates[ns] = {}; }
      this.templates[ns][name] = template;
      return this;
    },
    // create the elements for the template
    // and if an exisiting root el was passed in, append it to that root
    // either way, return the newly created element(s)
    render: function(name, data, opts) {
      var name_parts = name.split("."),
          ns = "global",
          new_el;
      name = name_parts[0];
      if(name_parts.length > 1) {
        ns = name_parts[1];
      }

      opts = opts || {};
      opts.scope = opts.scope || null;
      opts.data = data;

      // if a preprocessing function is specified in the options, call it
      // use either the specified scope, or the default of null (set earlier)
      // params
      if (opts.preData) { opts.data = opts.preData.call(opts.scope, opts.data); }
      if (opts.pre) { var ret = opts.pre.call(opts.scope, opts.data); }

      new_el = this.templates[ns][name](opts.data);
      if(typeof new_el === "object" && new_el.length > 0) {
        var _new_el=new_el.slice(0);
        new_el=document.createDocumentFragment();
        for(var i in _new_el) {
            new_el.appendChild( _new_el[i] );
        }
      }

      if(opts.el) {
        opts.el.appendChild(new_el);
      }

      // if a posprocessing function is specified in the options, call it
      // use either the specified scope, or the default of null (set earlier)
      if (opts.post) { opts.post.call(opts.scope, new_el, opts.data); }
      return new_el;
    },
    renderToString: function(name, data, opts) {
      opts = opts || {};
      delete opts.el;

      var el = document.createElement("div");
      el.appendChild(this.render(name, data, opts));

      return el.innerHTML;

    },
    // function to iterate over a collection and render a previously saved template
    // for each item in the collection
    // uses a document fragment to collect each element and pass it back
    eachRender: function(data, template_name, opts) {
      opts = opts || {};
      var frag = document.createDocumentFragment();
      opts.el = frag;
      for(var i in data) {
        if(data.hasOwnProperty(i)) {
          this.render(template_name, data[i], opts);
        }
      }
      return frag;
    },
    // more free form iterator function that allows passing an ad-hoc
    // rendering function to be evaluated for each item in the collection
    // uses a document fragment to collect each element and pass it back
    each: function(data, func) {
      var frag = document.createDocumentFragment(), child, idx=0;
      for(var i in data) {
        if(data.hasOwnProperty(i)) {
          child = func(data[i], idx);
          if(child) {
            frag.appendChild(child);
          }
          idx+=1;
        }
      }
      return frag;
    },
    // function that gets called in initializing the class... loops through
    // list of allowed html elements, and creates a helper function on the prototype
    // to allow easy creation of that element simply by calling its name as a function
    __createMethods: function() {
      //var el_list = "a abbr acronym address applet area b base basefont bdo bgsound big blockquote body br button caption center cite code col colgroup comment custom dd del dfn dir div dl dt em embed fieldset font form frame frameset head h1 h2 h3 h4 h5 h6 hn hr html i iframe img input input ins isindex kbd label legend li link listing map marquee menu meta nobr noframes noscript object ol optgroup option p param plaintext pre q rt ruby s samp script select small span strike strong style sub sup table tbody td textarea tfoot th thead title tr tt u ul var wbr xml xmp video audio";
      var el_list = "a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup command datalist dd del details device dfn div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li link map mark menu meta meter nav noscript object ol optgroup option output p param pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td textarea tfoot th thead time title tr track ul var video wbr",
          els = el_list.split(" "),
          prefix = this.options.prefix || "", _this = this;

      // extra helper for just grouping a bunch together without a specific parent
      els.push("frag");

      for(var i=0, len=els.length; i<len; i++) (function(el) {
        T.prototype[prefix+el] = function() {
          var args = Array.prototype.slice.call(arguments);
          args.unshift(el);
          return T.prototype.element.apply(_this, args);
        }
      })(els[i]);
      return this;
    },
    // generic version of the function used to build the element specific creation functions
    // type -> name of element to create
    // attributes (optional) -> object with key/value pairs for attributes to be added to the element
    //                          to avoid silliness with using class as an object key
    //                          you must use "clss" to set class.  yuck
    // content (optional) -> arbitrarily many pieces of content to be added within the element
    //                       can be strings, domElements, or anything that evaluates to either of those
    element: function(type, attributes, content) {
      var args = Array.prototype.slice.call(arguments).slice(1),
          el = (type==="frag" ? document.createDocumentFragment() : document.createElement(type));
      if(args.length) {
        content = args;
      }
      else {
        return el;
      }

      if (args[0].toString() === "[object Object]") {
        attributes = content.shift();
      }
      else {
        attributes = null;
      }

      if(attributes) {
        // when is not an attribute... but can accept a test case that can be used for conditional rendering
        // if it evaluates to true, the node will be rendered... if not, rendering will be short-circuited and an empty string will be returned
        if("when" in attributes && !attributes.when) { el = null; return ""; }

        for(attr in attributes) {
          switch(attr.toLowerCase()) {
            case "clss":
            case "classname":
              el.className = (attributes[attr].join ? attributes[attr].join(" ") : attributes[attr]);
              break;
            case "style":
              el.cssText = el.style.cssText = attributes[attr];
              break;
            default:
              if(attr.charAt(0) === "_") {
                var attr_name = attr.substring(1);
                if(attributes[attr]) {
                  el.setAttribute(attr_name, attr_name);
                }
              }
              else{
                el.setAttribute(attr, attributes[attr]);
              }
          }
        }
      }

      for(var i=0, len=content.length; i<len; i++) {
        // if the content is a string, create a Text Node to hold it and append
        // unless (for now) there are html tags or entities in it... then just innerHTML it
        switch(typeof content[i]) {
            case "string":
                this.addText(el, content[i]);
            break;

            case "number":
                el.appendChild(document.createTextNode(content[i]));
            break;

            case "function":
                var result = content[i]();
                if(typeof result == "string") {
                  this.addText(el, result);
                }
                else {
                  el.appendChild(result);
                }
            break;

            default:
                el.appendChild(content[i]);
            break;

        }
      }
      return el;
    },
    addText: function(el, text) {
      if(text.match(regex_pattern)) {
        el.innerHTML += (this.options.safe_mode ? this.escapeHTML(text) : text);
      }
      else {
        el.appendChild(document.createTextNode((this.options.safe_mode ? this.escapeHTML(text) : text)));
      }
      return this;
    },
    // method to escape potentially unsafe_html.. will convert any chars that may enable script injection to their
    // html entity equivalent
    escapeHTML: function( unsafe_html ) {
        return (unsafe_html && unsafe_html.replace(/&/mg, "&").replace(/"/mg, """).replace(/'/mg, "'")
                     .replace(/>/mg, ">").replace(/</mg, "<") ) || "";
    },
    setOption: function(key, val){
      if (typeof key === "object") {
        for (var _key in key) { this.options[_key] = key[_key]; }
      }
      else {
        this.options[key] = val;
      }
      return this;
    },
    // when safe mode is set to on, any strings
    safeMode: function(on) {
      if(typeof on == "undefined") { on = true; }
      this.options["safe_mode"] = !!on;
      return this;
    },
    // If you want another separate instance of newT, perhaps to keep its own template management
    // call newT.clone() and it will return another freshly initialized copy (with a clear templates object)
    clone: function() {
      return new T();
    },
    // want to write plugin elements that can do more than just render dom elements?
    // such as dom elements that have some extra processing or ajax requests related to their rendering
    // extend the core newT prototype with this method.
    extend: function(name, func, force) {
      if(!(name in T.prototype) || force) {
        T.prototype[name] = func;
        return true;
      }
      return false;
    }
  }
  window[temp] = new T();
})();
<|endoftext|>


<commit_before>/**
 * Internal data structure to represent 2D QuadTree node
 */
module.exports = function Node() {
  // body stored inside this node. In quad tree only leaf nodes (by construction)
  // contain boides:
  this.body = null;

  // Child nodes are stored in quads. Each quad is presented by number:
  // 0 | 1
  // -----
  // 2 | 3
  this.quads = [];

  // Total mass of current node
  this.mass = 0;

  // Center of mass coordinates
  this.massX = 0;
  this.massY = 0;

  // bounding box coordinates
  this.left = 0;
  this.top = 0;
  this.bottom = 0;
  this.right = 0;

  // Node is internal when it is not a leaf
  this.isInternal = false;
};
<commit_msg>Removed redundant field<commit_after>/**
 * Internal data structure to represent 2D QuadTree node
 */
module.exports = function Node() {
  // body stored inside this node. In quad tree only leaf nodes (by construction)
  // contain boides:
  this.body = null;

  // Child nodes are stored in quads. Each quad is presented by number:
  // 0 | 1
  // -----
  // 2 | 3
  this.quads = [];

  // Total mass of current node
  this.mass = 0;

  // Center of mass coordinates
  this.massX = 0;
  this.massY = 0;

  // bounding box coordinates
  this.left = 0;
  this.top = 0;
  this.bottom = 0;
  this.right = 0;
};
<|endoftext|>


<commit_before>import React from 'react';

import { formatPercentage } from 'common/format';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';

import Enemies from 'parser/shared/modules/Enemies';
import ExecuteRange from './Execute/ExecuteRange';
import SpellUsable from '../features/SpellUsable';

class OverpowerAnalyzer extends Analyzer {
    static dependencies = {
        executeRange: ExecuteRange,
        enemies: Enemies,
        spellUsable: SpellUsable,
    }

    proc = 0;
    wastedProc = 0;

    hasEP = false;

    constructor(...args) {
        super(...args);
        this.hasEP = this.selectedCombatant.hasTrait(SPELLS.EXECUTIONERS_PRECISION_TRAIT.id);
    }

    on_byPlayer_cast(event) {
        if (event.ability.guid !== SPELLS.OVERPOWER.id) {
            return;
        }

        this.proc += 1;
        const overpower = this.selectedCombatant.getBuff(SPELLS.OVERPOWER.id);
        if (!this.executeRange.isTargetInExecuteRange(event) && !this.hasEP) {
            if (overpower !== undefined && overpower.stacks === 2 && this.spellUsable.isAvailable(SPELLS.MORTAL_STRIKE.id)) {
                this.wastedProc += 1;

                event.meta = event.meta || {};
                event.meta.isInefficientCast = true;
                event.meta.inefficientCastReason = 'This Overpower was used while already at 2 stacks and Mortal Strike was available';
            }
        } else if (this.hasEP) {
            if (overpower !== undefined && overpower.stacks === 2 && this.spellUsable.isAvailable(SPELLS.MORTAL_STRIKE.id)){
                this.wastedProc += 1;

                event.meta = event.meta || {};
                event.meta.isInefficientCast = true;
                event.meta.inefficientCastReason = 'This Overpower was used while already at 2 stacks and Mortal Strike was available.';
            }
        }
    }

    get WastedOverpowerThresholds() {
        return {
            actual: this.wastedProc / this.proc,
            isGreaterThan: {
                minor: 0,
                average: 0.05,
                major: 0.1,
            },
            style: 'percentage',
        };
    }

    suggestions(when) {
        when(this.WastedOverpowerThresholds).addSuggestion((suggest, actual, recommended) => {
            return suggest(<>Try to avoid using <SpellLink id={SPELLS.OVERPOWER.id} icon /> at 2 stacks when <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> is available. Use your stacks of Overpower with Mortal Strike to avoid over stacking, which result in a loss of damage.</>)
                .icon(SPELLS.OVERPOWER.icon)
                .actual(`${formatPercentage(actual)}% of Overpower stacks were wasted.`)
                .recommended(`${formatPercentage(recommended)}% is recommended.`);
        });
    }
}

export default OverpowerAnalyzer;<commit_msg>RC - overpower<commit_after>import React from 'react';

import { formatPercentage } from 'common/format';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';

import Enemies from 'parser/shared/modules/Enemies';
import ExecuteRange from './Execute/ExecuteRange';
import SpellUsable from '../features/SpellUsable';

class OverpowerAnalyzer extends Analyzer {
    static dependencies = {
        executeRange: ExecuteRange,
        enemies: Enemies,
        spellUsable: SpellUsable,
    }

    proc = 0;
    wastedProc = 0;

    hasEP = false;

    constructor(...args) {
        super(...args);
        this.hasEP = this.selectedCombatant.hasTrait(SPELLS.EXECUTIONERS_PRECISION_TRAIT.id);
    }

    on_byPlayer_cast(event) {
        if (event.ability.guid !== SPELLS.OVERPOWER.id) {
            return;
        }

        this.proc += 1;
        const overpower = this.selectedCombatant.getBuff(SPELLS.OVERPOWER.id);
        if (!this.executeRange.isTargetInExecuteRange(event) && !this.hasEP) {
            if (overpower !== undefined && overpower.stacks === 2 && this.spellUsable.isAvailable(SPELLS.MORTAL_STRIKE.id)) {
                this.wastedProc += 1;

                event.meta = event.meta || {};
                event.meta.isInefficientCast = true;
                event.meta.inefficientCastReason = 'This Overpower was used while already at 2 stacks and Mortal Strike was available';
            }
        } else if (this.hasEP) {
            if (overpower.stacks === 2 && this.spellUsable.isAvailable(SPELLS.MORTAL_STRIKE.id)){
                this.wastedProc += 1;

                event.meta = event.meta || {};
                event.meta.isInefficientCast = true;
                event.meta.inefficientCastReason = 'This Overpower was used while already at 2 stacks and Mortal Strike was available.';
            }
        }
    }

    get WastedOverpowerThresholds() {
        return {
            actual: this.wastedProc / this.proc,
            isGreaterThan: {
                minor: 0,
                average: 0.05,
                major: 0.1,
            },
            style: 'percentage',
        };
    }

    suggestions(when) {
        when(this.WastedOverpowerThresholds).addSuggestion((suggest, actual, recommended) => {
            return suggest(<>Try to avoid using <SpellLink id={SPELLS.OVERPOWER.id} icon /> at 2 stacks when <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> is available. Use your stacks of Overpower with Mortal Strike to avoid over stacking, which result in a loss of damage.</>)
                .icon(SPELLS.OVERPOWER.icon)
                .actual(`${formatPercentage(actual)}% of Overpower stacks were wasted.`)
                .recommended(`${formatPercentage(recommended)}% is recommended.`);
        });
    }
}

export default OverpowerAnalyzer;<|endoftext|>


<commit_before>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').click(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	/*
	$('.califica .button-frame').click(function(e){
		e.preventDefault();
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});
	*/

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		$(this).next().addClass('on');
	});

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a.title').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	$('td.school').hover(function(){
		$('.tooltip').css({top:$(this).position().top,display:'block'});
	},
	function(){
		$('.tooltip').css('display','none');
	});

	if($('.container').hasClass('perfil')){
		var cct = $('span.CCT').html();
		if(!($.cookie('escuelas')) || $.cookie('escuelas').split('-').indexOf(cct)==-1){
			$('a[href="'+cct+'"]').trigger('click');
			if(!$('a[href="'+cct+'"]').size()){
				toggle_escuela(cct);
			}
		}

	}

	if($('.container').hasClass('comparar')){
		console.log(false);
		$('#general-search').submit(function(e){
			e.preventDefault();
			var url='';
			$(this).find('[name]').each(function(i,val){
				url +='&'+$(val).attr('name')+'='+$(val).val();
			});
			window.location = $(this).attr('action')+url;
		});
	}

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			location.href = url;
		}
	}
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}
<commit_msg>error redirecciona en search de compara/escuelas<commit_after>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').click(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	/*
	$('.califica .button-frame').click(function(e){
		e.preventDefault();
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});
	*/

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		$(this).next().addClass('on');
	});

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a.title').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	$('td.school').hover(function(){
		$('.tooltip').css({top:$(this).position().top,display:'block'});
	},
	function(){
		$('.tooltip').css('display','none');
	});

	if($('.container').hasClass('perfil')){
		var cct = $('span.CCT').html();
		if(!($.cookie('escuelas')) || $.cookie('escuelas').split('-').indexOf(cct)==-1){
			$('a[href="'+cct+'"]').trigger('click');
			if(!$('a[href="'+cct+'"]').size()){
				toggle_escuela(cct);
			}
		}

	}

	if($('.container').hasClass('comparar')){
		console.log(false);
		$('#general-search').submit(function(e){
			e.preventDefault();
			var url='';
			$(this).find('[name]').each(function(i,val){
				url +='&'+$(val).attr('name')+'='+$(val).val();
			});
			window.location = $(this).attr('action')+url;
		});
	}

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			if(document.URL != url)
				location.href = url;
		}
	}
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}
<|endoftext|>


<commit_before><commit_msg>emitter.js upgraded to enable all features<commit_after><|endoftext|>


<commit_before><commit_msg>bug fix dispatch.context.get<commit_after><|endoftext|>


<commit_before>//External modules
var path = require('path');
var util = require("util");

// Module Compile
exports.init = function (grunt) {
    'use strict';

    var module = require(path.join(path.dirname(__dirname), "default")).init(grunt);
    var configuration = {};

    util._extend(module, {
        name: path.basename(__dirname),
        run: function () {
            this.getConfiguration();

            if (this.isNotEmptyObject(this.environment.libraries)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseLibraries(this.environment.libraries));
            }

            if (this.isNotEmptyObject(this.environment.reqModules)) {
                this.smartMerge(configuration.default.options, this.parseRequireModules(this.environment.reqModules));
            }

            if (this.isNotEmptyObject(this.environment.packages)) {
                this.parsePackages(this.environment.packages, configuration.default.options.packages);
            }

            if (this.isNotEmptyObject(this.environment.base)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseBaseLibs(this.environment.base));
            }

            if (typeof configuration.default != "undefined" && typeof configuration.default.options.dir != "undefined") {
                this.makeClear(configuration.default.options.dir);
            }

            // Set SourcePath
            configuration.default.options.sourcePath = this.lastConfigurations.compile.default.sourcePath;

            // For Debug ->
            grunt.log.debug(JSON.stringify(configuration));

            // Make bundles
            configuration.default.options.done = function (done, output) {
                var bundles = require('rjs-build-analysis').parse(output);
                var output = {};
                if (bundles.hasOwnProperty("bundles") && grunt.util.kindOf(bundles.bundles) == "array") {
                    bundles.bundles.forEach(function (bundle) {
                        output[(bundle.parent.substr(0, bundle.parent.lastIndexOf('/main')) || bundle.parent)] = bundle.children.map(function (bnd) {
                            return (bnd.substr(0, bnd.lastIndexOf('.')) || bnd);
                        });
                    });
                }
                module.configuration = module.mergeObjects(module.configuration, {
                    bundles: output
                });
                done();
            };

            this.configuration = configuration;

            // Setting configuration
            this.loadPlugin("grunt-contrib-requirejs");
            return this.runTask("requirejs", configuration);
        },
        getConfiguration: function () {
            // Load default configuration
            var configFile = path.resolve(__dirname, "config/default.json");
            if (grunt.file.exists(configFile)) {
                try {
                    configuration = grunt.file.readJSON(configFile);
                    grunt.log.debug(this.name + " plugin default configuration is loaded!");
                } catch (ex) {
                    grunt.log.error("[ERROR] " + this.name + " plugin default configuration has error!");
                    configuration = {};
                }
            }

            // Load user created configuration
            var userFile = path.resolve(process.cwd(), "config/build", this.name + ".js");
            if (grunt.file.exists(userFile)) {
                var config = require(userFile)(grunt);

                //Parsing configuration
                configuration = this.mergeObjects(configuration, this.parse(config));
            } else {
                grunt.log.debug(this.name + " user configuration not found, continue");
            }

            return configuration;
        },
        parse: function (configuration) {
            var parsed = {};

            // Parsing
            if (configuration.hasOwnProperty("source")) {
                parsed.baseUrl = path.resolve(process.cwd(), configuration.source);
            }

            if (configuration.hasOwnProperty("target")) {
                parsed.dir = path.resolve(process.cwd(), configuration.target);
            }

            // Fix for RequireJS
            return {
                default: {
                    options: parsed
                }
            };
        },
        parseLibraries: function (source) {
            var parsed = {
                modules: [],
                packages: [],
                paths: {}
            };

            for (var libraryName in source) {
                var library = source[libraryName];

                // Check each library and library name
                if (library) {
                    var includes = [];
                    var excludes = [];
                    var includeRequire = [];

                    // Check packages
                    if (this.isNotEmptyObject(library.packages)) {
                        for (var packageName in library.packages) {
                            var pkg = library.packages[packageName];

                            if (typeof pkg == "boolean") {
                                excludes.push(packageName);
                            } else {
                                includes.push(packageName);

                                includeRequire.push(
                                    pkg.requireName ? pkg.requireName : packageName
                                );

                                if (pkg.replace) {
                                    parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                                }
                            }
                        }
                    }

                    parsed.modules.push({
                        name: libraryName,
                        include: includes,
                        exclude: excludes,
                        insertRequire: includeRequire,
                        create: true
                    });

                    parsed.packages.push(libraryName);
                }

                parsed.packages = parsed.packages.concat(includes);
            }

            return parsed;
        },
        parseBaseLibs: function (libs) {
            var paths = {};
            for (var lib in libs) {
                paths[lib] = "empty:";
            }
            return {
                paths: paths
            };
        },
        parsePackages: function (packages, confPackages) {
            var parsed = confPackages || [];

            for (var packageName in packages) {
                var pkg = packages[packageName];

                if (pkg) {
                    parsed.push(packageName);
                    if (pkg.replace) {
                        parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                    }
                }
            }

            confPackages = parsed;
        },
        parseRequireModules: function (reqModules) {
            var result = {};

            for (var lib in reqModules) {
                result[lib] = path.resolve(this.modulePath, reqModules[lib]).replace(/.js$/, "");
            }

            return {
                paths: result,
                stubModules: Object.keys(result)
            };
        }
    });

    return module;
};<commit_msg>reqLibs path<commit_after>//External modules
var path = require('path');
var util = require("util");

// Module Compile
exports.init = function (grunt) {
    'use strict';

    var module = require(path.join(path.dirname(__dirname), "default")).init(grunt);
    var configuration = {};

    util._extend(module, {
        name: path.basename(__dirname),
        run: function () {
            this.getConfiguration();

            if (this.isNotEmptyObject(this.environment.libraries)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseLibraries(this.environment.libraries));
            }

            if (this.isNotEmptyObject(this.environment.reqModules)) {
                this.smartMerge(configuration.default.options, this.parseRequireModules(this.environment.reqModules));
            }

            if (this.isNotEmptyObject(this.environment.packages)) {
                this.parsePackages(this.environment.packages, configuration.default.options.packages);
            }

            if (this.isNotEmptyObject(this.environment.base)) {
                configuration.default.options = this.mergeObjects(configuration.default.options, this.parseBaseLibs(this.environment.base));
            }

            if (typeof configuration.default != "undefined" && typeof configuration.default.options.dir != "undefined") {
                this.makeClear(configuration.default.options.dir);
            }

            // Set SourcePath
            configuration.default.options.sourcePath = this.lastConfigurations.compile.default.sourcePath;

            // For Debug ->
            grunt.log.debug(JSON.stringify(configuration));

            // Make bundles
            configuration.default.options.done = function (done, output) {
                var bundles = require('rjs-build-analysis').parse(output);
                var output = {};
                if (bundles.hasOwnProperty("bundles") && grunt.util.kindOf(bundles.bundles) == "array") {
                    bundles.bundles.forEach(function (bundle) {
                        output[(bundle.parent.substr(0, bundle.parent.lastIndexOf('/main')) || bundle.parent)] = bundle.children.map(function (bnd) {
                            return (bnd.substr(0, bnd.lastIndexOf('.')) || bnd);
                        });
                    });
                }
                module.configuration = module.mergeObjects(module.configuration, {
                    bundles: output
                });
                done();
            };

            this.configuration = configuration;

            // Setting configuration
            this.loadPlugin("grunt-contrib-requirejs");
            return this.runTask("requirejs", configuration);
        },
        getConfiguration: function () {
            // Load default configuration
            var configFile = path.resolve(__dirname, "config/default.json");
            if (grunt.file.exists(configFile)) {
                try {
                    configuration = grunt.file.readJSON(configFile);
                    grunt.log.debug(this.name + " plugin default configuration is loaded!");
                } catch (ex) {
                    grunt.log.error("[ERROR] " + this.name + " plugin default configuration has error!");
                    configuration = {};
                }
            }

            // Load user created configuration
            var userFile = path.resolve(process.cwd(), "config/build", this.name + ".js");
            if (grunt.file.exists(userFile)) {
                var config = require(userFile)(grunt);

                //Parsing configuration
                configuration = this.mergeObjects(configuration, this.parse(config));
            } else {
                grunt.log.debug(this.name + " user configuration not found, continue");
            }

            return configuration;
        },
        parse: function (configuration) {
            var parsed = {};

            // Parsing
            if (configuration.hasOwnProperty("source")) {
                parsed.baseUrl = path.resolve(process.cwd(), configuration.source);
            }

            if (configuration.hasOwnProperty("target")) {
                parsed.dir = path.resolve(process.cwd(), configuration.target);
            }

            // Fix for RequireJS
            return {
                default: {
                    options: parsed
                }
            };
        },
        parseLibraries: function (source) {
            var parsed = {
                modules: [],
                packages: [],
                paths: {}
            };

            for (var libraryName in source) {
                var library = source[libraryName];

                // Check each library and library name
                if (library) {
                    var includes = [];
                    var excludes = [];
                    var includeRequire = [];

                    // Check packages
                    if (this.isNotEmptyObject(library.packages)) {
                        for (var packageName in library.packages) {
                            var pkg = library.packages[packageName];

                            if (typeof pkg == "boolean") {
                                excludes.push(packageName);
                            } else {
                                includes.push(packageName);

                                includeRequire.push(
                                    pkg.requireName ? pkg.requireName : packageName
                                );

                                if (pkg.replace) {
                                    parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                                }
                            }
                        }
                    }

                    parsed.modules.push({
                        name: libraryName,
                        include: includes,
                        exclude: excludes,
                        insertRequire: includeRequire,
                        create: true
                    });

                    parsed.packages.push(libraryName);
                }

                parsed.packages = parsed.packages.concat(includes);
            }

            return parsed;
        },
        parseBaseLibs: function (libs) {
            var paths = {};
            for (var lib in libs) {
                paths[lib] = "empty:";
            }
            return {
                paths: paths
            };
        },
        parsePackages: function (packages, confPackages) {
            var parsed = confPackages || [];

            for (var packageName in packages) {
                var pkg = packages[packageName];

                if (pkg) {
                    parsed.push(packageName);
                    if (pkg.replace) {
                        parsed.paths = this.mergeObjects(parsed.paths, pkg.replace);
                    }
                }
            }

            confPackages = parsed;
        },
        parseRequireModules: function (reqModules) {
            var result = {};

            for (var lib in reqModules) {
                var reqModulePath = reqModules[lib]
                    .replace("{path.fromKelper}", this.modulePath)
                    .replace("{path.fromSource}", path.resolve(process.cwd(), this.lastConfigurations.compile.default.sourcePath))
                    .replace("{path.fromRoot}", process.cwd());
                result[lib] = path.normalize(reqModulePath);
            }

            return {
                paths: result,
                stubModules: Object.keys(result)
            };
        }
    });

    return module;
};<|endoftext|>


<commit_before>var timeFrom;
var timeTo;
var timeUnit = null;
var listnedTimeFromValue;
var listnedTimeToValue;
var oTable;
var page = gadgetUtil.getCurrentPage();
var globalUniqueArray = [];
var TOPIC_USERNAME = "subscriberUser";
var TOPIC_USERPREF_DELETION = "subscriberUserPrefDeletion";
var TOPIC = "subscriber";
var listnedAdditionalUserPrefs = "";

$(function() {

    var historyParmExist = gadgetUtil.getURLParam("persistTimeFrom");

    if(historyParmExist == null){
        listnedTimeFromValue = gadgetUtil.timeFrom();
        listnedTimeToValue = gadgetUtil.timeTo();
    }else{
        var historyParms = gadgetUtil.getURLParams();

        for (var key in historyParms) {
            if (historyParms.hasOwnProperty(key)) {

                if(key == "persistTimeFrom"){
                    listnedTimeFromValue = historyParms[key];
                }else if(key == "persistTimeTo"){
                    listnedTimeToValue = historyParms[key];
                }else if(Object.keys(historyParms).length > 2){
                    var historyParamVal = historyParms[key].toString();
                    addUserPrefsToGlobalArray("Topic",key,historyParamVal.split("_")[0]);
                }
            }
        }
    }

    if (page.name == TYPE_LANDING || page.name == TYPE_RESIDENT_IDP) {
        var idpFilter = "";
        var columns = [];

        if(page.name == TYPE_LANDING) {
            idpFilter = " AND identityProviderType:\"FEDERATED\"";
            columns = [
                { title: "User Name" },
                { title: "Service Provider" },
                { title: "Identity Provider" },
                { title: "Roles" },
                { title: "Ip" },
                { title: "Region" },
                { title: "Authentication Step Success" },
                { title: "Overall Success" },
                { title: "Timestamp" }
            ];

        } else if(page.name == TYPE_RESIDENT_IDP) {
            idpFilter = " AND identityProviderType:\"LOCAL\"";
            columns = [
                { title: "User Name" },
                { title: "Service Provider" },
                { title: "Userstore" },
                { title: "Roles" },
                { title: "Ip" },
                { title: "Region" },
                { title: "Authentication Step Success" },
                { title: "Overall Success" },
                { title: "Timestamp" }
            ];
        }

        oTable = $('#tblMessages').DataTable({
            scrollY: 500,
            scrollX: true,
            dom: '<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            "processing": true,
            "serverSide": true,
            "searching": false,
            "columns" : columns,
            "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                if ( aData[6] == true && aData[7] == true )
                {
                   $('td', nRow).eq(7).html('

Success

');
                }
                else if ( aData[6] == false && aData[7] == false)
                {
                    $('td', nRow).eq(7).html('

Failure

');
                }
                else {
                    $('td', nRow).eq(7).html('

');
                }
            },
            "ajax": {
                "url" : AUTHENTICATION_CONTEXT,
                "data" : function (d) {
                    d.type = page.type;
                    d.timeFrom = parseInt(listnedTimeFromValue);
                    d.timeTo = parseInt(listnedTimeToValue);
                    d.listnedAdditionalUserPrefs = listnedAdditionalUserPrefs;
                    d.idpType = idpFilter;
                }
            }
        });
    } else if(page.name == TYPE_SESSIONS) {
        oTable = $('#tblMessages').DataTable({
            scrollY: 600,
            scrollX: true,
            dom: '<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            "processing": true,
            "serverSide": true,
            "searching": false,
            "columns" : [
                { title: "Session ID" },
                { title: "Username" },
                { title: "Start Time" },
                { title: "Termination Time" },
                { title: "End Time" },
                { title: "Duration" },
                { title: "Is Active" },
                { title: "Userstore Domain" },
                { title: "IP" },
                { title: "Tenant Domain" },
                { title: "Remember Me Flag" },
                { title: "Timestamp" }

            ],
            "ajax": {
                "url" : SESSION_CONTEXT,
                "data" : function (d) {
                    d.type = page.type;
                    d.timeFrom = parseInt(listnedTimeFromValue);
                    d.timeTo = parseInt(listnedTimeToValue);
                }
            }
        });
    }

    $('#tblMessages tbody').on('click', 'tr', function() {
        var id = $(this).find("td:first").html();
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        } else {
            dataTable.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
        /*if( timeUnit == null) {
         timeUnit = qs.timeUnit;
         }*/
        // var targetUrl = MESSAGE_PAGE_URL + "?" + PARAM_ID + "=" + id + "&timeFrom=" + timeFrom + "&timeTo=" + timeTo + "&timeUnit=" + timeUnit;;
        var targetUrl = MESSAGE_PAGE_URL + "?" + PARAM_ID + "=" + id;
        parent.window.location = targetUrl;
    });

});

gadgets.HubSettings.onConnect = function() {

    gadgets.Hub.subscribe(TOPIC, function(topic, data, subscriberData) {
        listnedTimeFromValue = data.timeFrom;
        listnedTimeToValue = data.timeTo;
        onDataChanged();
    });

    gadgets.Hub.subscribe(TOPIC_USERNAME, function(topic, data, subscriberData) {

        addUserPrefsToGlobalArray(topic,data.mode,data.userPrefValue);
        onDataChanged();
    });

    gadgets.Hub.subscribe(TOPIC_USERPREF_DELETION, function(topic, data, subscriberData) {

        var index;
        for(i=0;i<globalUniqueArray.length;i++){
            if(globalUniqueArray[i][2] == data.category){
                index = i;
                break;
            }
        }
        globalUniqueArray.splice(index, 1);
        listnedAdditionalUserPrefs = "";

        for(i=0;i<globalUniqueArray.length;i++){
            if(globalUniqueArray[i][2] == "USERNAME"){
                listnedAdditionalUserPrefs+= " AND userName:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "SERVICEPROVIDER"){
                listnedAdditionalUserPrefs+= " AND serviceProvider:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "ROLE"){
                listnedAdditionalUserPrefs+= " AND rolesCommaSeperated:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "IDENTITYPROVIDER"){
                listnedAdditionalUserPrefs+= " AND identityProvider:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "USERSTORE"){
                listnedAdditionalUserPrefs+= " AND userStoreDomain:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "REGION"){
                listnedAdditionalUserPrefs+= " AND region:\""+globalUniqueArray[i][1]+"\"";
            }
        }

        onDataChanged();
    });
};

function addUserPrefsToGlobalArray(topic,mode,userPref){

    var valExist = false;

    if(globalUniqueArray.length != 0){
        for(i=0;i<globalUniqueArray.length;i++){
            if(globalUniqueArray[i][2] == mode){
                valExist = true;
                globalUniqueArray[i][0] = topic;
                globalUniqueArray[i][1] = userPref;
                break;
            }
        }

        if(!valExist){
            var arry = [topic,userPref,mode];
            globalUniqueArray.push(arry);
        }
    }else{
        var arry = [topic,userPref,mode];
        globalUniqueArray.push(arry);
    }

    listnedAdditionalUserPrefs = "";

    for(i=0;i<globalUniqueArray.length;i++){
        if(globalUniqueArray[i][2] == "USERNAME"){
            listnedAdditionalUserPrefs+= " AND userName:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "SERVICEPROVIDER"){
            listnedAdditionalUserPrefs+= " AND serviceProvider:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "ROLE"){
            listnedAdditionalUserPrefs+= " AND rolesCommaSeperated:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "IDENTITYPROVIDER"){
            listnedAdditionalUserPrefs+= " AND identityProvider:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "USERSTORE"){
            listnedAdditionalUserPrefs+= " AND userStoreDomain:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "REGION"){
            listnedAdditionalUserPrefs+= " AND region:\""+globalUniqueArray[i][1]+"\"";
        }
    }

}

function onDataChanged() {

    oTable.clear().draw();
    oTable.ajax.reload().draw();
};

function onError(msg) {
    $("#canvas").html(gadgetUtil.getErrorText(msg));
};<commit_msg>fixing data table<commit_after>var timeFrom;
var timeTo;
var timeUnit = null;
var listnedTimeFromValue;
var listnedTimeToValue;
var oTable;
var page = gadgetUtil.getCurrentPage();
var globalUniqueArray = [];
var TOPIC_USERNAME = "subscriberUser";
var TOPIC_USERPREF_DELETION = "subscriberUserPrefDeletion";
var TOPIC = "subscriber";
var listnedAdditionalUserPrefs = "";

$(function() {

    var historyParmExist = gadgetUtil.getURLParam("persistTimeFrom");

    if(historyParmExist == null){
        listnedTimeFromValue = gadgetUtil.timeFrom();
        listnedTimeToValue = gadgetUtil.timeTo();
    }else{
        var historyParms = gadgetUtil.getURLParams();

        for (var key in historyParms) {
            if (historyParms.hasOwnProperty(key)) {

                if(key == "persistTimeFrom"){
                    listnedTimeFromValue = historyParms[key];
                }else if(key == "persistTimeTo"){
                    listnedTimeToValue = historyParms[key];
                }else if(Object.keys(historyParms).length > 2){
                    var historyParamVal = historyParms[key].toString();
                    addUserPrefsToGlobalArray("Topic",key,historyParamVal.split("_")[0]);
                }
            }
        }
    }

    if (page.name == TYPE_LANDING || page.name == TYPE_RESIDENT_IDP) {
        var idpFilter = "";
        var columns = [];

        if(page.name == TYPE_LANDING) {
            idpFilter = " AND identityProviderType:\"FEDERATED\"";
            columns = [
                { title: "Context ID" },
                { title: "User Name" },
                { title: "Service Provider" },
                { title: "Identity Provider" },
                { title: "Roles" },
                { title: "Ip" },
                { title: "Region" },
                { title: "Authentication Step Success" },
                { title: "Overall Success" },
                { title: "Timestamp" }
            ];

        } else if(page.name == TYPE_RESIDENT_IDP) {
            idpFilter = " AND identityProviderType:\"LOCAL\"";
            columns = [
                { title: "Context ID" },
                { title: "User Name" },
                { title: "Service Provider" },
                { title: "Userstore" },
                { title: "Roles" },
                { title: "Ip" },
                { title: "Region" },
                { title: "Authentication Step Success" },
                { title: "Overall Success" },
                { title: "Timestamp" }
            ];
        }

        oTable = $('#tblMessages').DataTable({
            scrollY: 500,
            scrollX: true,
            dom: '<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            "processing": true,
            "serverSide": true,
            "searching": false,
            "columns" : columns,
            "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                if ( aData[7] == true && aData[8] == true )
                {
                   $('td', nRow).eq(8).html('

Success

');
                }
                else if ( aData[7] == false && aData[8] == false)
                {
                    $('td', nRow).eq(8).html('

Failure

');
                }
                else {
                    $('td', nRow).eq(8).html('

');
                }
            },
            "ajax": {
                "url" : AUTHENTICATION_CONTEXT,
                "data" : function (d) {
                    d.type = page.type;
                    d.timeFrom = parseInt(listnedTimeFromValue);
                    d.timeTo = parseInt(listnedTimeToValue);
                    d.listnedAdditionalUserPrefs = listnedAdditionalUserPrefs;
                    d.idpType = idpFilter;
                }
            }
        });
    } else if(page.name == TYPE_SESSIONS) {
        oTable = $('#tblMessages').DataTable({
            scrollY: 600,
            scrollX: true,
            dom: '<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            "processing": true,
            "serverSide": true,
            "searching": false,
            "columns" : [
                { title: "Session ID" },
                { title: "Username" },
                { title: "Start Time" },
                { title: "Termination Time" },
                { title: "End Time" },
                { title: "Duration" },
                { title: "Is Active" },
                { title: "Userstore Domain" },
                { title: "IP" },
                { title: "Tenant Domain" },
                { title: "Remember Me Flag" },
                { title: "Timestamp" }

            ],
            "ajax": {
                "url" : SESSION_CONTEXT,
                "data" : function (d) {
                    d.type = page.type;
                    d.timeFrom = parseInt(listnedTimeFromValue);
                    d.timeTo = parseInt(listnedTimeToValue);
                }
            }
        });
    }

    $('#tblMessages tbody').on('click', 'tr', function() {
        var id = $(this).find("td:first").html();
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        } else {
            dataTable.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
        /*if( timeUnit == null) {
         timeUnit = qs.timeUnit;
         }*/
        // var targetUrl = MESSAGE_PAGE_URL + "?" + PARAM_ID + "=" + id + "&timeFrom=" + timeFrom + "&timeTo=" + timeTo + "&timeUnit=" + timeUnit;;
        var targetUrl = MESSAGE_PAGE_URL + "?" + PARAM_ID + "=" + id;
        parent.window.location = targetUrl;
    });

});

gadgets.HubSettings.onConnect = function() {

    gadgets.Hub.subscribe(TOPIC, function(topic, data, subscriberData) {
        listnedTimeFromValue = data.timeFrom;
        listnedTimeToValue = data.timeTo;
        onDataChanged();
    });

    gadgets.Hub.subscribe(TOPIC_USERNAME, function(topic, data, subscriberData) {

        addUserPrefsToGlobalArray(topic,data.mode,data.userPrefValue);
        onDataChanged();
    });

    gadgets.Hub.subscribe(TOPIC_USERPREF_DELETION, function(topic, data, subscriberData) {

        var index;
        for(i=0;i<globalUniqueArray.length;i++){
            if(globalUniqueArray[i][2] == data.category){
                index = i;
                break;
            }
        }
        globalUniqueArray.splice(index, 1);
        listnedAdditionalUserPrefs = "";

        for(i=0;i<globalUniqueArray.length;i++){
            if(globalUniqueArray[i][2] == "USERNAME"){
                listnedAdditionalUserPrefs+= " AND userName:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "SERVICEPROVIDER"){
                listnedAdditionalUserPrefs+= " AND serviceProvider:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "ROLE"){
                listnedAdditionalUserPrefs+= " AND rolesCommaSeperated:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "IDENTITYPROVIDER"){
                listnedAdditionalUserPrefs+= " AND identityProvider:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "USERSTORE"){
                listnedAdditionalUserPrefs+= " AND userStoreDomain:\""+globalUniqueArray[i][1]+"\"";
            }else if(globalUniqueArray[i][2] == "REGION"){
                listnedAdditionalUserPrefs+= " AND region:\""+globalUniqueArray[i][1]+"\"";
            }
        }

        onDataChanged();
    });
};

function addUserPrefsToGlobalArray(topic,mode,userPref){

    var valExist = false;

    if(globalUniqueArray.length != 0){
        for(i=0;i<globalUniqueArray.length;i++){
            if(globalUniqueArray[i][2] == mode){
                valExist = true;
                globalUniqueArray[i][0] = topic;
                globalUniqueArray[i][1] = userPref;
                break;
            }
        }

        if(!valExist){
            var arry = [topic,userPref,mode];
            globalUniqueArray.push(arry);
        }
    }else{
        var arry = [topic,userPref,mode];
        globalUniqueArray.push(arry);
    }

    listnedAdditionalUserPrefs = "";

    for(i=0;i<globalUniqueArray.length;i++){
        if(globalUniqueArray[i][2] == "USERNAME"){
            listnedAdditionalUserPrefs+= " AND userName:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "SERVICEPROVIDER"){
            listnedAdditionalUserPrefs+= " AND serviceProvider:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "ROLE"){
            listnedAdditionalUserPrefs+= " AND rolesCommaSeperated:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "IDENTITYPROVIDER"){
            listnedAdditionalUserPrefs+= " AND identityProvider:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "USERSTORE"){
            listnedAdditionalUserPrefs+= " AND userStoreDomain:\""+globalUniqueArray[i][1]+"\"";
        }else if(globalUniqueArray[i][2] == "REGION"){
            listnedAdditionalUserPrefs+= " AND region:\""+globalUniqueArray[i][1]+"\"";
        }
    }

}

function onDataChanged() {

    oTable.clear().draw();
    oTable.ajax.reload().draw();
};

function onError(msg) {
    $("#canvas").html(gadgetUtil.getErrorText(msg));
};<|endoftext|>


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

function initialize() {
  var locations = [
  ['San Diego', 32.65, -117.05, 4]];

   window.map = new google.maps.Map(document.getElementById('map'), {
     mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: {lat: 50, lng: -70},
          zoom: 12,
          styles: [
    {"featureType": "administrative",
    "elementType": "geometry.fill",
    "stylers": [{"color": "#7f2200"},
    {"visibility": "off"}]},
    {"featureType": "administrative",
    "elementType": "geometry.stroke",
    "stylers":
    [{"visibility": "on"},
    {"color": "#87ae79"}]},
    {"featureType": "administrative",
    "elementType": "labels.text.fill",
    "stylers": [{"color": "#495421"}]},
    {"featureType": "administrative",
    "elementType": "labels.text.stroke",
    "stylers": [{"color": "#ffffff"},
    {"visibility": "on"},
    {"weight": 4.1}]},
    {"featureType": "administrative.neighborhood",
    "elementType": "labels",
    "stylers": [{"visibility": "off"}]},
    {"featureType": "landscape",
    "elementType": "geometry.fill",
    "stylers": [
    {"color": "#abce83"}]},
    {"featureType": "poi",
    "elementType": "geometry.fill",
    "stylers": [{"color": "#769E72"}]},
    {"featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{"color": "#7B8758"}]},
    {"featureType": "poi",
    "elementType": "labels.text.stroke",
    "stylers": [{"color": "#EBF4A4"}]},
    {"featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{"visibility": "simplified"},
    {"color": "#8dab68"}]},{
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [{
    "visibility": "simplified"}]},
    {"featureType": "road",
    "elementType": "labels.text.fill",
    "stylers": [{"color": "#5B5B3F"}]},
    {"featureType": "road",
    "elementType": "labels.text.stroke",
    "stylers": [{"color": "#ABCE83"}]},
    {"featureType": "road",
    "elementType": "labels.icon",
    "stylers": [{"visibility": "off"}]},
    {"featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{"color": "#EBF4A4"}]},
    {"featureType": "road.highway",
    "elementType": "geometry.stroke",
    "stylers": [{"weight": "0.56"}]},
    {"featureType": "road.highway.controlled_access",
    "elementType": "geometry.stroke",
    "stylers": [{"weight": "0.50"}]},
    {"featureType": "road.arterial",
    "elementType": "geometry",
    "stylers": [{"color": "#d8d385"}]},
    {"featureType": "road.arterial",
    "elementType": "geometry.stroke",
    "stylers": [{"weight": "0.18"},
    {"lightness": "21"}]},
    {"featureType": "road.local",
    "elementType": "geometry",
    "stylers": [{"color": "#A4C67D"}]},
    {"featureType": "transit",
    "elementType": "all",
    "stylers": [{"visibility": "off"}]},
    {"featureType": "water",
    "elementType": "geometry",
    "stylers": [{"visibility": "on"},
    {"color": "#aee2e0"}]}]
    });

  var infowindow = new google.maps.InfoWindow();

  var bounds = new google.maps.LatLngBounds();

  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),
      map: map
    });

    bounds.extend(marker.position);

    google.maps.event.addListener(marker, 'click', (function (marker, i) {
      return function () {
        infowindow.setContent(locations[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }

  map.fitBounds(bounds);

  var listener = google.maps.event.addListener(map, "idle", function () {
    map.setZoom(7);
    google.maps.event.removeListener(listener);
  });
}

$(document).ready(function(){
  $.ajax({
    url: '/',
    method: "GET",
    dataType: "JSON"
    })
    .done(function(response){
      var tweetResponse = response;

        var icons = {
          parking: {
            icon: 'http://pngimg.com/upload/bear_PNG1191.png'
          }
        };

      function addMarker(lat, long) {
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, long),
            icon: icons['parking'].icon,
            map: map
          });
          return marker
        }

      //the tweet response is an array of arrays, each containing tweet object
      //the code below iterates through the tweet response array, and the contained sub arrays
      //for each tweet object it pulls the longitude and latitude depending on where theyre store
      //it then creates a map marker for each one
      console.log(tweetResponse)
      tweetResponse.forEach(function(element, elementIndex){
        element.forEach(function(element1, elementIndex1) {
            if(element1.place){
              var latitude = element1.place.bounding_box.coordinates[0][1][0];
              var longitude = element1.place.bounding_box.coordinates[0][1][1];
              addMarker(longitude,latitude);
            }
            if(element1.coordinates){
              var latitude = element1.coordinates.coordinates[0];
              var longitude = element1.coordinates.coordinates[1];
              addMarker(longitude,latitude);
            }
        });

    })

      })

  $(".menu-btn").click(function(event){
    event.preventDefault();
    $("nav").toggleClass("menushow");
  });
})

<commit_msg>Add side-bar event listeners to given map markers<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

function initialize() {
  locations = [
  ['San Diego', 32.65, -117.05, 4]];

  window.map = new google.maps.Map(document.getElementById('map'), {
   mapTypeId: google.maps.MapTypeId.ROADMAP,
   center: {lat: 50, lng: -70},
   zoom: 12,
   styles: [
   {"featureType": "administrative",
   "elementType": "geometry.fill",
   "stylers": [{"color": "#7f2200"},
   {"visibility": "off"}]},
   {"featureType": "administrative",
   "elementType": "geometry.stroke",
   "stylers":
   [{"visibility": "on"},
   {"color": "#87ae79"}]},
   {"featureType": "administrative",
   "elementType": "labels.text.fill",
   "stylers": [{"color": "#495421"}]},
   {"featureType": "administrative",
   "elementType": "labels.text.stroke",
   "stylers": [{"color": "#ffffff"},
   {"visibility": "on"},
   {"weight": 4.1}]},
   {"featureType": "administrative.neighborhood",
   "elementType": "labels",
   "stylers": [{"visibility": "off"}]},
   {"featureType": "landscape",
   "elementType": "geometry.fill",
   "stylers": [
   {"color": "#abce83"}]},
   {"featureType": "poi",
   "elementType": "geometry.fill",
   "stylers": [{"color": "#769E72"}]},
   {"featureType": "poi",
   "elementType": "labels.text.fill",
   "stylers": [{"color": "#7B8758"}]},
   {"featureType": "poi",
   "elementType": "labels.text.stroke",
   "stylers": [{"color": "#EBF4A4"}]},
   {"featureType": "poi.park",
   "elementType": "geometry",
   "stylers": [{"visibility": "simplified"},
   {"color": "#8dab68"}]},{
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [{
      "visibility": "simplified"}]},
      {"featureType": "road",
      "elementType": "labels.text.fill",
      "stylers": [{"color": "#5B5B3F"}]},
      {"featureType": "road",
      "elementType": "labels.text.stroke",
      "stylers": [{"color": "#ABCE83"}]},
      {"featureType": "road",
      "elementType": "labels.icon",
      "stylers": [{"visibility": "off"}]},
      {"featureType": "road.highway",
      "elementType": "geometry",
      "stylers": [{"color": "#EBF4A4"}]},
      {"featureType": "road.highway",
      "elementType": "geometry.stroke",
      "stylers": [{"weight": "0.56"}]},
      {"featureType": "road.highway.controlled_access",
      "elementType": "geometry.stroke",
      "stylers": [{"weight": "0.50"}]},
      {"featureType": "road.arterial",
      "elementType": "geometry",
      "stylers": [{"color": "#d8d385"}]},
      {"featureType": "road.arterial",
      "elementType": "geometry.stroke",
      "stylers": [{"weight": "0.18"},
      {"lightness": "21"}]},
      {"featureType": "road.local",
      "elementType": "geometry",
      "stylers": [{"color": "#A4C67D"}]},
      {"featureType": "transit",
      "elementType": "all",
      "stylers": [{"visibility": "off"}]},
      {"featureType": "water",
      "elementType": "geometry",
      "stylers": [{"visibility": "on"},
      {"color": "#aee2e0"}]}]
    });

  var infowindow = new google.maps.InfoWindow();

  var bounds = new google.maps.LatLngBounds();

  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),
      map: map
    });

    bounds.extend(marker.position);

    google.maps.event.addListener(marker, 'click', (function (marker, i) {
      return function () {
        infowindow.setContent(locations[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }

  map.fitBounds(bounds);

  var listener = google.maps.event.addListener(map, "idle", function () {
    map.setZoom(7);
    google.maps.event.removeListener(listener);
  });
}

$(document).ready(function(){
  $.ajax({
    url: '/',
    method: "GET",
    dataType: "JSON"
  })
  .done(function(response){
    var tweetResponse = response;
    var icons = {
      parking: {
        icon: 'http://pngimg.com/upload/bear_PNG1191.png'
      }
    };

    function addMarker(lat, long) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, long),
        // icon: icons['parking'].icon,
        map: map
      });
      locations.push(['Test', lat, long, 4])
      console.log(locations)
      return marker
    }

    $(".menu-btn").click(function(event){
      event.preventDefault();
      $(".nav1").toggleClass("menushow");
    });

    $(".menu-btn2").click(function(event){
      event.preventDefault();
      $(".nav2").removeClass("menushow2");
    });

    google.maps.event.addListener(marker, 'click', function () {
      $(".nav2").addClass("menushow2");
      $(".menu-btn2").addClass("button-slide");
      currentMarker = $(this)
      $('.place-coordinates').append(marker.getPosition().lat() + ' ' + marker.getPosition().lng());
   });

      //the tweet response is an array of arrays, each containing tweet object
      //the code below iterates through the tweet response array, and the contained sub arrays
      //for each tweet object it pulls the longitude and latitude depending on where theyre store
      //it then creates a map marker for each one
      tweetResponse.forEach(function(element, elementIndex){
        element.forEach(function(element1, elementIndex1) {
          if(element1.place){
            var latitude = element1.place.bounding_box.coordinates[0][1][0];
            var longitude = element1.place.bounding_box.coordinates[0][1][1];
            addMarker(longitude,latitude).addListener('click', function() {
              // console.log("you clicked on" + longitude + latitude) // testing for responsiveness.
              $(".nav2").addClass("menushow2"); // bringing out slider from the right (NOTE: this is repetitive).
              $(".menu-btn2").addClass("button-slide");
              $('.place-coordinates').text("lat: " + latitude + "\n long: " + longitude) // adding lat, long to sidebar.
            });
          }
          if(element1.coordinates){
            var latitude = element1.coordinates.coordinates[0];
            var longitude = element1.coordinates.coordinates[1];
            addMarker(longitude,latitude)
            .addListener('click', function() {
              $(".nav2").addClass("menushow2");
              $(".menu-btn2").addClass("button-slide");
              $('.place-coordinates').text("lat: " + latitude + "\n long: " + longitude)
            });
          }
        });
      })
    })

})

<|endoftext|>


<commit_before>'use strict'

const serverOpts = {
  port: process.env.PORT || 8888,
  ip: process.env.IP || '127.0.0.1',
  baseDir: process.env.AVATARS_BASEDIR || 'Images',
  debug: process.env.AVATARS_DEBUT || false,
  pageSize: Number.parseInt(process.env.AVATARS_PAGESIZE, 10) || 30
}

const express = require('express')
const app = express()

const avatars = require('./routes/avatars')(serverOpts)

const {sendFile} = require('./utils/image')

app.get(/^\/(favicon[.]ico)?$/, (req, res) => sendFile('favicon.ico', undefined, res)
  .catch((err) => {
    console.error(err)
    res.status(400).send('error')
  }))

app.use('/avatars', avatars)

const redirector = (req, res) => {
  let newPath = `/avatars/${req.params.chooser || 'random'}/`
  if (req.params.width) {
    newPath += `size-${req.params.width}/`
  }
  newPath += `${req.params.folder.replace(/:/g, '/')}.png`
  res.redirect(301, newPath)
}
app.get('/:folder/:chooser?/:width?.png', redirector)
app.get('/:folder/:chooser?/:width?', redirector)

app.use((err, req, res, next) => {
  if (serverOpts.debug) {
    console.log(err.stack)
    return next(err)
  }
  res.sendStatus(500)
  res.end()
})

app.listen(serverOpts.port)
<commit_msg>remove old app file<commit_after><|endoftext|>