<commit_before>/* ex: set tabstop=2 softtabstop=2 shiftwidth=2 : */

/*jshint unused:false, boss:true */
/*global setProperty:true, elementFitsDescription:true */

(function (root, name) {
  "use strict";
  // in case we decide to change those names later on
  var delegateSelector = "selector",
      delegateFunction = "handler";

  // shorthand or toggle individual state of delegateFunction
  function changeState(delegateArray, item, state) {
    var i, delegateItem;
    for (i = 0; delegateItem = delegateArray[i]; i++) {
      if (delegateItem[delegateSelector] === item) {
        delegateItem.disabled = Boolean(state);
        break;
      }
    }
  }

  function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement;
  }

  function execute(func, scope) {
    if (func) {
      func.call(scope);
    }
  }

  function setEnv(scope) {
    var _previousInstance = scope.constructor.__registered__[scope.getRootElementSelector()];
    var _self = (_previousInstance.scope)[_previousInstance.variable] || scope;
    _previousInstance = null;
    return _self;
  }

  function pushIntoDelegates(toArr, fromArr, startPos) {
    startPos = startPos || 0;
    if (fromArr.length === startPos + 1 && typeof fromArr[startPos] === "array") {
      [].push.apply(toArr, fromArr[startPos]);
    }
    else {
      for (var i = startPos, item; item = fromArr[i]; i++) {
        if (item.selector) {
          toArr.push(item);
        }
      }
    }
    return toArr;
  }

  function addEventListenerHelper(element, _event, _obj) {
    if (element.addEventListener) {
      element.addEventListener(_event, _self[_event], false);
    }
    else if (element.attachEvent) {
      element.attachEvent("on" + _event, _self[_event]);
    }
  }

  function removeEventListenerHelper(element, _event, _obj) {
    if (element.removeEventListener) {
      element.removeEventListener(_event, _self[_event]);
    }
    else if (element.detachEvent) {
      element.detachEvent("on" + _event, _self[_event]);
    }
  }

  /**
   * @name DelegateList
   * @function
   *
   * @description
   * constructor for delegates method object/array
   * create a object simular to array
   * better not subclassing JavaScript Array
   * https://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array
   *
   * @param arr ARRAY
   */
  function DelegateList(arr) {
    /*jshint validthis:true */
    this.disabled = false;
    this.delegates = arr || [];

    // allow overwrite
    setProperty(this, "__unlistened__", false, true);
  }

  /*
   * we do not use this.disable to modify the master disable switch
   * because user might accidentally calls this method without giving an argument
   * for that circumstance, we should do nothing
   * instead, we use disableAll to modify the master disable switch
   */
  DelegateList.prototype.disable = function (item) {
    if (item) {
      changeState(this.delegates, item, true);
    }
    return this;
  };

  DelegateList.prototype.enable = function (item) {
    if (item) {
      changeState(this.delegates, item, false);
    }
    return this;
  };

  DelegateList.prototype.disableAll = function () {
    this.disabled = true;
    return this;
  };

  DelegateList.prototype.enableAll = function () {
    this.disabled = false;
    return this;
  };

  /**
   * @name handleEvent
   * @function
   *
   * @description
   * actual function to attach events
   * we all know that we could bind object in addEventListener
   * http://w3.org/TR/DOM-Level-2-Events/events.html
   * provided there is a `handleEvent' property in the object
   * here is the trick, we COULD use a function to generate an object with
   * `handleEvent' nicely hidden inside its `prototype'
   *
   * @param evt
   */
  DelegateList.prototype.handleEvent = function (evt) {
    // master switch
    if (this.disabled || this.delegates.length === 0) {
      return;
    }

    var i, item, targetElement = getEventTarget(evt);

    for (i = 0; item = this.delegates[i]; i++) {
      if (item.disabled) {
        continue;
      }

      if (elementFitsDescription(targetElement, item[delegateSelector])) {
        execute(item[delegateFunction], targetElement);
      }
    } // end of for loop
  };

  /**
   * @name listen
   * @function
   *
   * @description
   *
   * @param arr
   */
  DelegateList.prototype.listen = function () {
    this.delegates = this.delegates || [];
    // better than [].concat because concat will create a new array
    this.delegates = pushIntoDelegates(this.delegates, arguments);

    if (this.__unlistened__ === true) {
      addEventListenerHelper(this.getRootElement(), this.__event__, this);
      this.__unlistened__ = false;
    }
  };

  DelegateList.prototype.unlisten = function () {
    removeEventListenerHelper(this.getRootElement(), this.__event__, this);
    this.__unlistened__ = true;
  };
  DelegateList.prototype.isUnlistened = function () {
    return this.__unlistened__ || false;
  };

  // constructor for event delegate Center
  function EventList(element, registeredVariable, scope) {
    var selectorString = null;
    if (!element || element === document) {
      element = document;
      selectorString = "document";
    }
    else {
      /* this is only mute jshint warning */
      /*global jQuery:true*/
      // if `element' is a jQuery object
      if ("jQuery" in window && element instanceof jQuery) {
        selectorString = element.selector;
        element = element[0];
        // jQuery.selector return "" for $(document), $(document.body)
        // so we have to do some extra check
        if (jQuery(document)[0] === element) {
          selectorString = "document";
        }
        else if (jQuery("body")[0] === element) {
          selectorString = "body";
        }
      }

      // if `element' is a string
      // we do not have to use getTypeOf
      // typeof seems to be enough
      else if (typeof element === "string") {
        if ("querySelector" in document) {
          selectorString = element;
          if (!(element = document.querySelector(selectorString))) {
            throw new TypeError("Unable to parse element: unexpected response from querySelector.");
          }
        }
      }
    }

    if (!element.addEventListener && !element.attachEvent) {
      throw new Error("Unable to find addEventListener and attachEvent on Element" + _event);
    }

    // record every instance's variable name (if possible)
    // By the hidden info, we could make each new EventList a singleton
    // if we re-instantiated EventList, it will return proper object
    this.constructor.__registered__ = this.constructor.__registered__ || {};

    var _previousInstance = this.constructor.__registered__[selectorString];
    // FIXME compare __root__ for better matching
    if (_previousInstance) {
      if ((_previousInstance.scope)[_previousInstance.variable]) {
        return (_previousInstance.scope)[_previousInstance.variable];
      }
      _previousInstance = null;
    }
    else if (registeredVariable) {
      // Object key must be string
      // or must have identical value when toString is called
      // http://www.hacksparrow.com/object-as-javascript-objects-key.html
      this.constructor.__registered__[selectorString] =
                                          { "variable"  : registeredVariable,
                                            "scope"     : scope || root
                                          };
    }

    setProperty(this, "__root__", element);

    if (selectorString) {
      setProperty(this, "__rootSelector__", selectorString);
    }
  }

  // focus and blur does NOT bubble up
  EventList.prototype.listen = function () {
    var _self = setEnv(this);

    if (!arguments.length) {
      return _self;
    }
    var _event = arguments[0];

    if (!Object.prototype.hasOwnProperty.call(document.body, "on" + _event)) {
      throw new TypeError(_event + " unavailable.");
    }

    var delegateArray = [];
    // skipping the first argument
    delegateArray = pushIntoDelegates([], arguments, 1);

    // singleton for every event
    if (!_self.hasOwnProperty(_event)) {
      _self[_event] = new DelegateList(delegateArray);
      // until we have a better solution, we'll have to contaminate all object
      // created by DelegateList
      setProperty(_self[_event], "__root__", _self.getRootElement());
      setProperty(_self[_event], "__event__", _event);

      addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);       }
    else {
      _self[_event].listen(delegateArray);

      if (_self[_event].isUnlistened) {
        //_self.getRootElement().addEventListener(_event, _self[_event]);
        addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
        _self.__unlistened__ = false;
      }
    }
    delegateArray = null;

    return _self;
  };

  // only add a flag not to listen and removeEventListener
  // does NOT remove the EventList item
  EventList.prototype.unlisten = function (_event) {
    var _self = setEnv(this);

    removeEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
    _self[_event].__unlistened__ = true;

    return _self;
  };

  // only safe way to remove EventList item
  EventList.prototype.remove = function (_event) {
    var _self = setEnv(this);

    _self.unlisten(_event);
    delete _self[_event];

    return _self;
  };

  EventList.prototype.disable = function (_event) {
    var _self = setEnv(this);

    if (this[_event]) {
      this[_event].disabled = true;
    }
    return _self;
  };

  // for lesser browser
  // always check for `__' prefix in for-in loop
  // TODO: do we need this iterator?
  EventList.prototype.loop = function (_callback) {
    var _self = setEnv(this);

    _callback = _callback || function (key) { console.log(key); };

    // for browser that support `propertyIsEnumberable'
    // we check if prototype
    var key, value;
    if ("propertyIsEnumerable" in _self) {
      for (key in _self) {
        if (_self.hasOwnProperty(key) && _self[key].constructor.name === "DelegateList") {
          _callback.call(_self, key, value);
        }
      }
    }
    else {
      for (key in _self) {
        if (key !== "prototype" && ~key.indexOf("__")) {
          _callback.call(_self, key, value);
        }
      }
    }
  };

  EventList.prototype.getRootElement = function () {
    // we do not use _self for safety reasons
    if (this.__root__) {
      return this.__root__;
    }
    else {
      throw new Error("Root element not found.");
    }
  };

  EventList.prototype.getRootElementSelector = function () {
    // we do not use _self for safety reasons
    if (this.__rootSelector__) {
      return this.__rootSelector__;
    }
    else {
      // cannot throw error
      return null;
    }
  };

  EventList.prototype.isUnlistened = function () {
    var _self = setEnv(this);

    return _self.__unlistened__ || false;
  };

  // Events.* has no way of knowing the `__root__'
  // we have to delay this prototype function declaration
  // to dismiss `EventList' not found error
  DelegateList.prototype.getRootElement = EventList.prototype.getRootElement;

  // in case we need multiple instances
  root[name] = EventList;
}(this, "EventList"));
// test
//var a = new EventList("body","a"); a.x=1; var b = new EventList("body");
<commit_msg>fixed bugs in addEventListenerHelper<commit_after>/* ex: set tabstop=2 softtabstop=2 shiftwidth=2 : */

/*jshint unused:false, boss:true */
/*global setProperty:true, elementFitsDescription:true */

(function (root, name) {
  "use strict";
  // in case we decide to change those names later on
  var delegateSelector = "selector",
      delegateFunction = "handler";

  // shorthand or toggle individual state of delegateFunction
  function changeState(delegateArray, item, state) {
    var i, delegateItem;
    for (i = 0; delegateItem = delegateArray[i]; i++) {
      if (delegateItem[delegateSelector] === item) {
        delegateItem.disabled = Boolean(state);
        break;
      }
    }
  }

  function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement;
  }

  function execute(func, scope) {
    if (func) {
      func.call(scope);
    }
  }

  function setEnv(scope) {
    var _previousInstance = scope.constructor.__registered__[scope.getRootElementSelector()];
    var _self = (_previousInstance.scope)[_previousInstance.variable] || scope;
    _previousInstance = null;
    return _self;
  }

  function pushIntoDelegates(toArr, fromArr, startPos) {
    startPos = startPos || 0;
    if (fromArr.length === startPos + 1 && typeof fromArr[startPos] === "array") {
      [].push.apply(toArr, fromArr[startPos]);
    }
    else {
      for (var i = startPos, item; item = fromArr[i]; i++) {
        if (item.selector) {
          toArr.push(item);
        }
      }
    }
    return toArr;
  }

  function addEventListenerHelper(element, _event, _obj) {
    if (element.addEventListener) {
      element.addEventListener(_event, _obj, false);
    }
    else if (element.attachEvent) {
      element.attachEvent("on" + _event, _obj);
    }
  }

  function removeEventListenerHelper(element, _event, _obj) {
    if (element.removeEventListener) {
      element.removeEventListener(_event, _obj);
    }
    else if (element.detachEvent) {
      element.detachEvent("on" + _event, _obj);
    }
  }

  /**
   * @name DelegateList
   * @function
   *
   * @description
   * constructor for delegates method object/array
   * create a object simular to array
   * better not subclassing JavaScript Array
   * https://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array
   *
   * @param arr ARRAY
   */
  function DelegateList(arr) {
    /*jshint validthis:true */
    this.disabled = false;
    this.delegates = arr || [];

    // allow overwrite
    setProperty(this, "__unlistened__", false, true);
  }

  /*
   * we do not use this.disable to modify the master disable switch
   * because user might accidentally calls this method without giving an argument
   * for that circumstance, we should do nothing
   * instead, we use disableAll to modify the master disable switch
   */
  DelegateList.prototype.disable = function (item) {
    if (item) {
      changeState(this.delegates, item, true);
    }
    return this;
  };

  DelegateList.prototype.enable = function (item) {
    if (item) {
      changeState(this.delegates, item, false);
    }
    return this;
  };

  DelegateList.prototype.disableAll = function () {
    this.disabled = true;
    return this;
  };

  DelegateList.prototype.enableAll = function () {
    this.disabled = false;
    return this;
  };

  /**
   * @name handleEvent
   * @function
   *
   * @description
   * actual function to attach events
   * we all know that we could bind object in addEventListener
   * http://w3.org/TR/DOM-Level-2-Events/events.html
   * provided there is a `handleEvent' property in the object
   * here is the trick, we COULD use a function to generate an object with
   * `handleEvent' nicely hidden inside its `prototype'
   *
   * @param evt
   */
  DelegateList.prototype.handleEvent = function (evt) {
    // master switch
    if (this.disabled || this.delegates.length === 0) {
      return;
    }

    var i, item, targetElement = getEventTarget(evt);

    for (i = 0; item = this.delegates[i]; i++) {
      if (item.disabled) {
        continue;
      }
      // FIXME: add documentation explaining why we use this instead of querySelector match
      if (elementFitsDescription(targetElement, item[delegateSelector])) {
        execute(item[delegateFunction], targetElement);
      }
    } // end of for loop
  };

  /**
   * @name listen
   * @function
   *
   * @description
   *
   * @param arr
   */
  DelegateList.prototype.listen = function () {
    this.delegates = this.delegates || [];
    // better than [].concat because concat will create a new array
    this.delegates = pushIntoDelegates(this.delegates, arguments);

    if (this.__unlistened__ === true) {
      addEventListenerHelper(this.getRootElement(), this.__event__, this);
      this.__unlistened__ = false;
    }
  };

  DelegateList.prototype.unlisten = function () {
    removeEventListenerHelper(this.getRootElement(), this.__event__, this);
    this.__unlistened__ = true;
  };
  DelegateList.prototype.isUnlistened = function () {
    return this.__unlistened__ || false;
  };

  // constructor for event delegate Center
  function EventList(element, registeredVariable, scope) {
    var selectorString = null;
    if (!element || element === document) {
      element = document;
      selectorString = "document";
    }
    else {
      /* this is only mute jshint warning */
      /*global jQuery:true*/
      // if `element' is a jQuery object
      if ("jQuery" in window && element instanceof jQuery) {
        selectorString = element.selector;
        element = element[0];
        // jQuery.selector return "" for $(document), $(document.body)
        // so we have to do some extra check
        if (jQuery(document)[0] === element) {
          selectorString = "document";
        }
        else if (jQuery("body")[0] === element) {
          selectorString = "body";
        }
      }

      // if `element' is a string
      // we do not have to use getTypeOf
      // typeof seems to be enough
      else if (typeof element === "string") {
        if ("querySelector" in document) {
          selectorString = element;
          if (!(element = document.querySelector(selectorString))) {
            throw new TypeError("Unable to parse element: unexpected response from querySelector.");
          }
        }
      }
    }

    if (!element.addEventListener && !element.attachEvent) {
      throw new Error("Unable to find addEventListener and attachEvent on element.");
    }

    // record every instance's variable name (if possible)
    // By the hidden info, we could make each new EventList a singleton
    // if we re-instantiated EventList, it will return proper object
    this.constructor.__registered__ = this.constructor.__registered__ || {};

    var _previousInstance = this.constructor.__registered__[selectorString];
    // FIXME compare __root__ for better matching
    if (_previousInstance) {
      if ((_previousInstance.scope)[_previousInstance.variable]) {
        return (_previousInstance.scope)[_previousInstance.variable];
      }
      _previousInstance = null;
    }
    else if (registeredVariable) {
      // Object key must be string
      // or must have identical value when toString is called
      // http://www.hacksparrow.com/object-as-javascript-objects-key.html
      this.constructor.__registered__[selectorString] =
                                          { "variable"  : registeredVariable,
                                            "scope"     : scope || root
                                          };
    }

    setProperty(this, "__root__", element);

    if (selectorString) {
      setProperty(this, "__rootSelector__", selectorString);
    }
  }

  // focus and blur does NOT bubble up
  EventList.prototype.listen = function () {
    var _self = setEnv(this);

    if (!arguments.length) {
      return _self;
    }
    var _event = arguments[0];

    if (!Object.prototype.hasOwnProperty.call(document.body, "on" + _event)) {
      throw new TypeError(_event + " unavailable.");
    }

    var delegateArray = [];
    // skipping the first argument
    delegateArray = pushIntoDelegates([], arguments, 1);

    // singleton for every event
    if (!_self.hasOwnProperty(_event)) {
      _self[_event] = new DelegateList(delegateArray);
      // until we have a better solution, we'll have to contaminate all object
      // created by DelegateList
      setProperty(_self[_event], "__root__", _self.getRootElement());
      setProperty(_self[_event], "__event__", _event);

      addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
    }
    else {
      _self[_event].listen(delegateArray);

      if (_self[_event].isUnlistened) {
        //_self.getRootElement().addEventListener(_event, _self[_event]);
        addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
        _self.__unlistened__ = false;
      }
    }
    delegateArray = null;

    return _self;
  };

  // only add a flag not to listen and removeEventListener
  // does NOT remove the EventList item
  EventList.prototype.unlisten = function (_event) {
    var _self = setEnv(this);

    removeEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
    _self[_event].__unlistened__ = true;

    return _self;
  };

  // only safe way to remove EventList item
  EventList.prototype.remove = function (_event) {
    var _self = setEnv(this);

    _self.unlisten(_event);
    delete _self[_event];

    return _self;
  };

  EventList.prototype.disable = function (_event) {
    var _self = setEnv(this);

    if (this[_event]) {
      this[_event].disabled = true;
    }
    return _self;
  };

  // for lesser browser
  // always check for `__' prefix in for-in loop
  // TODO: do we need this iterator?
  EventList.prototype.loop = function (_callback) {
    var _self = setEnv(this);

    _callback = _callback || function (key) { console.log(key); };

    // for browser that support `propertyIsEnumberable'
    // we check if prototype
    var key, value;
    if ("propertyIsEnumerable" in _self) {
      for (key in _self) {
        if (_self.hasOwnProperty(key) && _self[key].constructor.name === "DelegateList") {
          _callback.call(_self, key, value);
        }
      }
    }
    else {
      for (key in _self) {
        if (key !== "prototype" && ~key.indexOf("__")) {
          _callback.call(_self, key, value);
        }
      }
    }
  };

  EventList.prototype.getRootElement = function () {
    // we do not use _self for safety reasons
    if (this.__root__) {
      return this.__root__;
    }
    else {
      throw new Error("Root element not found.");
    }
  };

  EventList.prototype.getRootElementSelector = function () {
    // we do not use _self for safety reasons
    if (this.__rootSelector__) {
      return this.__rootSelector__;
    }
    else {
      // cannot throw error
      return null;
    }
  };

  EventList.prototype.isUnlistened = function () {
    var _self = setEnv(this);

    return _self.__unlistened__ || false;
  };

  // Events.* has no way of knowing the `__root__'
  // we have to delay this prototype function declaration
  // to dismiss `EventList' not found error
  DelegateList.prototype.getRootElement = EventList.prototype.getRootElement;

  // in case we need multiple instances
  root[name] = EventList;
}(this, "EventList"));
// test
//var a = new EventList("body","a"); a.x=1; var b = new EventList("body");
<|endoftext|>


<commit_before>// This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
require('../../js/transition.js')
require('../../js/alert.js')
require('../../js/button.js')
require('../../js/carousel.js')
require('../../js/collapse.js')
require('../../js/dropdown.js')
require('../../js/modal.js')
require('../../js/tooltip.js')
require('../../js/popover.js')
require('../../js/scrollspy.js')
require('../../js/tab.js')
require('../../js/affix.js')<commit_msg>remove useless file<commit_after><|endoftext|>


<commit_before>#!/usr/bin/node
/**
 * Required modules
 */
var fs = require('fs'),
    cli = require('cli'),
    Promise = require('bluebird'),
    AWS = require('aws-sdk'),
    bind = require('dns-zonefile'),
    region;

/** Parse CLI commands */
cli.parse({
  log: ['v', 'Enable verbose logging'],
  awsKey: ['k', 'AWS access key (IAM user must have policy access to Route 53)', 'string'],
  awsSecret: ['s', 'AWS access secret (IAM user must have policy access to Route 53)', 'string'],
  awsRegion: ['r', 'AWS region', 'string', 'us-west-1'],
  input: ['i', 'Folder that holds all of the "*.db" files', 'path', '/var/named/']
});

/** Main process */
cli.main(function(args, options) {
  /** Overwrite console.log with a fake function when debug is false */
  if(!options.log) {
    console.log = function log() { return false; };
  }
  console.log('Input options', options);

  var _self = this;

  if(options.awsKey === null || options.awsSecret === null || options.awsRegion === null) {
    _self.fatal('Please supply awsKey, awsSecret and awsRegion (IAM user must have policy access to Route 53)');
  }

  /** AWS config setup */
  region = options.awsRegion;
  AWS.config.update({accessKeyId: options.awsKey, secretAccessKey: options.awsSecret, region: region});

  /** Check if path ends on "/" */
  if(options.input.substr(options.input - 1) != '/') {
    options.input += '/';
  }

  /** Loop through path to find domains */
  var domains = [];

  Promise.promisify(fs.readdir)(options.input).then(function(list) {
    return Promise.resolve(list).each(function(file) {
      if(file.substr(file.length - 3) == '.db')
        return domains.push(file);

      console.log('Skipping file', file);
    });
  }).catch(function(err) {
    console.log(err);
    _self.fatal('Reading input directory failed');
    process.exit();
  }).then(function() {
    var total = domains.length, i = 0;
    return Promise.resolve(domains).each(function(domain) {
      console.log(domain);
      return Promise.promisify(processDomain)(options.input, domain).then(function(result) {
        if(result === true)
          cli.progress(++i / total);
      }).catch(function(err) {
        _self.fatal(err.message);
        process.exit();
      });
    }).then(function() {
      return cli.ok('Finished!');
    });
  }).finally(function() {
    /** Kill the node */
    process.exit();
  });
});

var processDomain = function processDomain(path, file, fn) {
  var domain = file.substr(0, (file.length - 3)),
      zone = fs.readFileSync(path + file, 'utf8');

  var params = {
    CallerReference: 'NS_Migration_01', /* required */
    Name: domain, /* required */
    HostedZoneConfig: {
      Comment: 'Migrated'
    }
  };

  new AWS.Route53().createHostedZone(params, function(err, data) {
    if(err) {
      if(err.code == 'HostedZoneAlreadyExists') {
        console.log('This domain already exists in Route53');
        return fn(null, true);
      }
      console.log(err);
      return fn({'message': 'Check your AWS IAM user'}, false);
    }

    if(!('HostedZone' in data) || !('Id' in data.HostedZone))
      return fn({'message': 'Required data not returned by AWS, please contact the publisher of this utility'}, false);

    var zoneId = data.HostedZone.Id;
    parseBind(domain, bind.parse(zone), function(changes) {
      if(changes === false) {
        return fn({'message': 'The bind file could not be parsed: ' + domain}, false);
      }

      var params = {
        HostedZoneId: zoneId,
        ChangeBatch: {
          Changes: changes
        }
      };

      new AWS.Route53().changeResourceRecordSets(params, function(err, data) {
        if(err) {
          console.log(err);
          return fn({'message': 'Something went wrong while setting DNS records'}, false);
        }
        return fn(null, true);
      });
    });
  });
};

var parseBind = function parseBind(domain, bind, cb) {
  if(typeof bind !== 'object')
    return cb(false);

  var changes = [],
      setTempl = {
    'Action': 'CREATE',
    'ResourceRecordSet': {
      'Name': '',
      'Type': '',
      'TTL': '',
      'ResourceRecords': []
    }
  };

  var records = {
    'a': {},
    'aaaa': {},
    'srv': {},
    'ptr': {},
    'txt': {},
    'mx': {}
  }, obj;
  Promise.resolve(Object.keys(bind)).each(function(type) {
    switch(type) {
      case 'a':
      case 'aaaa':
      case 'srv':
      case 'ptr':
        Promise.resolve(bind[(type)]).each(function(value) {
          if(value.name.indexOf(domain) < 0)
            value.name += '.' + domain;
          if(value.name.substr(-1) != '.')
            value.name += '.';

          if(value.ip.indexOf('all') < 0) {
            if(value.name in records[(type)]) {
              records[(type)][(value.name)].ips.push(value.ip);
            }
            else {
              obj = {
                name: value.name,
                ttl: value.ttl,
                ips: [
                  value.ip
                ]
              };
              records[(type)][(value.name)] = obj;
            }
          }
        });
      break;
      case 'txt':
        Promise.resolve(bind[(type)]).each(function(value) {
          if(value.name.indexOf(domain) < 0)
            value.name += '.' + domain;
          if(value.name.substr(-1) != '.')
            value.name += '.';

          if(value.name in records[(type)]) {
            records[(type)][(value.name)].txts.push(value.txt);
          }
          else {
            obj = {
              name: value.name,
              ttl: value.ttl,
              txts: [
                value.txt
              ]
            };
            records[(type)][(value.name)] = obj;
          }
        });
      break;
      case 'mx':
        Promise.resolve(bind[(type)]).each(function(value) {
          if(value.name.indexOf(domain) < 0)
            value.name += '.' + domain;
          if(value.name.substr(-1) != '.')
            value.name += '.';

          if(value.name in records[(type)]) {
            records[(type)][(value.name)].mxs.push(value.preference + ' ' + value.host);
          }
          else {
            obj = {
              name: value.name,
              ttl: value.ttl,
              mxs: [
                value.preference + ' ' + value.host
              ]
            };
            records[(type)][(value.name)] = obj;
          }
        });
      break;
    }
  });

  Promise.resolve(Object.keys(records)).each(function(type) {
    switch(type) {
      case 'a':
      case 'aaaa':
      case 'srv':
      case 'ptr':
        Promise.resolve(Object.keys(records[(type)])).each(function(value) {
          value = records[(type)][(value)];

          var set = JSON.parse(JSON.stringify(setTempl));
          set['ResourceRecordSet']['Name'] = value.name;
          set['ResourceRecordSet']['Type'] = type.toUpperCase();
          set['ResourceRecordSet']['TTL']  = value.ttl;

          value.ips.forEach(function(ip) {
            set['ResourceRecordSet']['ResourceRecords'].push({
              'Value': ip
            });
          });

          changes.push(set);
        });
      break;
      case 'txt':
        Promise.resolve(Object.keys(records[(type)])).each(function(value) {
          value = records[(type)][(value)];

          var set = JSON.parse(JSON.stringify(setTempl));
          set['ResourceRecordSet']['Name'] = value.name;
          set['ResourceRecordSet']['Type'] = type.toUpperCase();
          set['ResourceRecordSet']['TTL']  = value.ttl;

          value.txts.forEach(function(txt) {
            set['ResourceRecordSet']['ResourceRecords'].push({
              'Value':  '"' + txt + '"'
            });
          });

          changes.push(set);
        });
      break;
      case 'mx':
        Promise.resolve(Object.keys(records[(type)])).each(function(value) {
          value = records[(type)][(value)];

          var set = JSON.parse(JSON.stringify(setTempl));
          set['ResourceRecordSet']['Name'] = value.name;
          set['ResourceRecordSet']['Type'] = type.toUpperCase();
          set['ResourceRecordSet']['TTL']  = value.ttl;

          value.mxs.forEach(function(mx) {
            set['ResourceRecordSet']['ResourceRecords'].push({
              'Value': mx
            });
          });

          changes.push(set);
        });
      break;
    }
  }).finally(function() {
    return cb(changes);
  });
};<commit_msg>Async fixes<commit_after>#!/usr/bin/node
/**
 * Required modules
 */
var fs = require('fs'),
    cli = require('cli'),
    Promise = require('bluebird'),
    AWS = require('aws-sdk'),
    bind = require('dns-zonefile'),
    region;

/** Parse CLI commands */
cli.parse({
  log: ['v', 'Enable verbose logging'],
  awsKey: ['k', 'AWS access key (IAM user must have policy access to Route 53)', 'string'],
  awsSecret: ['s', 'AWS access secret (IAM user must have policy access to Route 53)', 'string'],
  awsRegion: ['r', 'AWS region', 'string', 'us-west-1'],
  input: ['i', 'Folder that holds all of the "*.db" files', 'path', '/var/named/']
});

/** Main process */
cli.main(function(args, options) {
  /** Overwrite console.log with a fake function when debug is false */
  if(!options.log) {
    console.log = function log() { return false; };
  }
  console.log('Input options', options);

  var _self = this;

  if(options.awsKey === null || options.awsSecret === null || options.awsRegion === null) {
    _self.fatal('Please supply awsKey, awsSecret and awsRegion (IAM user must have policy access to Route 53)');
  }

  /** AWS config setup */
  region = options.awsRegion;
  AWS.config.update({accessKeyId: options.awsKey, secretAccessKey: options.awsSecret, region: region});

  /** Check if path ends on "/" */
  if(options.input.substr(options.input - 1) != '/') {
    options.input += '/';
  }

  /** Loop through path to find domains */
  var domains = [];

  Promise.promisify(fs.readdir)(options.input).then(function(list) {
    return Promise.resolve(list).each(function(file) {
      if(file.substr(file.length - 3) == '.db')
        return domains.push(file);

      console.log('Skipping file', file);
    });
  }).catch(function(err) {
    console.log(err);
    _self.fatal('Reading input directory failed');
    process.exit();
  }).then(function() {
    var total = domains.length, i = 0;
    return Promise.resolve(domains).each(function(domain) {
      console.log(domain);
      return Promise.promisify(processDomain)(options.input, domain).then(function(result) {
        if(result === true)
          cli.progress(++i / total);
      }).catch(function(err) {
        _self.fatal(err.message);
        process.exit();
      });
    }).then(function() {
      return cli.ok('Finished!');
    });
  }).finally(function() {
    /** Kill the node */
    process.exit();
  });
});

var processDomain = function processDomain(path, file, fn) {
  var domain = file.substr(0, (file.length - 3)),
      zone = fs.readFileSync(path + file, 'utf8');

  var params = {
    CallerReference: 'NS_Migration_01', /* required */
    Name: domain, /* required */
    HostedZoneConfig: {
      Comment: 'Migrated'
    }
  };

  new AWS.Route53().createHostedZone(params, function(err, data) {
    if(err) {
      if(err.code == 'HostedZoneAlreadyExists') {
        console.log('This domain already exists in Route53');
        return fn(null, true);
      }
      console.log(err);
      return fn({'message': 'Check your AWS IAM user'}, false);
    }

    if(!('HostedZone' in data) || !('Id' in data.HostedZone))
      return fn({'message': 'Required data not returned by AWS, please contact the publisher of this utility'}, false);

    var zoneId = data.HostedZone.Id;
    parseBind(domain, bind.parse(zone), function(changes) {
      if(changes === false) {
        return fn({'message': 'The bind file could not be parsed: ' + domain}, false);
      }

      var params = {
        HostedZoneId: zoneId,
        ChangeBatch: {
          Changes: changes
        }
      };

      new AWS.Route53().changeResourceRecordSets(params, function(err, data) {
        if(err) {
          console.log(err);
          return fn({'message': 'Something went wrong while setting DNS records'}, false);
        }
        return fn(null, true);
      });
    });
  });
};

var parseBind = function parseBind(domain, bind, cb) {
  if(typeof bind !== 'object')
    return cb(false);

  var changes = [],
      setTempl = {
    'Action': 'CREATE',
    'ResourceRecordSet': {
      'Name': '',
      'Type': '',
      'TTL': '',
      'ResourceRecords': []
    }
  };

  var records = {
    'a': {},
    'aaaa': {},
    'srv': {},
    'ptr': {},
    'txt': {},
    'mx': {}
  }, obj;

  return Promise.resolve(Object.keys(bind)).each(function(type) {
    switch(type) {
      case 'a':
      case 'aaaa':
      case 'srv':
      case 'ptr':
        Promise.resolve(bind[(type)]).each(function(value) {
          if(value.name.indexOf(domain) < 0)
            value.name += '.' + domain;
          if(value.name.substr(-1) != '.')
            value.name += '.';

          if(value.ip.indexOf('all') < 0) {
            if(value.name in records[(type)]) {
              records[(type)][(value.name)].ips.push(value.ip);
            }
            else {
              obj = {
                name: value.name,
                ttl: value.ttl,
                ips: [
                  value.ip
                ]
              };
              records[(type)][(value.name)] = obj;
            }
          }
        });
      break;
      case 'txt':
        Promise.resolve(bind[(type)]).each(function(value) {
          if(value.name.indexOf(domain) < 0)
            value.name += '.' + domain;
          if(value.name.substr(-1) != '.')
            value.name += '.';

          if(value.name in records[(type)]) {
            records[(type)][(value.name)].txts.push(value.txt);
          }
          else {
            obj = {
              name: value.name,
              ttl: value.ttl,
              txts: [
                value.txt
              ]
            };
            records[(type)][(value.name)] = obj;
          }
        });
      break;
      case 'mx':
        Promise.resolve(bind[(type)]).each(function(value) {
          if(value.name.indexOf(domain) < 0)
            value.name += '.' + domain;
          if(value.name.substr(-1) != '.')
            value.name += '.';

          if(value.name in records[(type)]) {
            records[(type)][(value.name)].mxs.push(value.preference + ' ' + value.host);
          }
          else {
            obj = {
              name: value.name,
              ttl: value.ttl,
              mxs: [
                value.preference + ' ' + value.host
              ]
            };
            records[(type)][(value.name)] = obj;
          }
        });
      break;
    }
  }).then(function() {
    return Promise.resolve(Object.keys(records)).each(function(type) {
      switch(type) {
        case 'a':
        case 'aaaa':
        case 'srv':
        case 'ptr':
          return Promise.resolve(Object.keys(records[(type)])).each(function(value) {
            value = records[(type)][(value)];

            var set = JSON.parse(JSON.stringify(setTempl));
            set['ResourceRecordSet']['Name'] = value.name;
            set['ResourceRecordSet']['Type'] = type.toUpperCase();
            set['ResourceRecordSet']['TTL']  = value.ttl;

            value.ips.forEach(function(ip) {
              set['ResourceRecordSet']['ResourceRecords'].push({
                'Value': ip
              });
            });

            changes.push(set);
          });
        case 'txt':
          return Promise.resolve(Object.keys(records[(type)])).each(function(value) {
            value = records[(type)][(value)];

            var set = JSON.parse(JSON.stringify(setTempl));
            set['ResourceRecordSet']['Name'] = value.name;
            set['ResourceRecordSet']['Type'] = type.toUpperCase();
            set['ResourceRecordSet']['TTL']  = value.ttl;

            value.txts.forEach(function(txt) {
              set['ResourceRecordSet']['ResourceRecords'].push({
                'Value':  '"' + txt + '"'
              });
            });

            changes.push(set);
          });
        case 'mx':
          return Promise.resolve(Object.keys(records[(type)])).each(function(value) {
            value = records[(type)][(value)];

            var set = JSON.parse(JSON.stringify(setTempl));
            set['ResourceRecordSet']['Name'] = value.name;
            set['ResourceRecordSet']['Type'] = type.toUpperCase();
            set['ResourceRecordSet']['TTL']  = value.ttl;

            value.mxs.forEach(function(mx) {
              set['ResourceRecordSet']['ResourceRecords'].push({
                'Value': mx
              });
            });

            changes.push(set);
          });
      }
    });
  }).finally(function() {
    return cb(changes);
  });
};<|endoftext|>


<commit_before>/*global $ */

$(document).ready(function () {
    "use strict";

	// page js
	// -------------------------------------------------------------------------------------
	var page         = $('#page'),
		alphabet     = '`1234567890-=qwertyuiop[]\\asdfghjkl;\'zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?',
		verbInterval = 0,
		charInterval = 0,
        bringOut     = 0;

	function renderTemplate(name, titleText) {
		if (titleText) {
			$('title').html(titleText);
		} else {
			$('title').text(name);
		}
		page.html($('#' + name + '-template').html());
		$(page.children()[0]).attr('id', name);
	}

    function renderHome() {

        renderTemplate('home', 'tim(othy)');

        var verb           = $('#verb'),
            verbs          = ['read', 'code', 'write', 'walk', 'ponder', 'hike', 'garden'],
            verbIndx       = 0,
            maxVerbLen     = 0,
            verbText       = '',
            r              = '',
            i              = 0,
            charPeriod     = 40,
            verbPeriod     = 2500,
            randCharNum    = 5,
            randChar       = 0,
            charIndx       = 0;
        verbs.forEach(function (item) {
            maxVerbLen = Math.max(maxVerbLen, item.length);
        });

        // timing intervals
        verbInterval = setInterval(function () {

            //verbText = new Array(maxVerbLen + 1).join('_');
            verbText = "";
            for (i = 0; i < maxVerbLen + 1; i += 1) {
                verbText += "_";
            }

            charInterval = setInterval(function () {
                if (charIndx < verbs[verbIndx].length) {
                    if (randChar < randCharNum) {
                        r        = Math.floor(alphabet.length * Math.random());
                        verbText = verbText.substr(0, charIndx) + alphabet[r] + verbText.substr(charIndx + 1);
                        randChar += 1;
                    } else {
                        verbText = verbText.substr(0, charIndx) + verbs[verbIndx][charIndx] + verbText.substr(charIndx + 1);
                        charIndx += 1;
                        randChar = 0;
                    }
                    verb.text(verbText);
                } else {
                    verbText = verbs[verbIndx] + verbText.substr(verbs[verbIndx].length);
                    verbIndx = (verbIndx + 1) % verbs.length;
                    randChar  = 0;
                    charIndx  = 0;
                    verb.text(verbText);
                    clearInterval(charInterval);
                }
            }, charPeriod);
        }, verbPeriod);
    }

	// route hashchanges to page
	function router() {

		// clear last page stuff
		clearInterval(charInterval);
		clearInterval(verbInterval);

		// cache page & url
		page = page || $('#page');

		// off-page hash

        $('#page section').addClass('bringOut');

        bringOut = setTimeout(function () {
            page.removeClass('rendered');
            page.addClass('routing');

            renderHome();

            // setup
            page.addClass('rendered');

            $('html,body').animate({
                scrollTop: 0
            }, 512);

            clearInterval(bringOut);
        }, 500);
	}

	// listen for hash change or page load
	$(window).on('hashchange', router);
	$(window).on('load', router);

});<commit_msg>update timing<commit_after>/*global $ */

$(document).ready(function () {
    "use strict";

	// page js
	// -------------------------------------------------------------------------------------
	var page         = $('#page'),
		alphabet     = '`1234567890-=qwertyuiop[]\\asdfghjkl;\'zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?',
		verbInterval = 0,
		charInterval = 0,
        bringOut     = 0;

	function renderTemplate(name, titleText) {
		if (titleText) {
			$('title').html(titleText);
		} else {
			$('title').text(name);
		}
		page.html($('#' + name + '-template').html());
		$(page.children()[0]).attr('id', name);
	}

    function renderHome() {

        renderTemplate('home', 'tim(othy)');

        var verb           = $('#verb'),
            verbs          = ['read', 'code', 'write', 'walk', 'ponder', 'hike', 'garden'],
            verbIndx       = 0,
            maxVerbLen     = 0,
            blankText      = '',
            verbText       = '',
            r              = '',
            i              = 0,
            charPeriod     = 35,
            verbPeriod     = 3200,
            randCharNum    = 6,
            randChar       = 0,
            charIndx       = 0;
        verbs.forEach(function (item) {
            maxVerbLen = Math.max(maxVerbLen, item.length);
        });

        //verbText = new Array(maxVerbLen + 1).join('_');
        for (i = 0; i < maxVerbLen; i += 1) {
            blankText += '_';
        }

        // timing intervals
        verbInterval = setInterval(function () {

            verbText = blankText;
            charInterval = setInterval(function () {
                if (charIndx < verbs[verbIndx].length) {
                    if (randChar < randCharNum) {
                        r        = Math.floor(alphabet.length * Math.random());
                        verbText = verbText.substr(0, charIndx) + alphabet[r] + verbText.substr(charIndx + 1);
                        randChar += 1;
                    } else {
                        verbText = verbText.substr(0, charIndx) + verbs[verbIndx][charIndx] + verbText.substr(charIndx + 1);
                        charIndx += 1;
                        randChar = 0;
                    }
                    verb.text(verbText);
                } else {
                    verbText = verbs[verbIndx] + verbText.substr(verbs[verbIndx].length);
                    verbIndx = (verbIndx + 1) % verbs.length;
                    randChar  = 0;
                    charIndx  = 0;
                    verb.text(verbText);
                    clearInterval(charInterval);
                }
            }, charPeriod);
        }, verbPeriod);
    }

	// route hashchanges to page
	function router() {

		// clear last page stuff
		clearInterval(charInterval);
		clearInterval(verbInterval);

		// cache page & url
		page = page || $('#page');

		// off-page hash

        $('#page section').addClass('bringOut');

        bringOut = setTimeout(function () {
            page.removeClass('rendered');
            page.addClass('routing');

            renderHome();

            // setup
            page.addClass('rendered');

            $('html,body').animate({
                scrollTop: 0
            }, 512);

            clearInterval(bringOut);
        }, 500);
	}

	// listen for hash change or page load
	$(window).on('hashchange', router);
	$(window).on('load', router);

});<|endoftext|>


<commit_before>
$("#speechButton").click( function() { startListening(); } );

$( "#searchInput" ).keydown(function() {
  	var e = window.event;
	if(e.keyCode == 13){
		alert('5');
	}
});

function startListening(event) {

	if (!('webkitSpeechRecognition' in window)) {
	  alert("Your browser does not support Speach Recognition.  Please try using Google Chrome 25 or later.")
	} else {

		var final_transcript = '';

		var recognition = new webkitSpeechRecognition();
		recognition.lang = 'en-US';
		recognition.start();
		recognition.continuous = false;
		recognition.interimResults = true;
		//recognition.grammars = speechRecognitionList;
		//var speechRecognitionList = new SpeechGrammarList();
		//var grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;'
		//speechRecognitionList.addFromString(grammar, 1);

		recognition.onstart = function() {
			var text = $("#speechOutput").text();
			if (!text.includes("What would you like to do?")) {
				addToSpeechLog("What would you like to do?");
			}
		}

		recognition.onresult = function(event) {
			//Want to make sure the system has some confidence in the result before we take action
			if (event.results[0][0].confidence >= .6) {
				var interim_transcript = '';
				for (var i = event.resultIndex; i < event.results.length; ++i) {
					if (event.results[i].isFinal) {
						final_transcript += event.results[i][0].transcript;
					}else {
						interim_transcript += event.results[i][0].transcript;
					}
				}

				if(final_transcript.toLowerCase().includes("buy") || final_transcript.toLowerCase().includes("purchase")){
					addToSpeechLog("You said " + final_transcript);
					sleep(100);
				} else if (final_transcript.includes("finished") || final_transcript.includes("stop") || final_transcript.includes("cancel")){
					recognition.stop();
				} else {
					addToSpeechLog("Sorry, that is not a command I know, I heard: " + final_transcript);
					addToSpeechLog("Try saying something like but tickets.");
					sleep(200);
				}
			}
		}

		recognition.onerror = function(event) {
			addToSpeechLog("Error");
		}

		recognition.onend = function() {
			if (final_transcript.includes("finished") || final_transcript.includes("stop") || final_transcript.includes("cancel")) {
				addToSpeechLog("Stopping speech recognition.");
				recognition.stop();
			} else {
				sleep(100);
				recognition.start();
				final_transcript = '';
			}
		}
	}
}

function addToSpeechLog(message) {
	var text = $("#speechOutput").html();
	$("#speechOutput").html(text + "
" + message);
}

function sleep(milliseconds) {
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++) {
		if ((new Date().getTime() - start) > milliseconds){
			break;
		}
	}
}
<commit_msg>Improved voice controls<commit_after>
$("#speechButton").click( function() { startListening(); } );

$( "#searchInput" ).keydown(function() {
  	var e = window.event;
	if(e.keyCode == 13){
		addToSpeechLog($("#searchInput")[0].value, "Let me see if we have that movie.", false);
	}
});

function startListening(event) {

	if (!('webkitSpeechRecognition' in window)) {
	  alert("Your browser does not support Speach Recognition.  Please try using Google Chrome 25 or later.")
	} else {

		var final_transcript = '';

		var recognition = new webkitSpeechRecognition();
		recognition.lang = 'en-US';
		recognition.start();
		recognition.continuous = false;
		recognition.interimResults = true;
		//recognition.grammars = speechRecognitionList;
		//var speechRecognitionList = new SpeechGrammarList();
		//var grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;'
		//speechRecognitionList.addFromString(grammar, 1);

		recognition.onstart = function() {
			// var text = $("#speechOutput").text();
			// if (!text.includes("What would you like to do?")) {
			// 	addToSpeechLog("", "What would you like to do?");
			// }
		}

		recognition.onresult = function(event) {
			//Want to make sure the system has some confidence in the result before we take action
			if (event.results[0][0].confidence >= .6) {
				var interim_transcript = '';
				for (var i = event.resultIndex; i < event.results.length; ++i) {
					if (event.results[i].isFinal) {
						final_transcript += event.results[i][0].transcript;
					}else {
						interim_transcript += event.results[i][0].transcript;
					}
				}

				if(final_transcript.toLowerCase().includes("buy") || final_transcript.toLowerCase().includes("purchase")){
					//We should do something to allow the user to buy tickets here
					addToSpeechLog(final_transcript, "Awesome, lets get you some tickets", true);
					sleep(100);
				} else if (final_transcript.includes("finished") || final_transcript.includes("stop") || final_transcript.includes("cancel")){
					//Speech recognition is done at this point
					recognition.stop();
				} else if (final_transcript.includes("help")){
					//We should give the user a list of good commands they can use here
				} else {
					//The user said a command we did not plan for
					addToSpeechLog(final_transcript, "Sorry, that is not a command I know", true);
					sleep(200);
				}
			}
		}

		recognition.onerror = function(event) {
			//An error has occured
			addToSpeechLog("Error");
		}

		recognition.onend = function() {
			if (final_transcript.includes("finished") || final_transcript.includes("stop") || final_transcript.includes("cancel")) {
				addToSpeechLog(final_transcript, "Stopping audio recognition", true);
				recognition.stop();
			} else {
				sleep(100);
				recognition.start();
				final_transcript = '';
			}
		}
	}
}

function addToSpeechLog(userMessage, computerMessage, isSpeech) {
	var element = $("#speechOutput");
	if (isSpeech){
		element.html("You said: " + userMessage);
	} else {
		element.html("You searched for: " + userMessage);
	}

	element.html(element.html() + "
" + computerMessage);
}

function sleep(milliseconds) {
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++) {
		if ((new Date().getTime() - start) > milliseconds){
			break;
		}
	}
}
<|endoftext|>


<commit_before>var jslide = (function() {
  function buildSpotLight(r) {
    var canvas, c, grad, im,
        shown = false,
        x, y;

    // build canvas
    canvas = $('<canvas/>').addClass('jslideSpotlight');
    $('body').append(canvas);

    // initial position
    x = 0;
    y = 0;

    // draw and cache spotlight
    c = canvas[0].getContext('2d');
    recache(r);

    // bind the 'dry' mousemove handler (only update coordinates, no redrawing)
    $(document).bind( 'mousemove', mouseMoveHandlerDry );

    // methods
    function recache(newr) {
      r = newr;
      // resize temporarily
      canvas[0].width = 2*r;
      canvas[0].height = 2*r;
      // radial gradient
      grad = c.createRadialGradient(r,r,r*0.75,r,r,r);
      grad.addColorStop(0, 'rgba(0,0,0,0)');
      grad.addColorStop(1, 'rgba(0,0,0,0.5)');
      // draw shapes
      c.fillStyle = grad;
      c.fillRect(0,0,2*r,2*r);
      im = c.getImageData( 0, 0, 2*r, 2*r );

      // scale back and redraw
      scale();
    }
    function scale() {
      var w = $(window).width(),
          h = $(window).height();
      canvas[0].width = w;
      canvas[0].height = h;
      draw();
    }
    function draw() {
      c.fillStyle = 'rgba(0,0,0,0.5)';
      c.clearRect(0,0,canvas[0].width,canvas[0].height);
      c.fillRect(0,0,canvas[0].width,canvas[0].height);
      c.putImageData( im, x, y );
    }
    function mouseMoveHandler(e) {
      var coord = e.pageX + ' ' + e.pageY;
      x = e.pageX - r;
      y = e.pageY - r;
      draw();
    }
    function mouseMoveHandlerDry(e) {
      var coord = e.pageX + ' ' + e.pageY;
      x = e.pageX - r;
      y = e.pageY - r;
    }
    function mouseWheelHandler(e, delta) {
      var newr = Math.floor( r + (10+r/10)*delta );
      if( newr < 30 || newr > 1000 ) { return; }
      x = x + r - newr;
      y = y + r - newr;
      recache( newr );
    }
    function show() {
      $(document).unbind( 'mousemove', mouseMoveHandlerDry );
      $(document).bind( 'mousemove', mouseMoveHandler );
      $(document).mousewheel( mouseWheelHandler );
      $(window).bind( 'resize', scale );
      $('body').css('cursor','crosshair');
      scale();
      canvas.fadeIn();
      shown = true;
    }
    function hide() {
      $(document).unbind( 'mousemove', mouseMoveHandler );
      $(document).bind( 'mousemove', mouseMoveHandlerDry );
      $(document).unmousewheel( mouseWheelHandler );
      $(window).unbind( 'resize', scale );
      $('body').css('cursor','');
      canvas.fadeOut();
      shown = false;
    }
    function toggle() {
      if( shown ) {
        hide();
      } else {
        show();
      }
      return shown;
    }

    return {
      toggle : toggle
    };
  };

  function scale() {
    var cs = $(slideList[current]),
        sc = $('.slides'),
        ww = $(window).width(),
        wh = $(window).height(),
        ew = cs.outerWidth(),
        eh = cs.outerHeight(),
        r = Math.min(ww/ew,wh/eh),
        sx = Math.round((ww-ew*r)/2),
        sy = Math.round((wh-eh*r)/2);

    // scale
    $.each(['webkit','moz','o'], function(i,p) { sc.css('-'+p+'-transform','scale('+r+', '+r+')'); } );

    // center
    sc.css( { left: sx+'px', top: sy+'px' } );
  }

  // go to slide
  var current;
  function goToSlide(n) {
    var handler;
    // leaving a slide or entering the presentation?
    if( current !== undefined ) {
      // fire onleave handler for current slide (may prevent leaving)
      handler = $(slideList[current]).data('onleave');
      if( handler && handler() === false ) {
        return;
      }
    }
    current = n;

    // fire onenter hander
    handler = $(slideList[current]).data('onenter');
    if( handler ) {
      handler();
    }

    // reset visibility
    slideList.each( function(i,e) {
      $(e).attr( 'class', slideClass[i] );
      if( i == current ) {
        $(e).addClass('slideCurrent');
      } else if ( i == current-1 ) {
        $(e).addClass('slidePrev');
      } else if ( i == current+1 ) {
        $(e).addClass('slideNext');
      } else if ( i < current-1 ) {
        $(e).addClass('slideFarPrev');
      } else if ( i > current+1 ) {
        $(e).addClass('slideFarNext');
      }
    } );

    // make visible changes
    window.location.hash = slideList[current].id;
    scale();
  }

  // next slide
  function nextSlide() {
    if( current < slideList.length-1 ) {
      goToSlide(current+1);
    }
  }

  // previous slide
  function prevSlide() {
    if( current > 0 ) {
      goToSlide(current-1);
    }
  }

  function parseSteps(s) {
    var passTwo = [], steps = [],
        items = s.split(','),
        toEnd = /^(\d+)-$/,
        fromBegin = /^-(\d+)$/,
        range = /^(\d+)-(\d+)$/,
        num   = /^(\d+)$/,
        i, j, m;
    for( i = 0; i < items.length; ++i ) {
      // range
      m = range.exec( items[i] );
      if( m ) {
        if( m[1] == 0 ) {
          throw 'Steps start at 1';
        }
        for( j = m[1]; j <= m[2]; j++ ) {
          steps[j-1] = true;
        }
        continue;
      }

      // single step
      m = num.exec( items[i] );
      if( m ) {
        if( m[1] == 0 ) {
          throw 'Steps start at 1';
        }
        steps[m[1]-1] = true;
        continue;
      }

      // invalid
      throw 'Invalid step set:' + s;
    }

    return steps;
  }

  // add svg overlay to current slide
  function addOverlay( slide, callback ) {
    var o = $('

').addClass('svgOverlay');
    $(slide).append(o);
    function initOverlay(svg) {
      var d = svg.defs('myDefs');
      var m = svg.marker(d,'overlayArrow',1,2,4,4,'auto');
      svg.polyline(m,[[0,0], [4,2],[0,4],[1,2]]);

      callback(svg);
    }
    o.svg( { onLoad: initOverlay } );
  }
  // get svg handler for slide
  function getOverlay( slide ) {
    return $(slide).find('.svgOverlay').svg('get');
  }
  // draw an arrow
  function arrow(svg,x1,y1,x2,y2, options) {
    svg.line( x1, y1, x2, y2, $.extend( { markerEnd: 'url(#overlayArrow)', strokeWidth: 5, stroke: 'blue' }, options ) );
  }
  // connect two elements on the slide with an arrow
  // TODO write function to traverse relative positions up to slide level
  function arrowFromTo( svg, from, to, options ) {
    var f = $(from).position(), t = $(to).position(),
        x1 = f.left + $(from).width()/2,
        x2 = t.left + $(to).width()/2,
        y1 = f.top + $(from).height()/2,
        y2 = t.top + $(to).height()/2;
    arrow(svg,x1,y1,x2,y2,options);
  }

  // initialization
  var slideList, slideClass = [], stepTable, spotLight;
  function init() {
    var i, j, h,
        common,
        handlerList = ['onleave', 'onenter'];

    // build list of slides, remember orignal classes
    slideList = $('div.slide');
    slideList.each( function(i,e) { slideClass[i] = $(e).attr('class') });

    // append common content to all slides
    common = $('.slidecommon').detach();
    slideList.append(common);

    // compile slide event handlers
    slideList.each( function(i,e) {
      var handler;
      for( j = 0; j < handlerList.length; ++j ) {
        handler =  $(e).data(handlerList[j]);
        if( handler ) {
          $(e).data(handlerList[j], new Function(handler) );
        }
      }
    });

    // analyse step-by-step reveal information
    slideList.each( function(i,e) {
      var steps = $(e).data('steps');
      if( steps !== undefined ) {
        $(e).find('[step]').each( function(j,e) {
          // hook into list
        });
      }
    });

    // Spotlight
    spotLight = buildSpotLight(100);

    // honor url hash
    h = window.location.hash.substr(1);
    if( h !== '' ) {
      for( i = 0; i < slideList.length; ++i ) {
        if( slideList[i].id === h ) {
          goToSlide(i);
          break;
        }
      }
      if( i == slideList.length ) {
        // not found
        alert( h + " not found" );
        goToSlide(0);
      }
    } else {
      goToSlide(0);
    }
    $(window).resize(scale);
    scale();

    // add event handlers
    var frozen = false;
    $(document).keyup( function(e) {
      if( frozen ) { return; }
      switch(e.which) {
        case 34: // page down
        case 39: // crsr right
        case 40: // crsr down
        case 32: // space
          nextSlide(); break;
        case 8 : // backspace
        case 33: // page up
        case 37: // crsr left
        case 38: // crsr up
          prevSlide(); break;
        case 35: // end
          goToSlide(slideList.length-1); break;
        case 36: // home
          goToSlide(0); break;
        case 83 : // s
          spotLight.toggle(); break;
      }
    } );
  }

  return {
    init : init,
    nextSlide : nextSlide,
    prevSlide : prevSlide,
    freeze    : function() { frozen = true; },
    unfreeze  : function() { frozen = false; },
    addOverlay  : addOverlay,
    getOverlay  : getOverlay,
    arrow       : arrow,
    arrowFromTo : arrowFromTo,
    getStatus : function() { return [ current, slideList, spotLight ]; }
  };
})();

$(jslide.init);

<commit_msg>save scale factor, fix arrowFromTo, add ellipseAround<commit_after>var jslide = (function() {
  var scaleFactor, // scale factor
      current;     // current slide number

  function buildSpotLight(r) {
    var canvas, c, grad, im,
        shown = false,
        x, y;

    // build canvas
    canvas = $('<canvas/>').addClass('jslideSpotlight');
    $('body').append(canvas);

    // initial position
    x = 0;
    y = 0;

    // draw and cache spotlight
    c = canvas[0].getContext('2d');
    recache(r);

    // bind the 'dry' mousemove handler (only update coordinates, no redrawing)
    $(document).bind( 'mousemove', mouseMoveHandlerDry );

    // methods
    function recache(newr) {
      r = newr;
      // resize temporarily
      canvas[0].width = 2*r;
      canvas[0].height = 2*r;
      // radial gradient
      grad = c.createRadialGradient(r,r,r*0.75,r,r,r);
      grad.addColorStop(0, 'rgba(0,0,0,0)');
      grad.addColorStop(1, 'rgba(0,0,0,0.5)');
      // draw shapes
      c.fillStyle = grad;
      c.fillRect(0,0,2*r,2*r);
      im = c.getImageData( 0, 0, 2*r, 2*r );

      // scale back and redraw
      scale();
    }
    function scale() {
      var w = $(window).width(),
          h = $(window).height();
      canvas[0].width = w;
      canvas[0].height = h;
      draw();
    }
    function draw() {
      c.fillStyle = 'rgba(0,0,0,0.5)';
      c.clearRect(0,0,canvas[0].width,canvas[0].height);
      c.fillRect(0,0,canvas[0].width,canvas[0].height);
      c.putImageData( im, x, y );
    }
    function mouseMoveHandler(e) {
      var coord = e.pageX + ' ' + e.pageY;
      x = e.pageX - r;
      y = e.pageY - r;
      draw();
    }
    function mouseMoveHandlerDry(e) {
      var coord = e.pageX + ' ' + e.pageY;
      x = e.pageX - r;
      y = e.pageY - r;
    }
    function mouseWheelHandler(e, delta) {
      var newr = Math.floor( r + (10+r/10)*delta );
      if( newr < 30 || newr > 1000 ) { return; }
      x = x + r - newr;
      y = y + r - newr;
      recache( newr );
    }
    function show() {
      $(document).unbind( 'mousemove', mouseMoveHandlerDry );
      $(document).bind( 'mousemove', mouseMoveHandler );
      $(document).mousewheel( mouseWheelHandler );
      $(window).bind( 'resize', scale );
      $('body').css('cursor','crosshair');
      scale();
      canvas.fadeIn();
      shown = true;
    }
    function hide() {
      $(document).unbind( 'mousemove', mouseMoveHandler );
      $(document).bind( 'mousemove', mouseMoveHandlerDry );
      $(document).unmousewheel( mouseWheelHandler );
      $(window).unbind( 'resize', scale );
      $('body').css('cursor','');
      canvas.fadeOut();
      shown = false;
    }
    function toggle() {
      if( shown ) {
        hide();
      } else {
        show();
      }
      return shown;
    }

    return {
      toggle : toggle
    };
  };

  // global: scaleFactor
  function scale() {
    var cs = $(slideList[current]),
        sc = $('.slides'),
        ww = $(window).width(),
        wh = $(window).height(),
        ew = cs.outerWidth(),
        eh = cs.outerHeight(),
        r = Math.min(ww/ew,wh/eh),
        sx = Math.round((ww-ew*r)/2),
        sy = Math.round((wh-eh*r)/2);

    // scale
    $.each(['webkit','moz','o'], function(i,p) { sc.css('-'+p+'-transform','scale('+r+', '+r+')'); } );
    scaleFactor = r;

    // center
    sc.css( { left: sx+'px', top: sy+'px' } );
  }

  // go to slide
  // global: current
  function goToSlide(n) {
    var handler;
    // leaving a slide or entering the presentation?
    if( current !== undefined ) {
      // fire onleave handler for current slide (may prevent leaving)
      handler = $(slideList[current]).data('onleave');
      if( handler && handler() === false ) {
        return;
      }
    }
    current = n;

    // fire onenter hander
    handler = $(slideList[current]).data('onenter');
    if( handler ) {
      handler();
    }

    // reset visibility
    slideList.each( function(i,e) {
      $(e).attr( 'class', slideClass[i] );
      if( i == current ) {
        $(e).addClass('slideCurrent');
      } else if ( i == current-1 ) {
        $(e).addClass('slidePrev');
      } else if ( i == current+1 ) {
        $(e).addClass('slideNext');
      } else if ( i < current-1 ) {
        $(e).addClass('slideFarPrev');
      } else if ( i > current+1 ) {
        $(e).addClass('slideFarNext');
      }
    } );

    // make visible changes
    window.location.hash = slideList[current].id;
    scale();
  }

  // next slide
  function nextSlide() {
    if( current < slideList.length-1 ) {
      goToSlide(current+1);
    }
  }

  // previous slide
  function prevSlide() {
    if( current > 0 ) {
      goToSlide(current-1);
    }
  }

  function parseSteps(s) {
    var passTwo = [], steps = [],
        items = s.split(','),
        toEnd = /^(\d+)-$/,
        fromBegin = /^-(\d+)$/,
        range = /^(\d+)-(\d+)$/,
        num   = /^(\d+)$/,
        i, j, m;
    for( i = 0; i < items.length; ++i ) {
      // range
      m = range.exec( items[i] );
      if( m ) {
        if( m[1] == 0 ) {
          throw 'Steps start at 1';
        }
        for( j = m[1]; j <= m[2]; j++ ) {
          steps[j-1] = true;
        }
        continue;
      }

      // single step
      m = num.exec( items[i] );
      if( m ) {
        if( m[1] == 0 ) {
          throw 'Steps start at 1';
        }
        steps[m[1]-1] = true;
        continue;
      }

      // invalid
      throw 'Invalid step set:' + s;
    }

    return steps;
  }

  // add svg overlay to current slide
  function addOverlay( slide, callback ) {
    var o = $('

').addClass('svgOverlay');
    $(slide).append(o);
    function initOverlay(svg) {
      var d = svg.defs('myDefs');
      var m = svg.marker(d,'overlayArrow',3,2,4,4,'auto');
      svg.polyline(m,[[0,0], [4,2],[0,4],[1,2]]);

      callback(svg);
    }
    o.svg( { onLoad: initOverlay } );
  }
  // get svg handler for slide
  function getOverlay( slide ) {
    return $(slide).find('.svgOverlay').svg('get');
  }
  // draw an arrow
  function arrow(svg,x1,y1,x2,y2, options) {
    svg.line( x1, y1, x2, y2, $.extend( { markerEnd: 'url(#overlayArrow)', strokeWidth: 5, stroke: 'blue' }, options ) );
  }
  // connect two elements on the slide with an arrow
  function arrowFromTo( slide, from, to, options ) {
    var f = $(from).offset(), t = $(to).offset(), s = $(slide).offset(),
        x1 = ( f.left - s.left )/scaleFactor + $(from).width()/2,
        x2 = ( t.left - s.left )/scaleFactor + $(to).width()/2,
        y1 = ( f.top - s.top )/scaleFactor + $(from).height()/2,
        y2 = ( t.top - s.top )/scaleFactor + $(to).height()/2;
    arrow(getOverlay(slide),x1,y1,x2,y2,options);
  }
  // draw an ellipse around an element on the slide
  function ellipseAround( slide, to, options ) {
    var t = $(to).offset(), s = $(slide).offset(),
        rx = $(to).width()/2,
        x  = ( t.left - s.left )/scaleFactor  + rx,
        ry = $(to).height()/2,
        y  = ( t.top - s.top )/scaleFactor + ry;
    getOverlay(slide).ellipse(x,y,rx*1.4,ry*1.4,$.extend( { strokeWidth: 5, stroke: 'blue', fill: 'none', opacity: 0.75 }, options ) );
  }

  // initialization
  var slideList, slideClass = [], stepTable, spotLight;
  function init() {
    var i, j, h,
        common,
        handlerList = ['onleave', 'onenter'];

    // build list of slides, remember orignal classes
    slideList = $('div.slide');
    slideList.each( function(i,e) { slideClass[i] = $(e).attr('class') });

    // append common content to all slides
    common = $('.slidecommon').detach();
    slideList.append(common);

    // compile slide event handlers
    slideList.each( function(i,e) {
      var handler;
      for( j = 0; j < handlerList.length; ++j ) {
        handler =  $(e).data(handlerList[j]);
        if( handler ) {
          $(e).data(handlerList[j], new Function(handler) );
        }
      }
    });

    // analyse step-by-step reveal information
    slideList.each( function(i,e) {
      var steps = $(e).data('steps');
      if( steps !== undefined ) {
        $(e).find('[step]').each( function(j,e) {
          // hook into list
        });
      }
    });

    // Spotlight
    spotLight = buildSpotLight(100);

    // honor url hash
    h = window.location.hash.substr(1);
    if( h !== '' ) {
      for( i = 0; i < slideList.length; ++i ) {
        if( slideList[i].id === h ) {
          goToSlide(i);
          break;
        }
      }
      if( i == slideList.length ) {
        // not found
        alert( h + " not found" );
        goToSlide(0);
      }
    } else {
      goToSlide(0);
    }
    $(window).resize(scale);
    scale();

    // add event handlers
    var frozen = false;
    $(document).keyup( function(e) {
      if( frozen ) { return; }
      switch(e.which) {
        case 34: // page down
        case 39: // crsr right
        case 40: // crsr down
        case 32: // space
          nextSlide(); break;
        case 8 : // backspace
        case 33: // page up
        case 37: // crsr left
        case 38: // crsr up
          prevSlide(); break;
        case 35: // end
          goToSlide(slideList.length-1); break;
        case 36: // home
          goToSlide(0); break;
        case 83 : // s
          spotLight.toggle(); break;
      }
    } );
  }

  return {
    init : init,
    nextSlide : nextSlide,
    prevSlide : prevSlide,
    freeze    : function() { frozen = true; },
    unfreeze  : function() { frozen = false; },
    addOverlay   : addOverlay,
    getOverlay   : getOverlay,
    arrow        : arrow,
    arrowFromTo  : arrowFromTo,
    ellipseAround: ellipseAround,
    style : { redArrow : { stroke: 'red' } },
    getStatus : function() { return [ current, slideList, spotLight ]; }
  };
})();

$(jslide.init);

<|endoftext|>


<commit_before>/*global DISQUS*/

export default class Disqus {
  constructor() {
    this.isScriptLoading = false;
    this.currentIdentifier = "";
  }

  setup(identifier) {
    this.currentIdentifier = identifier;

    window.disqus_shortname = 'argshood';
    window.disqus_identifier = this.currentIdentifier;
    window.disqus_url = window.location.href;
    window.disqus_title = document.title;

    if (!this.ready()) { return; }

    setTimeout(this.resetDisqus.bind(this), 80);
  }

  ready() {
    if(!this.isScriptLoading) {
      this.isScriptLoading = true;
      this.loadDisqus();
      return false;
    }

    return typeof window.DISQUS !== 'undefined';
  }

  loadDisqus() {
    var d = document,
        s = d.createElement('script');

    s.src = '//argshood.disqus.com/embed.js';

    s.onload = () => {
      this.setup(this.currentIdentifier);
    }

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
  }

  resetDisqus() {
    let identifier = this.currentIdentifier;

    DISQUS.reset({
      reload: true,
      config: function () {
        this.page.identifier = identifier;
        this.page.url = window.location.href;
        this.page.title = document.title;
      }
    });
  }
}

<commit_msg>maybe this is better i donno<commit_after>/*global DISQUS*/

export default class Disqus {
  constructor() {
    this.isScriptLoading = false;
    this.currentIdentifier = "";
  }

  setup(identifier) {
    this.currentIdentifier = identifier;

    window.disqus_shortname = 'argshood';
    window.disqus_identifier = this.currentIdentifier;
    window.disqus_url = window.location.href;
    window.disqus_title = document.title;

    if (!this.ready()) { return; }

    setTimeout(this.resetDisqus.bind(this), 80);
  }

  ready() {
    if(!this.isScriptLoading) {
      this.isScriptLoading = true;
      this.loadDisqus();
      return false;
    }

    return typeof window.DISQUS !== 'undefined';
  }

  loadDisqus() {
    var d = document,
        s = d.createElement('script');

    s.src = '//argshood.disqus.com/embed.js';

    s.onload = () => {
      this.setup(this.currentIdentifier);
    }

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
  }

  resetDisqus() {
    let identifier = this.currentIdentifier;

    window.disqus_config = function() {
      this.page.identifier = identifier;
    };

    console.log(this.currentIdentifier);
    DISQUS.reset({
      reload: true,
      config: function () {
        this.page.identifier = identifier;
      }
    });
  }
}

<|endoftext|>


<commit_before>import Immutable from 'immutable';
import {DateConverter, NumberConverter} from '../converters';

const DEFAULT_FORMAT_INFO = {
  dateFormat: 'dd/MM/yyyy',
  numberFormat: '#,##0',
  decimalNumberFormat: '#,##0.00',
  decimalNumberSeparator: '.',
  numberGroupingSeparator: ',',
  numberGroupingSeparatorUse: true
};

/**
 * Performs initialization and handling of intl data.
 * It supports intl data in React Intl format.
 *
 * @author Alexander Frolov
 */
class I18nManager {
  /**
   * Creates and initialize new manager instance.
   * Where locale is current locale and intDatas
   * is an list with messages for different locales.
   * (see React Intl Data format)
   */
  constructor(locale, intlDatas, formatInfos) {
    this._intlData = {locales:[locale], messages: {}};
    this._intlDatas = [this._intlData];
    this._components = [];
    // current locale
    this.locale = locale;
    if(intlDatas) {
      this.register("default", intlDatas);
    }

    this._formatInfos = formatInfos;
    if (formatInfos) {
      this._formatInfo = formatInfos[locale] || DEFAULT_FORMAT_INFO;
    } else {
      this._formatInfo = DEFAULT_FORMAT_INFO;
    }

    let numberGroupingSeparator = this._formatInfo.numberGroupingSeparatorUse ? this._formatInfo.numberGroupingSeparator : null;
    this._dateConverter = new DateConverter(this._formatInfo.dateFormat);
    this._decimalNumberConverter = new NumberConverter(
      this._formatInfo.decimalNumberFormat,
      numberGroupingSeparator,
      this._formatInfo.decimalNumberSeparator
    );
    this._numberConverter = new NumberConverter(
      this._formatInfo.numberFormat,
      numberGroupingSeparator
    );
  }

  register = (component, intlDatas) => {

    if(this._components.indexOf(component) < 0) {
      // function to check if locales have common elements
      const intersects = (l1, l2) => {
        for (var i = 0; i < l1.length; i++) {
          if(l2.indexOf(l1[i]) >= 0) {
            return true;
          }
        }
      }

      intlDatas.forEach((intlData) => {
        for (var i = 0; i < this._intlDatas.length; i++) {
          if(intersects(this._intlDatas[i].locales, intlData.locales)) {
            this._intlDatas[i] = Immutable.Map({
              locales: Immutable.List(this._intlDatas[i].locales).mergeDeep(Immutable.List(intlData.locales)),
              messages: Immutable.Map(this._intlDatas[i].messages).mergeDeep(Immutable.Map(intlData.messages))
            }).toJS();
          }
          if(this._intlDatas[i].locales.indexOf(this.locale) >= 0) {
            this._intlData = this._intlDatas[i];
          }
        }
      });
      this._components.push(component);
    }

    return this;
  }

  getMessage = (path, args = {}) => {
    let messages = this._intlData.messages;

    const pathParts = path.split(".");

    let message;

    try {
      message = pathParts.reduce((obj, pathPart) => obj[pathPart], messages);
    } finally {
      if (message === undefined) {
        throw new ReferenceError("Could not find Intl message: " + path);
      }
    }

    for (let param in args) {
      let paramValue = args[param];

      if (paramValue !== null) {
        message = message.replace(`{${param}}`, paramValue.toString());
      }
    }

    return message;
  }

  get dateFormat() {
    return this._formatInfo.dateFormat;
  }

  formatDate = (date) => {
    return this._dateConverter.valueToString(date);
  }

  formatDecimalNumber = (number) => {
    return this._decimalNumberConverter.valueToString(number)
  }

  formatNumber = (number) => {
    return this._numberConverter.valueToString(number);
  }

  parseDate = (string) => {
    return this._dateConverter.stringToValue(string);
  }

  parseDecimalNumber = (string) => {
    return this._decimalNumberConverter.stringToValue(string);
  }

  parseNumber = (string) => {
    return this._numberConverter.stringToValue(string);
  }
}

export default I18nManager;
<commit_msg>Fixing undefined param value when get message with null params<commit_after>import Immutable from 'immutable';
import {DateConverter, NumberConverter} from '../converters';

const DEFAULT_FORMAT_INFO = {
  dateFormat: 'dd/MM/yyyy',
  numberFormat: '#,##0',
  decimalNumberFormat: '#,##0.00',
  decimalNumberSeparator: '.',
  numberGroupingSeparator: ',',
  numberGroupingSeparatorUse: true
};

/**
 * Performs initialization and handling of intl data.
 * It supports intl data in React Intl format.
 *
 * @author Alexander Frolov
 */
class I18nManager {
  /**
   * Creates and initialize new manager instance.
   * Where locale is current locale and intDatas
   * is an list with messages for different locales.
   * (see React Intl Data format)
   */
  constructor(locale, intlDatas, formatInfos) {
    this._intlData = {locales:[locale], messages: {}};
    this._intlDatas = [this._intlData];
    this._components = [];
    // current locale
    this.locale = locale;
    if(intlDatas) {
      this.register("default", intlDatas);
    }

    this._formatInfos = formatInfos;
    if (formatInfos) {
      this._formatInfo = formatInfos[locale] || DEFAULT_FORMAT_INFO;
    } else {
      this._formatInfo = DEFAULT_FORMAT_INFO;
    }

    let numberGroupingSeparator = this._formatInfo.numberGroupingSeparatorUse ? this._formatInfo.numberGroupingSeparator : null;
    this._dateConverter = new DateConverter(this._formatInfo.dateFormat);
    this._decimalNumberConverter = new NumberConverter(
      this._formatInfo.decimalNumberFormat,
      numberGroupingSeparator,
      this._formatInfo.decimalNumberSeparator
    );
    this._numberConverter = new NumberConverter(
      this._formatInfo.numberFormat,
      numberGroupingSeparator
    );
  }

  register = (component, intlDatas) => {

    if(this._components.indexOf(component) < 0) {
      // function to check if locales have common elements
      const intersects = (l1, l2) => {
        for (var i = 0; i < l1.length; i++) {
          if(l2.indexOf(l1[i]) >= 0) {
            return true;
          }
        }
      }

      intlDatas.forEach((intlData) => {
        for (var i = 0; i < this._intlDatas.length; i++) {
          if(intersects(this._intlDatas[i].locales, intlData.locales)) {
            this._intlDatas[i] = Immutable.Map({
              locales: Immutable.List(this._intlDatas[i].locales).mergeDeep(Immutable.List(intlData.locales)),
              messages: Immutable.Map(this._intlDatas[i].messages).mergeDeep(Immutable.Map(intlData.messages))
            }).toJS();
          }
          if(this._intlDatas[i].locales.indexOf(this.locale) >= 0) {
            this._intlData = this._intlDatas[i];
          }
        }
      });
      this._components.push(component);
    }

    return this;
  }

  getMessage = (path, args = {}) => {
    let messages = this._intlData.messages;

    const pathParts = path.split(".");

    let message;

    try {
      message = pathParts.reduce((obj, pathPart) => obj[pathPart], messages);
    } finally {
      if (message === undefined) {
        throw new ReferenceError("Could not find Intl message: " + path);
      }
    }

    for (let param of Object.keys(args)) {
      let paramValue = args[param];

      if (paramValue !== null && paramValue !== undefined) {
        message = message.replace(`{${param}}`, paramValue.toString());
      }
    }

    return message;
  }

  get dateFormat() {
    return this._formatInfo.dateFormat;
  }

  formatDate = (date) => {
    return this._dateConverter.valueToString(date);
  }

  formatDecimalNumber = (number) => {
    return this._decimalNumberConverter.valueToString(number)
  }

  formatNumber = (number) => {
    return this._numberConverter.valueToString(number);
  }

  parseDate = (string) => {
    return this._dateConverter.stringToValue(string);
  }

  parseDecimalNumber = (string) => {
    return this._decimalNumberConverter.stringToValue(string);
  }

  parseNumber = (string) => {
    return this._numberConverter.stringToValue(string);
  }
}

export default I18nManager;
<|endoftext|>