<commit_before>//  Copyright 2002-2014, University of Colorado Boulder

/**
 * Reward node that shows many nodes animating, for fun!  Shown when a perfect score is achieved in a game.
 * You can also test this by running vegas/vegas_en.html and clicking on the "Reward" screen
 *
 * There are two ways to run the animation step function.  The client code can manually call step(dt), or the client code can pass in an Events instance that triggers events on 'step'.
 * In the latter case, the listener will automatically be removed when the animation is complete.
 *
 * Notes:
 * 1. Instead of continuous animation, the animation is shown as a transient behavior that shows for a few seconds and then disappears.
 *    This is to encourage the student to move to the next challenge, instead of becoming mesmerized by a perpetual animation.
 * 2. TODO: I would like to add optional support for rotation, scaling or other visual candy
 * 3. TODO: The RewardNode automatically detaches from its parents after the animation is complete?  Or perhaps this is normally coupled to the "continue" button in the LevelCompletedDialogNode?
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var CanvasNode = require( 'SCENERY/nodes/CanvasNode' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var StarNode = require( 'SCENERY_PHET/StarNode' );
  var FaceNode = require( 'SCENERY_PHET/FaceNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var Node = require( 'SCENERY/nodes/Node' );

  //This debug flag shows a gray rectangle for the CanvasNode to help ensure that its bounds are accurate
  var debug = false;

  function RewardNode( options ) {
    var rewardNode = this;
    this.options = options = _.extend( {

      //Bounds in which to render the canvas.  TODO: Should be full screen
      canvasBounds: new Bounds2( 0, 0, ScreenView.DEFAULT_LAYOUT_BOUNDS.width, ScreenView.DEFAULT_LAYOUT_BOUNDS.height ),

      //Scale things up for rasterization and back down for rendering so they have nice resolution on retina
      scaleForResolution: 2,

      //Nodes to appear in the reward node.  They will be cached as images to improve performance
      nodes: RewardNode.createRandomNodes( [
        new FaceNode( 40, {headStroke: 'black', headLineWidth: 1.5} ),
        new StarNode()
      ], 150 ),

      //If you pass in a stepSource, which conforms to the Events interface, the RewardNode will register for events through that source
      stepSource: null
    }, options );

    //If you pass in a stepSource, which conforms to the Events interface, the RewardNode will register for events through that source
    if ( options.stepSource ) {
      this.stepCallback = function( dt ) {rewardNode.step( dt );};
      options.stepSource.on( 'step', this.stepCallback );
    }

    //Cache the nodes as images.  Use an intermediate imageWrapper since the images will be returned later asynchronously
    //And we need a place to store them, and know when they have arrived
    this.imageWrappers = [];

    //find the unique nodes in the array
    var uniqueNodes = _.uniq( this.options.nodes );

    uniqueNodes.forEach( function( node, i ) {
      rewardNode.imageWrappers.push(
        {
          image: null,

          //Record the width so the nodes can be partially offscreen since layout done before toImage completed
          width: node.width,

          node: node
        } );
      var parent = new Node( {children: [node], scale: options.scaleForResolution} );
      parent.toImage( function( image ) {
        rewardNode.imageWrappers[i].image = image;
      } );
    } );

    CanvasNode.call( this, options );

    //Some initialization must occur after this node is attached to the scene graph, see documentation for RewardNode.init below.
    this.inited = false;
  }

  return inherit( CanvasNode, RewardNode, {

      //Paint the rewards on the canvas
      // @param {CanvasContextWrapper} wrapper
      paintCanvas: function( wrapper ) {
        var context = wrapper.context;

        //If the debugging flag is on, show the bounds of the canvas
        if ( debug ) {
          var bounds = this.options.canvasBounds;

          //Fill the canvas with gray
          context.fillStyle = 'rgba(50,50,50,0.5)';
          context.fillRect( bounds.minX, bounds.minY, bounds.width, bounds.height );

          //Stroke the canvas border with blue
          context.strokeStyle = "#0000ff";
          context.lineWidth = 5;
          context.strokeRect( bounds.minX, bounds.minY, bounds.width, bounds.height );
        }
        context.scale( 1 / this.options.scaleForResolution, 1 / this.options.scaleForResolution );

        //Display the rewards, but check that they exist first.  They do not exist when attached to the timer with stepSource
        if ( this.rewards ) {
          for ( var i = 0; i < this.rewards.length; i++ ) {
            var reward = this.rewards[i];
            if ( reward.imageWrapper.image ) {
              context.drawImage( reward.imageWrapper.image, reward.x, reward.y );
            }
          }
        }
      },

      getScene: function() {
        //Find the root of the scene tree
        var node = this;
        while ( node ) {
          assert && assert( node._parents[1] === undefined, 'globalToLocalPoint unable to work for DAG' );
          if ( node._parents[0] ) {
            node = node._parents[0];
          }
          else {
            break;
          }
        }

        //TODO: add assertion to make sure node is a scenery.Scene
        return node;
      },

      //Find the first parent that is a ScreenView so we can listen for its transform, see https://github.com/phetsims/vegas/issues/4
      getScreenView: function() {
        var node = this;
        while ( node ) {
          assert && assert( node._parents[1] === undefined, 'globalToLocalPoint unable to work for DAG' );
          if ( node._parents[0] ) {
            node = node._parents[0];
            if ( node instanceof ScreenView ) {
              return node;
            }
          }
          else {
            break;
          }
        }

        throw new Error( 'No ScreenView found' );
      },

      //Only init after being attached to the scene graph, since we must ascertain the local bounds such that they take up the global screen.
      // 1. listen to the size of the scene/display
      // 2. record the trail between the scene and your CanvasNode, and
      // 3. apply the inverse of that transform to the CanvasNode (whenever an ancestor's transform changes, or when the scene/display size changes).
      //
      // Later @jonathanolson continued:
      // I don't recall how Scenery will handle Bounds2.EVERYTHING (probably assertion fails) right now, but that can change
      // for implementing now, I'd watch the iso transform, compute the inverse, and set bounds on changes to be precise (since you need them anyways to draw)
      init: function() {
        var rewardNode = this;
        var scene = this.getScene();

        //Listen to the bounds of the scene, so the canvas can be resized if the window is reshaped
        var updateBounds = function() {

          var local = rewardNode.globalToLocalBounds( scene.sceneBounds );
          rewardNode.setCanvasBounds( local );

          //Also, store the bounds in the options so the debug flag can render the bounds
          rewardNode.options.canvasBounds = local;
        };

        //When the scene is resized, update the bounds
        scene.addEventListener( 'resize', updateBounds );

        //When the ScreenView transform changes, update the bounds.  This prevents a "behind by one" problem, see https://github.com/phetsims/vegas/issues/4
        this.getScreenView().getTransform().addTransformListener( {before: function() {}, after: function() {updateBounds();}} );

        //Set the initial bounds
        updateBounds();

        //Store each reward, which has an imageWrapper (see above), x, y, speed
        this.rewards = [];
        for ( var i = 0; i < this.options.nodes.length; i++ ) {

          var node = this.options.nodes[i];
          //find the image wrapper corresponding to the node
          var imageWrapper = _.find( this.imageWrappers, function( imageWrapper ) {return imageWrapper.node === node} );
          this.rewards.push( {
            imageWrapper: imageWrapper,
            x: (Math.random() * this.options.canvasBounds.width + this.options.canvasBounds.left) * this.options.scaleForResolution - imageWrapper.width / 2,
            y: this.options.canvasBounds.top - Math.random() * this.options.canvasBounds.height * 2 - 200,
            speed: (Math.random() + 1) * 200
          } );
        }
      },

      //Move the rewards down according to their speed
      step: function( dt ) {
        if ( !this.inited && this.getScene() !== null ) {
          this.init();
          this.inited = true;
        }

        //Update all of the rewards
        var maxY = this.options.canvasBounds.height * this.options.scaleForResolution;
        for ( var i = 0; i < this.rewards.length; i++ ) {
          var reward = this.rewards[i];
          reward.y += reward.speed * dt;
          if ( reward.y > maxY ) {
            reward.y = this.options.canvasBounds.top - Math.random() * this.options.canvasBounds.height * 2 - 200;
          }
        }
        this.invalidatePaint();
      }
    },

    //Static methods
    {
      /**
       * Convenience factory method to create an array of the specified nodes in an even distribution.
       * @param {Array[Node]} nodes array of nodes to use
       * @param {Number} count
       */
      createRandomNodes: function( nodes, count ) {
        var array = [];
        for ( var i = 0; i < count; i++ ) {
          array.push( nodes[i % nodes.length] );
        }
        return array;
      }
    } );
} );<commit_msg>removed extra , and updated docs<commit_after>//  Copyright 2002-2014, University of Colorado Boulder

/**
 * Reward node that shows many nodes animating, for fun!  Shown when a perfect score is achieved in a game.
 * You can also test this by running vegas/vegas_en.html and clicking on the "Reward" screen
 *
 * There are two ways to run the animation step function.  The client code can manually call step(dt), or the client code can pass in an Events instance that triggers events on 'step'.
 * In the latter case, the listener will automatically be removed when the animation is complete.
 *
 * Notes:
 * 1. Instead of continuous animation, the animation is shown as a transient behavior that shows for a few seconds and then disappears.
 *    This is to encourage the student to move to the next challenge, instead of becoming mesmerized by a perpetual animation.
 * 2. TODO: I would like to add optional support for rotation, scaling or other visual candy
 * 3. TODO: The RewardNode automatically detaches from its parents after the animation is complete?  Or perhaps this is normally coupled to the "continue" button in the LevelCompletedDialogNode?
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var CanvasNode = require( 'SCENERY/nodes/CanvasNode' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var StarNode = require( 'SCENERY_PHET/StarNode' );
  var FaceNode = require( 'SCENERY_PHET/FaceNode' );
  var Bounds2 = require( 'DOT/Bounds2' );
  var Node = require( 'SCENERY/nodes/Node' );

  //This debug flag shows a gray rectangle for the CanvasNode to help ensure that its bounds are accurate
  var debug = false;

  function RewardNode( options ) {
    var rewardNode = this;
    this.options = options = _.extend( {

      //Bounds in which to render the canvas.  TODO: Should be full screen
      canvasBounds: new Bounds2( 0, 0, ScreenView.DEFAULT_LAYOUT_BOUNDS.width, ScreenView.DEFAULT_LAYOUT_BOUNDS.height ),

      //Scale things up for rasterization and back down for rendering so they have nice resolution on retina
      scaleForResolution: 2,

      //Nodes to appear in the reward node.  They will be cached as images to improve performance
      nodes: RewardNode.createRandomNodes( [
        new FaceNode( 40, {headStroke: 'black', headLineWidth: 1.5} ),
        new StarNode()
      ], 150 ),

      //If you pass in a stepSource, which conforms to the Events interface, the RewardNode will register for events through that source
      stepSource: null
    }, options );

    //If you pass in a stepSource, which conforms to the Events interface, the RewardNode will register for events through that source
    if ( options.stepSource ) {
      this.stepCallback = function( dt ) {rewardNode.step( dt );};
      options.stepSource.on( 'step', this.stepCallback );
    }

    //Cache the nodes as images.  Use an intermediate imageWrapper since the images will be returned later asynchronously
    //And we need a place to store them, and know when they have arrived
    this.imageWrappers = [];

    //find the unique nodes in the array
    var uniqueNodes = _.uniq( this.options.nodes );

    uniqueNodes.forEach( function( node, i ) {
      rewardNode.imageWrappers.push(
        {
          image: null,

          //Record the width so the nodes can be partially offscreen since layout done before toImage completed
          width: node.width,

          node: node
        } );
      var parent = new Node( {children: [node], scale: options.scaleForResolution} );
      parent.toImage( function( image ) {
        rewardNode.imageWrappers[i].image = image;
      } );
    } );

    CanvasNode.call( this, options );

    //Some initialization must occur after this node is attached to the scene graph, see documentation for RewardNode.init below.
    this.inited = false;
  }

  return inherit( CanvasNode, RewardNode, {

      //Paint the rewards on the canvas
      // @param {CanvasContextWrapper} wrapper
      paintCanvas: function( wrapper ) {
        var context = wrapper.context;

        //If the debugging flag is on, show the bounds of the canvas
        if ( debug ) {
          var bounds = this.options.canvasBounds;

          //Fill the canvas with gray
          context.fillStyle = 'rgba(50,50,50,0.5)';
          context.fillRect( bounds.minX, bounds.minY, bounds.width, bounds.height );

          //Stroke the canvas border with blue
          context.strokeStyle = "#0000ff";
          context.lineWidth = 5;
          context.strokeRect( bounds.minX, bounds.minY, bounds.width, bounds.height );
        }
        context.scale( 1 / this.options.scaleForResolution, 1 / this.options.scaleForResolution );

        //Display the rewards, but check that they exist first.  They do not exist when attached to the timer with stepSource
        if ( this.rewards ) {
          for ( var i = 0; i < this.rewards.length; i++ ) {
            var reward = this.rewards[i];
            if ( reward.imageWrapper.image ) {
              context.drawImage( reward.imageWrapper.image, reward.x, reward.y );
            }
          }
        }
      },

      getScene: function() {
        //Find the root of the scene tree
        var node = this;
        while ( node ) {
          assert && assert( node._parents[1] === undefined, 'globalToLocalPoint unable to work for DAG' );
          if ( node._parents[0] ) {
            node = node._parents[0];
          }
          else {
            break;
          }
        }

        //TODO: add assertion to make sure node is a scenery.Scene
        return node;
      },

      //Find the first parent that is a ScreenView so we can listen for its transform, see https://github.com/phetsims/vegas/issues/4
      getScreenView: function() {
        var node = this;
        while ( node ) {
          assert && assert( node._parents[1] === undefined, 'globalToLocalPoint unable to work for DAG' );
          if ( node._parents[0] ) {
            node = node._parents[0];
            if ( node instanceof ScreenView ) {
              return node;
            }
          }
          else {
            break;
          }
        }

        throw new Error( 'No ScreenView found' );
      },

      //Only init after being attached to the scene graph, since we must ascertain the local bounds such that they take up the global screen.
      // 1. listen to the size of the scene/display
      // 2. record the trail between the scene and your CanvasNode, and
      // 3. apply the inverse of that transform to the CanvasNode (whenever an ancestor's transform changes, or when the scene/display size changes).
      //
      // JO said: for implementing now, I'd watch the iso transform, compute the inverse, and set bounds on changes to be precise (since you need them anyways to draw)
      init: function() {
        var rewardNode = this;
        var scene = this.getScene();

        //Listen to the bounds of the scene, so the canvas can be resized if the window is reshaped
        var updateBounds = function() {

          var local = rewardNode.globalToLocalBounds( scene.sceneBounds );
          rewardNode.setCanvasBounds( local );

          //Also, store the bounds in the options so the debug flag can render the bounds
          rewardNode.options.canvasBounds = local;
        };

        //When the scene is resized, update the bounds
        scene.addEventListener( 'resize', updateBounds );

        //When the ScreenView transform changes, update the bounds.  This prevents a "behind by one" problem, see https://github.com/phetsims/vegas/issues/4
        this.getScreenView().getTransform().addTransformListener( {before: function() {}, after: function() {updateBounds();}} );

        //Set the initial bounds
        updateBounds();

        //Store each reward, which has an imageWrapper (see above), x, y, speed
        this.rewards = [];
        for ( var i = 0; i < this.options.nodes.length; i++ ) {

          var node = this.options.nodes[i];
          //find the image wrapper corresponding to the node
          var imageWrapper = _.find( this.imageWrappers, function( imageWrapper ) {return imageWrapper.node === node} );
          this.rewards.push( {
            imageWrapper: imageWrapper,
            x: (Math.random() * this.options.canvasBounds.width + this.options.canvasBounds.left) * this.options.scaleForResolution - imageWrapper.width / 2,
            y: this.options.canvasBounds.top - Math.random() * this.options.canvasBounds.height * 2 - 200,
            speed: (Math.random() + 1) * 200
          } );
        }
      },

      //Move the rewards down according to their speed
      step: function( dt ) {
        if ( !this.inited && this.getScene() !== null ) {
          this.init();
          this.inited = true;
        }

        //Update all of the rewards
        var maxY = this.options.canvasBounds.height * this.options.scaleForResolution;
        for ( var i = 0; i < this.rewards.length; i++ ) {
          var reward = this.rewards[i];
          reward.y += reward.speed * dt;
          if ( reward.y > maxY ) {
            reward.y = this.options.canvasBounds.top - Math.random() * this.options.canvasBounds.height * 2 - 200;
          }
        }
        this.invalidatePaint();
      }
    },

    //Static methods
    {
      /**
       * Convenience factory method to create an array of the specified nodes in an even distribution.
       * @param {Array[Node]} nodes array of nodes to use
       * @param {Number} count
       */
      createRandomNodes: function( nodes, count ) {
        var array = [];
        for ( var i = 0; i < count; i++ ) {
          array.push( nodes[i % nodes.length] );
        }
        return array;
      }
    } );
} );<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /**
                                                                                * Copyright (c) 2015 ZenPayroll
                                                                                *
                                                                                * This source code is licensed under the MIT license found in the
                                                                                * LICENSE file in the root directory of this source tree.
                                                                                */

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _SelectionUtils = require('./SelectionUtils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var DEFAULT_TRANSLATIONS = {
  '9': /\d/,
  'a': /[A-Za-z]/,
  '*': /[A-Za-z0-9]/
};

var BLANK_CHAR = '_';

var MaskedField = _react2.default.createClass({
  displayName: 'MaskedField',

  propTypes: {
    mask: _react2.default.PropTypes.string,
    translations: _react2.default.PropTypes.object,
    value: _react2.default.PropTypes.string,
    placeholder: _react2.default.PropTypes.string,
    onChange: _react2.default.PropTypes.func,
    onKeyDown: _react2.default.PropTypes.func,
    onComplete: _react2.default.PropTypes.func,
    onFocus: _react2.default.PropTypes.func,
    onBlur: _react2.default.PropTypes.func,
    valueLink: _react2.default.PropTypes.object
  },
  getInitialState: function getInitialState() {
    if (!this.props.mask) {
      return null;
    }

    this._buffer = this._initialBuffer();
    this._cursorPos = this._firstNonMaskIdx;

    var propsValue = this._getPropsValue();
    return {
      // TODO: Any way we can do this in one pass?
      value: propsValue ? this._maskedValue(propsValue) : ''
    };
  },
  componentDidUpdate: function componentDidUpdate() {
    if (this._cursorPos !== undefined) {
      this._setSelection(this._cursorPos);
    }
  },
  componentDidMount: function componentDidMount() {
    this._isMounted = true;
    var propsValue = this._getPropsValue();
    if (this.props.mask && typeof propsValue === 'string' && this.state.value !== propsValue) {
      this._callOnChange(this.state.value);
    }
  },
  componentWillUnmount: function componentWillUnmount() {
    this._isMounted = false;
  },
  render: function render() {
    var props = {};
    if (this.props.mask) {
      props = {
        onChange: this._handleChange,
        onKeyDown: this._handleKeyDown,
        onFocus: this._handleFocus,
        onBlur: this._handleBlur,
        value: this.state.value,
        valueLink: null
      };

      if (!this.props.placeholder) {
        props.placeholder = this._initialBuffer().join('');
      }
    }

    return _react2.default.createElement('input', _extends({}, this.props, props, { type: 'text' }));
  },
  _getSelection: function _getSelection() {
    if (this._isMounted) {
      return (0, _SelectionUtils.getSelection)(this.getDOMNode());
    } else {
      var cursorPos = (this._getPropsValue() || '').length;
      return { start: cursorPos, end: cursorPos };
    }
  },
  _setSelection: function _setSelection(start) {
    var end = arguments.length <= 1 || arguments[1] === undefined ? start : arguments[1];

    var domNode = _react2.default.findDOMNode(this);
    if (domNode === document.activeElement) {
      (0, _SelectionUtils.setSelection)(domNode, start, end);
    }
  },
  _getPropsValue: function _getPropsValue() {
    if (this.props.valueLink) {
      return this.props.valueLink.value;
    } else {
      return this.props.value;
    }
  },
  _getPattern: function _getPattern(idx) {
    var maskChar = this.props.mask[idx];
    var pattern = this.props.translations ? this.props.translations[maskChar] : null;

    return pattern || DEFAULT_TRANSLATIONS[maskChar];
  },
  _resetBuffer: function _resetBuffer(start, end) {
    for (var i = start; i < end; ++i) {
      if (this._getPattern(i)) {
        this._buffer[i] = BLANK_CHAR;
      }
    }
  },
  _initialBuffer: function _initialBuffer() {
    var buffer = [];
    for (var idx = 0; idx < this.props.mask.length; ++idx) {
      if (this._getPattern(idx)) {
        if (this._firstNonMaskIdx === undefined) {
          this._firstNonMaskIdx = idx;
        }
        buffer.push('_');
      } else {
        buffer.push(this.props.mask[idx]);
      }
    }

    return buffer;
  },
  _isBufferEmpty: function _isBufferEmpty() {
    var _this = this;

    return this._buffer.every(function (char, idx) {
      return !_this._getPattern(idx) || char === BLANK_CHAR;
    });
  },
  _isBufferFull: function _isBufferFull() {
    var _this2 = this;

    return this._buffer.every(function (char, idx) {
      return !_this2._getPattern(idx) || char !== BLANK_CHAR;
    });
  },
  _nextNonMaskIdx: function _nextNonMaskIdx(idx) {
    var next = idx + 1;
    for (; next < this.props.mask.length; ++next) {
      if (this._getPattern(next)) {
        break;
      }
    }

    return next;
  },
  _prevNonMaskIdx: function _prevNonMaskIdx(idx) {
    var prev = idx - 1;
    for (; prev >= 0; --prev) {
      if (this._getPattern(prev)) {
        break;
      }
    }

    return prev;
  },
  _callOnChange: function _callOnChange(value) {
    if (this.props.valueLink) {
      this.props.valueLink.requestChange(value);
    } else if (this.props.onChange) {
      this.props.onChange({ target: { value: value } });
    }
  },
  _callOnComplete: function _callOnComplete(value) {
    if (this.props.onComplete && this._isBufferFull()) {
      this.props.onComplete(value);
    }
  },
  _setValue: function _setValue(value) {
    if (value !== this.state.value) {
      this._callOnChange(value);
    }
    this.setState({ value: value });
  },
  _handleFocus: function _handleFocus(e) {
    var _this3 = this;

    setTimeout(function () {
      return _this3._setSelection(_this3._cursorPos);
    }, 0);

    if (this.props.onFocus) {
      this.props.onFocus(e);
    }

    this.setState({ value: this._buffer.join('') });
  },
  _handleBlur: function _handleBlur(e) {
    if (this._isBufferEmpty()) {
      this._setValue('');
    }

    if (this.props.onBlur) {
      this.props.onBlur(e);
    }
  },
  _handleKeyDown: function _handleKeyDown(e) {
    if (e.key === 'Backspace' || e.key === 'Delete') {
      var _getSelection2 = this._getSelection();

      var start = _getSelection2.start;
      var end = _getSelection2.end;

      if (start === end) {
        start = e.key === 'Delete' ? this._nextNonMaskIdx(start - 1) : this._prevNonMaskIdx(start);
        end = this._nextNonMaskIdx(start);
      }

      var value = undefined;
      var pattern = this._getPattern(start);
      if (pattern && pattern.test(this._buffer[end])) {
        value = this._maskedValue(this.state.value.substring(end), start);
      } else {
        this._resetBuffer(start, end);
        value = this._buffer.join('');
      }

      this._setValue(value);
      this._cursorPos = Math.max(start, this._firstNonMaskIdx);

      e.preventDefault();
    }

    if (this.props.onKeyDown) {
      this.props.onKeyDown(e);
    }
  },
  _handleChange: function _handleChange(e) {
    var value = this._maskedValue(e.target.value);
    this._setValue(value);
    this._callOnComplete(value);
  },
  _maskedValue: function _maskedValue(value) {
    var start = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];

    var originalCursorPos = this._cursorPos = this._getSelection().start;
    for (var bufferIdx = start, valueIdx = 0; bufferIdx < this.props.mask.length; ++bufferIdx) {
      var pattern = this._getPattern(bufferIdx);
      if (pattern) {
        var lastPatternIdx = bufferIdx;
        this._buffer[bufferIdx] = BLANK_CHAR;
        while (valueIdx < value.length && bufferIdx < this.props.mask.length) {
          var c = value[valueIdx++];
          if (c === this._buffer[bufferIdx]) {
            bufferIdx++;
          } else if (pattern.test(c)) {
            this._buffer[bufferIdx] = c;
            break;
          } else if (this._cursorPos > lastPatternIdx) {
            this._cursorPos--;
          }
        }

        if (valueIdx >= value.length) {
          this._resetBuffer(lastPatternIdx + 1, this.props.mask.length);
          break;
        }
      } else {
        if (this._buffer[bufferIdx] === value[valueIdx]) {
          if (valueIdx === originalCursorPos) {
            this._cursorPos++;
          }

          valueIdx++;
        } else if (valueIdx <= originalCursorPos) {
          this._cursorPos++;
        }
      }
    }

    return this._buffer.join('');
  }
});

exports.default = MaskedField;<commit_msg>Added latest build<commit_after>'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /**
                                                                                * Copyright (c) 2015 ZenPayroll
                                                                                *
                                                                                * This source code is licensed under the MIT license found in the
                                                                                * LICENSE file in the root directory of this source tree.
                                                                                */

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _SelectionUtils = require('./SelectionUtils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var DEFAULT_TRANSLATIONS = {
  '9': /\d/,
  'a': /[A-Za-z]/,
  '*': /[A-Za-z0-9]/
};

var BLANK_CHAR = '_';

var MaskedField = _react2.default.createClass({
  displayName: 'MaskedField',

  propTypes: {
    mask: _react2.default.PropTypes.string,
    translations: _react2.default.PropTypes.object,
    value: _react2.default.PropTypes.string,
    placeholder: _react2.default.PropTypes.string,
    onChange: _react2.default.PropTypes.func,
    onKeyDown: _react2.default.PropTypes.func,
    onComplete: _react2.default.PropTypes.func,
    onFocus: _react2.default.PropTypes.func,
    onBlur: _react2.default.PropTypes.func,
    valueLink: _react2.default.PropTypes.object
  },
  getInitialState: function getInitialState() {
    if (!this.props.mask) {
      return null;
    }

    this._buffer = this._initialBuffer();
    this._cursorPos = this._firstNonMaskIdx;

    var propsValue = this._getPropsValue();
    return {
      // TODO: Any way we can do this in one pass?
      value: propsValue ? this._maskedValue(propsValue) : ''
    };
  },
  componentDidUpdate: function componentDidUpdate() {
    if (this._cursorPos !== undefined) {
      this._setSelection(this._cursorPos);
    }
  },
  componentDidMount: function componentDidMount() {
    this._isMounted = true;
    var propsValue = this._getPropsValue();
    if (this.props.mask && typeof propsValue === 'string' && this.state.value !== propsValue) {
      this._callOnChange(this.state.value);
    }
  },
  componentWillUnmount: function componentWillUnmount() {
    this._isMounted = false;
  },
  render: function render() {
    var props = {};
    if (this.props.mask) {
      props = {
        onChange: this._handleChange,
        onKeyDown: this._handleKeyDown,
        onFocus: this._handleFocus,
        onBlur: this._handleBlur,
        value: this.state.value,
        valueLink: null
      };

      if (!this.props.placeholder) {
        props.placeholder = this._initialBuffer().join('');
      }
    }

    return _react2.default.createElement('input', _extends({}, this.props, props, { type: 'text' }));
  },
  _getSelection: function _getSelection() {
    if (this._isMounted) {
      return (0, _SelectionUtils.getSelection)(this.getDOMNode());
    } else {
      var cursorPos = (this._getPropsValue() || '').length;
      return { start: cursorPos, end: cursorPos };
    }
  },
  _setSelection: function _setSelection(start) {
    var end = arguments.length <= 1 || arguments[1] === undefined ? start : arguments[1];

    var domNode = _react2.default.findDOMNode(this);
    if (domNode === document.activeElement) {
      (0, _SelectionUtils.setSelection)(domNode, start, end);
    }
  },
  _getPropsValue: function _getPropsValue() {
    if (this.props.valueLink) {
      return this.props.valueLink.value;
    } else {
      return this.props.value;
    }
  },
  _getPattern: function _getPattern(idx) {
    var maskChar = this.props.mask[idx];
    var pattern = this.props.translations ? this.props.translations[maskChar] : null;

    return pattern || DEFAULT_TRANSLATIONS[maskChar];
  },
  _resetBuffer: function _resetBuffer(start, end) {
    for (var i = start; i < end; ++i) {
      if (this._getPattern(i)) {
        this._buffer[i] = BLANK_CHAR;
      }
    }
  },
  _initialBuffer: function _initialBuffer() {
    var buffer = [];
    for (var idx = 0; idx < this.props.mask.length; ++idx) {
      if (this._getPattern(idx)) {
        if (this._firstNonMaskIdx === undefined) {
          this._firstNonMaskIdx = idx;
        }
        buffer.push('_');
      } else {
        buffer.push(this.props.mask[idx]);
      }
    }

    return buffer;
  },
  _isBufferEmpty: function _isBufferEmpty() {
    var _this = this;

    return this._buffer.every(function (char, idx) {
      return !_this._getPattern(idx) || char === BLANK_CHAR;
    });
  },
  _isBufferFull: function _isBufferFull() {
    var _this2 = this;

    return this._buffer.every(function (char, idx) {
      return !_this2._getPattern(idx) || char !== BLANK_CHAR;
    });
  },
  _nextNonMaskIdx: function _nextNonMaskIdx(idx) {
    var next = idx + 1;
    for (; next < this.props.mask.length; ++next) {
      if (this._getPattern(next)) {
        break;
      }
    }

    return next;
  },
  _prevNonMaskIdx: function _prevNonMaskIdx(idx) {
    var prev = idx - 1;
    for (; prev >= 0; --prev) {
      if (this._getPattern(prev)) {
        break;
      }
    }

    return prev;
  },
  _callOnChange: function _callOnChange(value) {
    if (this.props.valueLink) {
      this.props.valueLink.requestChange(value);
    } else if (this.props.onChange) {
      this.props.onChange({ target: { value: value } });
    }
  },
  _callOnComplete: function _callOnComplete(value) {
    if (this.props.onComplete && this._isBufferFull()) {
      this.props.onComplete(value);
    }
  },
  _setValue: function _setValue(value) {
    if (value !== this.state.value) {
      this._callOnChange(value);
    }
    this.setState({ value: value });
  },
  _handleFocus: function _handleFocus(e) {
    var _this3 = this;

    setTimeout(function () {
      return _this3._setSelection(_this3._cursorPos);
    }, 0);

    if (this.props.onFocus) {
      this.props.onFocus(e);
    }

    this.setState({ value: this._buffer.join('') });
  },
  _handleBlur: function _handleBlur(e) {
    if (this._isBufferEmpty()) {
      this._setValue('');
    }

    if (this.props.onBlur) {
      this.props.onBlur(e);
    }
  },
  _handleKeyDown: function _handleKeyDown(e) {
    if (e.key === 'Backspace' || e.key === 'Delete') {
      var _getSelection2 = this._getSelection();

      var start = _getSelection2.start;
      var end = _getSelection2.end;

      if (start === end) {
        start = e.key === 'Delete' ? this._nextNonMaskIdx(start - 1) : this._prevNonMaskIdx(start);
        end = this._nextNonMaskIdx(start);
      }

      var value = undefined;
      var pattern = this._getPattern(start);
      if (pattern && pattern.test(this._buffer[end])) {
        value = this._maskedValue(this.state.value.substring(end), start);
      } else {
        this._resetBuffer(start, end);
        value = this._buffer.join('');
      }

      this._setValue(value);
      this._cursorPos = Math.max(start, this._firstNonMaskIdx);

      e.preventDefault();
    }

    if (this.props.onKeyDown) {
      this.props.onKeyDown(e);
    }
  },
  _handleChange: function _handleChange(e) {
    var value = this._maskedValue(e.target.value);
    this._setValue(value);
    this._callOnComplete(value);
  },
  _maskedValue: function _maskedValue(value) {
    var start = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];

    var originalCursorPos = this._cursorPos = this._getSelection().start;
    for (var bufferIdx = start, valueIdx = 0; bufferIdx < this.props.mask.length; ++bufferIdx) {
      var pattern = this._getPattern(bufferIdx);
      if (pattern) {
        var lastPatternIdx = bufferIdx;
        this._buffer[bufferIdx] = BLANK_CHAR;
        while (valueIdx < value.length && bufferIdx < this.props.mask.length) {
          var c = value[valueIdx++];
          if (c === this._buffer[bufferIdx]) {
            bufferIdx++;
          } else if (pattern.test(c)) {
            this._buffer[bufferIdx] = c;
            break;
          } else if (this._cursorPos > lastPatternIdx) {
            this._cursorPos--;
          }
        }

        if (valueIdx >= value.length) {
          this._resetBuffer(lastPatternIdx + 1, this.props.mask.length);
          break;
        }
      } else {
        if (this._buffer[bufferIdx] === value[valueIdx]) {
          if (valueIdx === originalCursorPos) {
            this._cursorPos++;
          }

          valueIdx++;
        } else if (valueIdx <= originalCursorPos) {
          this._cursorPos++;
        }
      }
    }

    return this._buffer.join('');
  }
});

module.exports = MaskedField;<|endoftext|>


<commit_before>import DomainMap from "domain-map"
import ServiceHandler from "./serviceHandler";

class RestServices {

  /**
  * Construct services.
  *
  * TODO: Provide methods to register new resources on the fly...
  *
  * @param configuration
  */
  constructor(configuration = {}) {
    this._registry = new DomainMap();

    let debug = configuration.hasOwnProperty('debug') ?
      configuration.debug : false;

    this._registry.set('properties', 'debug', debug);

    this.loadServices(configuration);
  }

  /**
  * Load services
  *
  * @param configuration
  *   services
  *     List of services with service configuration.
  */
  loadServices(configuration) {
    let services = configuration.hasOwnProperty('services') ?
      configuration.services : [];

    services.map(serviceConfig => {
      // Allow custom handlers
      let handler = serviceConfig.hasOwnProperty('handler') ?
        new serviceConfig.handler(serviceConfig, this) :
        new ServiceHandler(serviceConfig, this)

      this._registry.set('services', serviceConfig.serviceName, handler);
      this.log(`Service '${serviceConfig.serviceName}' registered`);
    });
  }

  /**
  * Returns list of intalled services.
  *
  * @return map
  */
  getServices() {
    return this._registry.getDomain('services', new Map());
  }

  /**
  * Returns installed service by key id.
  *
  * @param service name
  * @return map
  */
  getServiceByName(serviceName) {
    return this._registry.get('services', serviceName);
  }

  /**
  * Mount services to express application.
  *
  * @param app
  *   Express application where services are mounted
  */
  mount(app) {
    var self = this;

    // For each service handlers
    self.getServices().forEach((serviceHandler, serviceName) => {
      self.log(`Mounting service: ${serviceName}`);

      // Mount each resource id
      serviceHandler.getResourceIdentifiers().map((resource_key) => {
        let path = `/${serviceHandler.getServicePath()}/${resource_key}`;
        self.log(`Registering path ${path}`);

        app.use(path, function(req, res, next) {
          // Route request to resource and fetch response
          serviceHandler.lookup(req, res, function(err, response = {}) {
            // Allow altering response sending
            self.sendResponse(err, req, res, response);
          });
        });
      });
    });
  }

  /**
  * Method returns query response. This allows one to alter response before
  * sending.
  *
  * @param err
  * @param req
  * @param res
  * @param response
  */
  sendResponse(err, req, res, response) {
    // TODO: Check headers to get preferred format
    var responseFormat = "json";
    if (err) {
      var hsc = err.hasOwnProperty('code') ? err.code : 500;
      res.status(hsc).send(err.message);

    } else if (response.hasOwnProperty('result') && response.result != null) {
      // Send result
      if (responseFormat == "jsonp") {
        res.jsonp(response.result);
      } else if (responseFormat == "json") {
        res.json(response.result);
      } else {
        // Unknown response format
        res.sendStatus(400);
      }
    } else {
      // No content, send status
      res.sendStatus(200);
    }
    res.end();
  }

  /**
  * Log debugging data.
  *
  * @param value
  */
  log(value) {
    if (this._registry.get('properties', 'debug', false))
      console.log(value);
  }
}

export default RestServices;<commit_msg>Added support for content type checks<commit_after>import DomainMap from "domain-map"
import ServiceHandler from "./serviceHandler";

class RestServices {

  /**
  * Construct services.
  *
  * TODO: Provide methods to register new resources on the fly...
  *
  * @param configuration
  */
  constructor(configuration = {}) {
    this._registry = new DomainMap();

    let debug = configuration.hasOwnProperty('debug') ?
      configuration.debug : false;

    this._registry.set('properties', 'debug', debug);

    this.loadServices(configuration);
  }

  /**
  * Load services
  *
  * @param configuration
  *   services
  *     List of services with service configuration.
  */
  loadServices(configuration) {
    let services = configuration.hasOwnProperty('services') ?
      configuration.services : [];

    services.map(serviceConfig => {
      // Allow custom handlers
      let handler = serviceConfig.hasOwnProperty('handler') ?
        new serviceConfig.handler(serviceConfig, this) :
        new ServiceHandler(serviceConfig, this)

      this._registry.set('services', serviceConfig.serviceName, handler);
      this.log(`Service '${serviceConfig.serviceName}' registered`);
    });
  }

  /**
  * Returns list of intalled services.
  *
  * @return map
  */
  getServices() {
    return this._registry.getDomain('services', new Map());
  }

  /**
  * Returns installed service by key id.
  *
  * @param service name
  * @return map
  */
  getServiceByName(serviceName) {
    return this._registry.get('services', serviceName);
  }

  /**
  * Mount services to express application.
  *
  * @param app
  *   Express application where services are mounted
  */
  mount(app) {
    var self = this;

    // For each service handlers
    self.getServices().forEach((serviceHandler, serviceName) => {
      self.log(`Mounting service: ${serviceName}`);

      // Mount each resource id
      serviceHandler.getResourceIdentifiers().map((resource_key) => {
        let path = `/${serviceHandler.getServicePath()}/${resource_key}`;
        self.log(`Registering path ${path}`);

        app.use(path, function(req, res, next) {
          // Route request to resource and fetch response
          serviceHandler.lookup(req, res, function(err, response = {}) {
            // Allow altering response sending
            self.sendResponse(err, req, res, response);
          });
        });
      });
    });
  }

  /**
  * Method returns query response. This allows one to alter response before
  * sending.
  *
  * @param err
  * @param req
  * @param res
  * @param response
  */
  sendResponse(err, req, res, response) {
    var responseFormat = 'text';
    let contentType = req.get('Content-Type');

    switch (contentType) {
      case "json":
      case "application/json":
        responseFormat = "json"
        break;

      case "javascript":
      case "application/javascript":
        responseFormat = "jsonp"
        break;
    }

    if (err) {
      var hsc = err.hasOwnProperty('code') ? err.code : 500;

      if (responseFormat == "jsonp") {
        res.status(hsc).jsonp({
          error: {
            code: hsc,
            message: err.message
          }
        });
      } else if (responseFormat == "json") {
        res.status(hsc).json({
          error: {
            code: hsc,
            message: err.message
          }
        });
      } else {
        // Unknown response format
        res.status(hsc).send(err.message);
      }

    } else if (response.hasOwnProperty('result') && response.result != null) {
      // Send result
      if (responseFormat == "jsonp") {
        res.jsonp(response.result);
      } else if (responseFormat == "json") {
        res.json(response.result);
      } else {
        // Unknown response format
        res.sendStatus(400);
      }
    } else {
      // No content, send status
      res.sendStatus(200);
    }
    res.end();
  }

  /**
  * Log debugging data.
  *
  * @param value
  */
  log(value) {
    if (this._registry.get('properties', 'debug', false))
      console.log(value);
  }
}

export default RestServices;<|endoftext|>


<commit_before>"use strict"
const colors = require('colors');
const walk = require('walk');
const fs = require("fs");
const ytdl = require('ytdl-core');

class MusicManager{
  constructor(options){
    this.options = options;
    this.disnode = options.disnode;

    this.following = [];

    this.defaultConfig = {
      commands:[
				{
		      "cmd": "list",
		      "context": "MusicManager",
		      "run": "cmdListAudio",
		      "desc": "Displays list of Audio Files.",
		      "usage": "list [page]",
		    },
		    {
		      "cmd": "play",
		      "context": "MusicManager",
		      "run": "cmdPlay",
		      "desc": "Plays an audio file.",
		      "usage": "play [filename] [volume]",
		    },
        {
		      "cmd": "skip",
		      "context": "MusicManager",
		      "run": "cmdSkip",
		      "desc": "Displays list of Audio Files.",
		      "usage": "list [page]",
		    },
				{
		      "cmd": "stream",
		      "context": "MusicManager",
		      "run": "cmdStream",
		      "desc": "Plays an audio file.",
		      "usage": "play [url] [volume]",
		    },
				{
		      "cmd": "addsong",
		      "context": "MusicManager",
		      "run": "cmdAddSong",
		      "desc": "Adds a song",
		      "usage": "addsong [name] [url]",
		    },
		    {
		      "cmd": "stop",
		      "context": "MusicManager",
		      "run": "cmdStop",
		      "desc": "Stops all audio.",
		      "usage": "stop",
		    },
				{
          "cmd": "jv",
          "context": "MusicManager",
          "run": "cmdJoinVoice",
          "desc": "Joins the voice channel you are connected to.",
          "usage": "jv"
        },
        {
          "cmd": "lv",
          "context": "MusicManager",
          "run": "cmdLeaveVoice",
          "desc": "Leaves the voice channel you are connected to.",
          "usage": "lv",
        },
        {
          "cmd": "follow",
          "context": "MusicManager",
          "run": "cmdFollowUser",
          "desc": "Test Command that lists all params.",
          "usage": "follow [User]",
        },
        {
          "cmd": "unfollow",
          "context": "MusicManager",
          "run": "cmdUnFollowUser",
          "desc": "Test Command that lists all params.",
          "usage": "unfollow [parms]",
        }
			],
			songs: [],
			resNoName : "```Please Enter a name for this song!```",
			resNoUrl : "```Please Enter a Youtube URL for this song!```",
			resSongAdded : "```[Song] Added!```",
      resFollow : "**Following: ** [Sender]",
      resUnFollow : "**Stop Following: ** [Sender]",
      resJoiningServer: "**Joining Server: ** [Server]",
      resNotInServer: "**Can't Join You! Try Joining a Channel First!**"
    };

    this.config = this.disnode.config.MusicManager || this.defaultConfig;

    if(options.voiceEvents == true){
       options.disnode.bot.on("voiceJoin", (c,u)=>this.OnVoiceJoin(c,u));
       options.disnode.bot.on("voiceLeave", (c,u)=>this.OnVoiceLeave(c,u));
    }
  }

  OnVoiceJoin(channel,user){
    if(this.following.includes(user.username)){
        this.JoinServer(channel);
    }
  }

  OnVoiceLeave(channel,user){
    if(this.following.includes(user.username)){
      this.LeaveServer(channel);
    }
  }

  playLoop(connection){
    var self = this;
    connection.playRunning = true;
    var stream = ytdl(connection.queue[0], {audioonly: true});
    stream.on('end', function(){
      if(stream.length == 0){
        connection.playRunning = false;

      }else{
        connection.queue.splice(0,1);
        self.playLoop(connection);
        console.log("NEXT IN queue");
      }
    });
		connection.playRawStream(stream);
  }

  playUrl(url,connection, volumeOptions){
    var bot = this.disnode.bot;
    if(!connection.queue){connection.queue = [];}
    connection.queue.push(url);
    if(!connection.playRunning){
      this.playLoop(connection);
    }
  }

  JoinServer(channel){
    var self = this;
    this.disnode.bot.joinVoiceChannel(channel, function(err, connnection){
      if(err){
        console.log(err);
        return;
      }
    });
  }

  LeaveServer(channel){
    var self = this;
    this.disnode.bot.leaveVoiceChannel(channel, function(err, connnection){
      if(err){
        console.log(err);
        return;
      }
    });
  }

  cmdPlay(parsedMsg){
    var url = parsedMsg.params[0];
    var channel = GetVoiceConnectionViaMsg(parsedMsg.msg, this.disnode.bot.voiceConnections);

    if(channel){
      this.playUrl(url,channel,{})
    }
  }

  cmdJoinVoice(parsedMsg){
    var self = this;
    var channel = parsedMsg.msg.author.voiceChannel;
    if(channel){
      this.JoinServer(channel);
      this.disnode.sendResponse(parsedMsg, this.config.resJoiningServer,{parse: true});
    }else{
      this.disnode.sendResponse(parsedMsg, this.config.resNotInServer,{parse: true});
    }
  }

  cmdLeaveVoice(parsedMsg){
    var channel = GetVoiceConnectionViaMsg(parsedMsg.msg, this.disnode.bot.voiceConnections).voiceChannel;
    this.LeaveServer(channel);
  }

  cmdSkip(parsedMsg){
    var connection = GetVoiceConnectionViaMsg(parsedMsg.msg, this.disnode.bot.voiceConnections);

    if(connection){
      connection.queue.splice(0,1);
      this.playLoop(connection);
    }
  }

  cmdFollowUser(parsedMsg){
    var self = this;
    this.following.push(parsedMsg.msg.author.username);
    console.log(this.following);
    this.disnode.sendResponse(parsedMsg, this.config.resFollow,{parse: true});
  }

  cmdUnFollowUser(parsedMsg){
    var index = this.following.indexOf(parsedMsg.msg.author.username);

    this.following.splice(index,1);

    this.disnode.sendResponse(parsedMsg, this.config.resUnFollow,{parse: true});
  }

}

function GetVoiceConnectionViaMsg(msg, voiceConnections){
  var connection = {};

  var serverChannels = msg.server.channels;

  for (var i = 0; i < voiceConnections.length; i++) {
    var channel = voiceConnections[i].voiceChannel;

    if(serverChannels.includes(channel)){
      connection = voiceConnections[i];
    }
  }

  return connection;
}

module.exports = MusicManager;
<commit_msg>Added Connection Check for Play Command<commit_after>"use strict"
const colors = require('colors');
const walk = require('walk');
const fs = require("fs");
const ytdl = require('ytdl-core');

class MusicManager{
  constructor(options){
    this.options = options;
    this.disnode = options.disnode;

    this.following = [];

    this.defaultConfig = {
      commands:[
				{
		      "cmd": "list",
		      "context": "MusicManager",
		      "run": "cmdListAudio",
		      "desc": "Displays list of Audio Files.",
		      "usage": "list [page]",
		    },
		    {
		      "cmd": "play",
		      "context": "MusicManager",
		      "run": "cmdPlay",
		      "desc": "Plays an audio file.",
		      "usage": "play [filename] [volume]",
		    },
        {
		      "cmd": "skip",
		      "context": "MusicManager",
		      "run": "cmdSkip",
		      "desc": "Displays list of Audio Files.",
		      "usage": "list [page]",
		    },
				{
		      "cmd": "stream",
		      "context": "MusicManager",
		      "run": "cmdStream",
		      "desc": "Plays an audio file.",
		      "usage": "play [url] [volume]",
		    },
				{
		      "cmd": "addsong",
		      "context": "MusicManager",
		      "run": "cmdAddSong",
		      "desc": "Adds a song",
		      "usage": "addsong [name] [url]",
		    },
		    {
		      "cmd": "stop",
		      "context": "MusicManager",
		      "run": "cmdStop",
		      "desc": "Stops all audio.",
		      "usage": "stop",
		    },
				{
          "cmd": "jv",
          "context": "MusicManager",
          "run": "cmdJoinVoice",
          "desc": "Joins the voice channel you are connected to.",
          "usage": "jv"
        },
        {
          "cmd": "lv",
          "context": "MusicManager",
          "run": "cmdLeaveVoice",
          "desc": "Leaves the voice channel you are connected to.",
          "usage": "lv",
        },
        {
          "cmd": "follow",
          "context": "MusicManager",
          "run": "cmdFollowUser",
          "desc": "Test Command that lists all params.",
          "usage": "follow [User]",
        },
        {
          "cmd": "unfollow",
          "context": "MusicManager",
          "run": "cmdUnFollowUser",
          "desc": "Test Command that lists all params.",
          "usage": "unfollow [parms]",
        }
			],
			songs: [],
			resNoName : "```Please Enter a name for this song!```",
			resNoUrl : "```Please Enter a Youtube URL for this song!```",
			resSongAdded : "```[Song] Added!```",
      resFollow : "**Following: ** [Sender]",
      resUnFollow : "**Stop Following: ** [Sender]",
      resJoiningServer: "**Joining Server: ** [Server]",
      resNotInServer: "**Can't Join You! Try Joining a Channel First!**"
    };

    this.config = this.disnode.config.MusicManager || this.defaultConfig;

    if(options.voiceEvents == true){
       options.disnode.bot.on("voiceJoin", (c,u)=>this.OnVoiceJoin(c,u));
       options.disnode.bot.on("voiceLeave", (c,u)=>this.OnVoiceLeave(c,u));
    }
  }

  OnVoiceJoin(channel,user){
    if(this.following.includes(user.username)){
        this.JoinServer(channel);
    }
  }

  OnVoiceLeave(channel,user){
    if(this.following.includes(user.username)){
      this.LeaveServer(channel);
    }
  }

  playLoop(connection){
    var self = this;
    connection.playRunning = true;
    var stream = ytdl(connection.queue[0], {audioonly: true});
    stream.on('end', function(){
      if(stream.length == 0){
        connection.playRunning = false;

      }else{
        connection.queue.splice(0,1);
        self.playLoop(connection);
        console.log("NEXT IN queue");
      }
    });
		connection.playRawStream(stream);
  }

  playUrl(url,connection, volumeOptions){
    var bot = this.disnode.bot;
    if(!connection.queue){connection.queue = [];}
    connection.queue.push(url);
    if(!connection.playRunning){
      this.playLoop(connection);
    }
  }

  JoinServer(channel){
    var self = this;
    this.disnode.bot.joinVoiceChannel(channel, function(err, connnection){
      if(err){
        console.log(err);
        return;
      }
    });
  }

  LeaveServer(channel){
    var self = this;
    this.disnode.bot.leaveVoiceChannel(channel, function(err, connnection){
      if(err){
        console.log(err);
        return;
      }
    });
  }

  cmdPlay(parsedMsg){
    var url = parsedMsg.params[0];
    var channel = GetVoiceConnectionViaMsg(parsedMsg.msg, this.disnode.bot.voiceConnections);

    if(channel){
      this.playUrl(url,channel,{});
    }
    else{
      this.disnode.sendResponse(parsedMsg, "Not In Server!");
    }
  }

  cmdJoinVoice(parsedMsg){
    var self = this;
    var channel = parsedMsg.msg.author.voiceChannel;
    if(channel){
      this.JoinServer(channel);
      this.disnode.sendResponse(parsedMsg, this.config.resJoiningServer,{parse: true});
    }else{
      this.disnode.sendResponse(parsedMsg, this.config.resNotInServer,{parse: true});
    }
  }

  cmdLeaveVoice(parsedMsg){
    var channel = GetVoiceConnectionViaMsg(parsedMsg.msg, this.disnode.bot.voiceConnections).voiceChannel;
    this.LeaveServer(channel);
  }

  cmdSkip(parsedMsg){
    var connection = GetVoiceConnectionViaMsg(parsedMsg.msg, this.disnode.bot.voiceConnections);

    if(connection){
      connection.queue.splice(0,1);
      this.playLoop(connection);
    }
  }

  cmdFollowUser(parsedMsg){
    var self = this;
    this.following.push(parsedMsg.msg.author.username);
    console.log(this.following);
    this.disnode.sendResponse(parsedMsg, this.config.resFollow,{parse: true});
  }

  cmdUnFollowUser(parsedMsg){
    var index = this.following.indexOf(parsedMsg.msg.author.username);

    this.following.splice(index,1);

    this.disnode.sendResponse(parsedMsg, this.config.resUnFollow,{parse: true});
  }

}

function GetVoiceConnectionViaMsg(msg, voiceConnections){
  var connection;

  var serverChannels = msg.server.channels;

  for (var i = 0; i < voiceConnections.length; i++) {
    var channel = voiceConnections[i].voiceChannel;

    if(serverChannels.includes(channel)){
      connection = voiceConnections[i];
    }
  }

  return connection;
}

module.exports = MusicManager;
<|endoftext|>


<commit_before>// Copyright 2014-2015, University of Colorado Boulder

/**
 * Renders text that contains subscripts and superscripts.
 * This was created to render chemical formulas (e.g. 'H3O+') but will undoubtedly have other uses.
 * Text must be provided in HTML format, and may contain only plaintext,  and .
 * Each  and  tag must be preceded by plaintext, and nesting of tags is not supported.
 * This node's y position will be at the text's baseline.
 *

 * Beware of using this for situations where the text changes frequently.
 * The implementation relies on jQuery to parse the HTML, and this has not been profiled.
 * More significantly, since the HTML string is general, changing it requires rebuilding the node.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Text = require( 'SCENERY/nodes/Text' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var StringUtils = require( 'PHETCOMMON/util/StringUtils' );

  /**
   *
   * @param {string} text
   * @param {Object} [options]
   * @constructor
   */
  function SubSupText( text, options ) {

    // defaults
    options = _.extend( {
      // all text
      fill: 'black',
      font: new PhetFont( 20 ),
      // plain text
      textXSpacing: 0, // space between plain text and whatever precedes it
      // subscripts
      subScale: 0.75, // scale of subscript relative to plain text
      subXSpacing: 0, // space between subscript and whatever precedes it
      subYOffset: 0, // offset of subscript's center from baseline
      // superscripts
      supScale: 0.75, // scale of superscript relative to plain text
      supXSpacing: 0, // space between superscript and whatever precedes it
      supYOffset: 0, // offset of superscript's center from cap line
      capHeightScale: 0.75 // fudge factor for computing cap height, compensates for inaccuracy of Text.height
    }, options );

    // scenery.Text properties with setters and getters
    this._text = text; // @private
    this._options = options; // @private

    // compute cap line offset from baseline, must be recomputed if font changes!
    var tmpText = new Text( 'X', { font: options.font } );
    this._capLineYOffset = options.capHeightScale * ( tmpText.top - tmpText.y ); // @private

    Node.call( this );

    // Single parent for all Text nodes, so that we can change properties without affecting children added by clients.
    this._textParent = new Node(); // @private
    this.addChild( this._textParent );

    this.update();

    this.mutate( options );
  }

  sceneryPhet.register( 'SubSupText', SubSupText );

  return inherit( Node, SubSupText, {

    /*
     * @private
     * @throws Error if the text doesn't follow the constraints defines in the JSdoc above
     */
    update: function() {
      var text = this._text;
      var options = this._options;

      /*---------------------------------------------------------------------------*
       * Parsing the text into slices
       *
       * E.g. if we have a string (with embedding marks represented by LTR, RTL, POP):
       * RTL + 'Molecule: ' + LTR + 'Na2O' + POP + POP
       *
       * Then we will result in an array of slices:
       *
       * [
       *   { mode: 'normal', string: RTL + 'Molecule: ' + LTR + 'Na' + POP + POP },
       *   { mode: 'sub', string: RTL + LTR + '2' + POP + POP },
       *   { mode: 'normal', string: RTL + LTR + 'O' + POP + POP }
       * ]
       *
       * See https://github.com/phetsims/scenery-phet/issues/207 for details on the embedding mark handling.
       *---------------------------------------------------------------------------*/

      var regex = /<\/?[^>]+>/g; // Regular expression that will identify start and end tags
      var match; // {string} - Matched string with an index, from regex.exec( string ). Also has .index property.
      var index = 0;
      var mode = 'normal'; // 'normal', 'sub', 'sup' - Current "mode", nesting not supported
      var slices = []; // {Array.<{ mode: 'normal'|'sub'|'sup', string: {string} }>} - Strings tagged with sub/sup info

      // Pushes a string slice (tagged with the current sub/sup mode) to the slices array.
      function addSlice( startIndex, endIndex ) {
        // Ignore empty strings
        if ( endIndex > startIndex ) {
          slices.push( {
            mode: mode,

            // Use embeddedSlice so that embedding marks are added to keep the directions the same.
            // See https://github.com/phetsims/scenery-phet/issues/207
            string: StringUtils.embeddedSlice( text, startIndex, endIndex )
          } );
        }
      }

      // Iterate through regex matches. The match will be the full string of the tag, like '', and will have the
      // index of the match in the string.
      while ( ( match = regex.exec( text ) ) !== null ) {
        var matchString = match[ 0 ]; // e.g. ''
        var matchIndex = match.index;

        // If we have remaining text before this tag, add it as a slice
        addSlice( index, matchIndex );
        index = matchIndex + matchString.length;

        // Change modes, with assertions to ensure we have the expected tag values
        if ( mode === 'normal' ) {
          assert && assert( matchString === '' || matchString === '',
            'Unexpected tag in normal mode: ' + matchString );

          if ( matchString === '' ) {
            mode = 'sub';
          }
          else if ( matchString === '' ) {
            mode = 'sup';
          }
        }
        else if ( mode === 'sub' ) {
          assert && assert( matchString === '',
            'Unexpected tag in sub mode: ' + matchString );

          mode = 'normal';
        }
        else if ( mode === 'sup' ) {
          assert && assert( matchString === '',
            'Unexpected tag in sup mode: ' + matchString );

          mode = 'normal';
        }
      }

      // At the end, add a slice for any text that's between the last tag and the end of the string
      addSlice( index, text.length );

      /*---------------------------------------------------------------------------*
       * Node construction
       *---------------------------------------------------------------------------*/

      // For non-normal slices, what their centerY value be set to.
      var centerYs = {
        sub: options.subYOffset,
        sup: this._capLineYOffset + options.subYOffset
      };

      // What slices scale should be set to.
      var scales = {
        normal: 1,
        sub: options.subScale,
        sup: options.supScale
      };

      this._textParent.removeAllChildren();

      var previousSlice;
      for ( var i = 0; i < slices.length; i++ ) {
        var slice = slices[ i ];
        var node = new Text( slice.string, {
          font: options.font,
          fill: options.fill,
          scale: scales[ slice.mode ],
          left: previousSlice ? previousSlice.node.right + options.textXSpacing : 0
        } );
        if ( slice.mode !== 'normal' ) {
          node.centerY = centerYs[ slice.mode ];
        }
        slice.node = node;
        this._textParent.addChild( node );
        previousSlice = slice;
      }
    },

    // text ----------------------------------------------------------

    // @public
    setText: function( text ) {
      this._text = text;
      this.update();
    },
    set text( value ) { this.setText( value ); },

    // @public
    getText: function() { return this._text; },
    get text() { return this.getText(); },

    // fill ----------------------------------------------------------

    // @public
    setFill: function( fill ) {
      this._options.fill = fill;
      var childrenCount = this._textParent.getChildrenCount();
      for ( var i = 0; i < childrenCount; i++ ) {
        this._textParent.getChildAt( i ).fill = fill;
      }
    },
    set fill( value ) { this.setFill( value ); },

    // @public
    getFill: function() { return this._fill; },
    get fill() { return this.getFill(); }

    //TODO add setters and getters for other scenery.Text properties as needed
  } );
} );
<commit_msg>Support missing sup/sub script options, see #215<commit_after>// Copyright 2014-2015, University of Colorado Boulder

/**
 * Renders text that contains subscripts and superscripts.
 * This was created to render chemical formulas (e.g. 'H3O+') but will undoubtedly have other uses.
 * Text must be provided in HTML format, and may contain only plaintext,  and .
 * Each  and  tag must be preceded by plaintext, and nesting of tags is not supported.
 * This node's y position will be at the text's baseline.
 *

 * Beware of using this for situations where the text changes frequently.
 * The implementation relies on jQuery to parse the HTML, and this has not been profiled.
 * More significantly, since the HTML string is general, changing it requires rebuilding the node.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Text = require( 'SCENERY/nodes/Text' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var StringUtils = require( 'PHETCOMMON/util/StringUtils' );

  /**
   *
   * @param {string} text
   * @param {Object} [options]
   * @constructor
   */
  function SubSupText( text, options ) {

    // defaults
    options = _.extend( {
      // all text
      fill: 'black',
      font: new PhetFont( 20 ),
      // plain text
      textXSpacing: 0, // space between plain text and whatever precedes it
      // subscripts
      subScale: 0.75, // scale of subscript relative to plain text
      subXSpacing: 0, // space between subscript and whatever precedes it
      subYOffset: 0, // offset of subscript's center from baseline
      // superscripts
      supScale: 0.75, // scale of superscript relative to plain text
      supXSpacing: 0, // space between superscript and whatever precedes it
      supYOffset: 0, // offset of superscript's center from cap line
      capHeightScale: 0.75 // fudge factor for computing cap height, compensates for inaccuracy of Text.height
    }, options );

    // scenery.Text properties with setters and getters
    this._text = text; // @private
    this._options = options; // @private

    // compute cap line offset from baseline, must be recomputed if font changes!
    var tmpText = new Text( 'X', { font: options.font } );
    this._capLineYOffset = options.capHeightScale * ( tmpText.top - tmpText.y ); // @private

    Node.call( this );

    // Single parent for all Text nodes, so that we can change properties without affecting children added by clients.
    this._textParent = new Node(); // @private
    this.addChild( this._textParent );

    this.update();

    this.mutate( options );
  }

  sceneryPhet.register( 'SubSupText', SubSupText );

  return inherit( Node, SubSupText, {

    /*
     * @private
     * @throws Error if the text doesn't follow the constraints defines in the JSdoc above
     */
    update: function() {
      var text = this._text;
      var options = this._options;

      /*---------------------------------------------------------------------------*
       * Parsing the text into slices
       *
       * E.g. if we have a string (with embedding marks represented by LTR, RTL, POP):
       * RTL + 'Molecule: ' + LTR + 'Na2O' + POP + POP
       *
       * Then we will result in an array of slices:
       *
       * [
       *   { mode: 'normal', string: RTL + 'Molecule: ' + LTR + 'Na' + POP + POP },
       *   { mode: 'sub', string: RTL + LTR + '2' + POP + POP },
       *   { mode: 'normal', string: RTL + LTR + 'O' + POP + POP }
       * ]
       *
       * See https://github.com/phetsims/scenery-phet/issues/207 for details on the embedding mark handling.
       *---------------------------------------------------------------------------*/

      var regex = /<\/?[^>]+>/g; // Regular expression that will identify start and end tags
      var match; // {string} - Matched string with an index, from regex.exec( string ). Also has .index property.
      var index = 0;
      var mode = 'normal'; // 'normal', 'sub', 'sup' - Current "mode", nesting not supported
      var slices = []; // {Array.<{ mode: 'normal'|'sub'|'sup', string: {string} }>} - Strings tagged with sub/sup info

      // Pushes a string slice (tagged with the current sub/sup mode) to the slices array.
      function addSlice( startIndex, endIndex ) {
        // Ignore empty strings
        if ( endIndex > startIndex ) {
          slices.push( {
            mode: mode,

            // Use embeddedSlice so that embedding marks are added to keep the directions the same.
            // See https://github.com/phetsims/scenery-phet/issues/207
            string: StringUtils.embeddedSlice( text, startIndex, endIndex )
          } );
        }
      }

      // Iterate through regex matches. The match will be the full string of the tag, like '', and will have the
      // index of the match in the string.
      while ( ( match = regex.exec( text ) ) !== null ) {
        var matchString = match[ 0 ]; // e.g. ''
        var matchIndex = match.index;

        // If we have remaining text before this tag, add it as a slice
        addSlice( index, matchIndex );
        index = matchIndex + matchString.length;

        // Change modes, with assertions to ensure we have the expected tag values
        if ( mode === 'normal' ) {
          assert && assert( matchString === '' || matchString === '',
            'Unexpected tag in normal mode: ' + matchString );

          if ( matchString === '' ) {
            mode = 'sub';
          }
          else if ( matchString === '' ) {
            mode = 'sup';
          }
        }
        else if ( mode === 'sub' ) {
          assert && assert( matchString === '',
            'Unexpected tag in sub mode: ' + matchString );

          mode = 'normal';
        }
        else if ( mode === 'sup' ) {
          assert && assert( matchString === '',
            'Unexpected tag in sup mode: ' + matchString );

          mode = 'normal';
        }
      }

      // At the end, add a slice for any text that's between the last tag and the end of the string
      addSlice( index, text.length );

      /*---------------------------------------------------------------------------*
       * Node construction
       *---------------------------------------------------------------------------*/

      // For non-normal slices, what their centerY and centerX values should be set to.
      var centerYs = {
        sub: options.subYOffset,
        sup: this._capLineYOffset + options.supYOffset
      };

      var centerXs = {
        sub: options.subXSpacing,
        sup: options.supXSpacing
      };

      // What slices scale should be set to.
      var scales = {
        normal: 1,
        sub: options.subScale,
        sup: options.supScale
      };

      this._textParent.removeAllChildren();

      var previousSlice;
      for ( var i = 0; i < slices.length; i++ ) {
        var slice = slices[ i ];
        var node = new Text( slice.string, {
          font: options.font,
          fill: options.fill,
          scale: scales[ slice.mode ],
          left: previousSlice ? previousSlice.node.right + options.textXSpacing : 0
        } );
        if ( slice.mode !== 'normal' ) {
          node.centerY = centerYs[ slice.mode ];
          node.left = previousSlice.node.right + centerXs[ slice.mode ];
        }
        slice.node = node;
        this._textParent.addChild( node );
        previousSlice = slice;
      }
    },

    // text ----------------------------------------------------------

    // @public
    setText: function( text ) {
      this._text = text;
      this.update();
    },
    set text( value ) { this.setText( value ); },

    // @public
    getText: function() { return this._text; },
    get text() { return this.getText(); },

    // fill ----------------------------------------------------------

    // @public
    setFill: function( fill ) {
      this._options.fill = fill;
      var childrenCount = this._textParent.getChildrenCount();
      for ( var i = 0; i < childrenCount; i++ ) {
        this._textParent.getChildAt( i ).fill = fill;
      }
    },
    set fill( value ) { this.setFill( value ); },

    // @public
    getFill: function() { return this._fill; },
    get fill() { return this.getFill(); }

    //TODO add setters and getters for other scenery.Text properties as needed
  } );
} );
<|endoftext|>


<commit_before>var imageDefault = "null";
var errorImage = 1;
var modify = false;

function checkImage() {
    var regexp = /\w+\.(gif|png|jpg|jpeg)/i;
    var tag = null;
    tag = document.getElementById("wallpaper_new_img");
    if (tag.value.search(regexp) == -1 || tag.value == imageDefault) {
    	// Inserito un file che non è immagine o
        tag.style.color = "red";
        errorImage = 1;
    } else {
        tag.style.color = "black";
        errorImage = 0;
    }
    checkSubmit();
}

function checkSubmit() {
    var tag = null;
    tag = document.getElementById("submit_modal_wallpaper");
    if(errorImage) {
	// Manca l'immagine o c'è stato un caricamento errato
	tag.disabled = true;
	tag.style.background =  "gray";
	tag.style.textShadow = "1px 1px 2px black";
     } else {
	tag.disabled = false;
	tag.style.background =  "#A00";
	tag.style.textShadow = "1px 1px 1px #9E3F3F";
     }
}

document.addEventListener("DOMContentLoaded", function() {
    if(document.getElementById("submit_modal_wallpaper")) {
        // Stringhe di base dell'input type=file
        imageDefault = document.getElementById("wallpaper_new_img").value;

        // Inizializzo errori
        document.getElementById("wallpaper_new_img").addEventListener("blur", checkImage, true);
        document.getElementById("wallpaper_new_img").addEventListener("change", checkImage, true);
    }
    // Controllo sumbit
    checkSubmit();
}, true);
<commit_msg>admin_news.js edited online with Bitbucket<commit_after>document.addEventListener("DOMContentLoaded", function() {
    if (document.getElementById("submit_modal_wallpaper")) {

    	document.getElementById("form_modal_modify").onsubmit = function() {
    		var regexp = /\w+\.(gif|png|jpg|jpeg)/i;
    		var img = document.getElementById("wallpaper_new_img");
    		var submit = document.getElementById('submit_modal_wallpaper');

    		if (submit.value == 'Aggiungi') {
    			if (img.value.search(regexp) == -1) {
    				img.style.color = "red";
    				return false;
    			} else return true;
    		} else return true;
    	};

		document.getElementById("wallpaper_new_img").addEventListener("change", function() {
        	var regexp = /\w+\.(gif|png|jpg|jpeg)/i;
    		var img = document.getElementById("wallpaper_new_img");
    		if (img.value.search(regexp) == -1) {
	        	img.style.color = "red";
    		} else {
    			img.style.color = "black";
    		}
        });
    }
}, true);<|endoftext|>


<commit_before>$(function() {

  $( "#fecha" ).datepicker();
  $( "#fecha" ).datepicker( "option", "dateFormat", "yy-mm-dd" );

  // $( "#frmasistencia" ).on( "change", "#fecha", function() {
  //   $( "#date" ).val($( "#fecha" ).val());
  // });

$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var perfil = $("#tecnico1id").val();
      window.location.href = '/index.php/monedero?perfil='+perfil+'&fecha='+fecha;
});
/*
$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var dni = $("#tecnico1id").val();
      window.location.href = '/index.php/monedero?dni='+dni+'&fecha='+fecha;
});
*/

  $( "#frmasistencia" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmasistencia #fecha').val();
      var dni = $('#frmasistencia #dni').val();
      console.log(dni);
      var url =  '/index.php/asistencia/buscar/' + fecha+'&dni='+dni;
      window.location.href = '/index.php/asistencia?fecha='+fecha+'&dni='+dni;
    /*
      $.ajax({
        url : url,
        data : {fecha : fecha},
        type : 'GET',
        dataType : 'json',
        success : function(json) {
            // window.location.href = url;
            // history.pushState(null, "", url);
            //alert('okk');
            window.location.href = '/index.php/asistencia?fecha='+fecha;
            //$('#resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });*/

    $( "#date" ).val($( "#fecha" ).val());

  });

  $( "#grabar" ).on( "click", function() {
      var fecha = $('#fecha').val();
      var result = $('#result').val();

      if (result=='result2')
        var url = '/index.php/asistencia/grabar';
      else
        var url= '/index.php/asistencia/grabar_asistencia';

      var data = $('#frmasistencia').serialize();
      $.ajax({
        url : url,
        data : {data : data},
        type : 'POST',
        dataType : 'json',
        success : function(json) {
              alert('Asistencia guardada correctamente');
              window.location.href = '/index.php/asistencia?fecha='+fecha;
            // history.pushState(null, "", url);
            // $('#frmasistencia #resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });
  });

});
<commit_msg>billetera<commit_after>$(function() {

  $( "#fecha" ).datepicker();
  $( "#fecha" ).datepicker( "option", "dateFormat", "yy-mm-dd" );

  // $( "#frmasistencia" ).on( "change", "#fecha", function() {
  //   $( "#date" ).val($( "#fecha" ).val());
  // });

$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var perfil = $("#tecnico1id").val();
      window.location.href = '/index.php/monedero?perfil='+perfil+'&fecha='+fecha;
});
/*
$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var dni = $("#tecnico1id").val();
      window.location.href = '/index.php/monedero?dni='+dni+'&fecha='+fecha;
});
*/

  $( "#frmasistencia" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmasistencia #fecha').val();
      var dni = $('#frmasistencia #dni').val();
      console.log(dni);
      var url =  '/index.php/asistencia/buscar/' + fecha+'&dni='+dni;
      window.location.href = '/index.php/asistencia?fecha='+fecha+'&dni='+dni;
    /*
      $.ajax({
        url : url,
        data : {fecha : fecha},
        type : 'GET',
        dataType : 'json',
        success : function(json) {
            // window.location.href = url;
            // history.pushState(null, "", url);
            //alert('okk');
            window.location.href = '/index.php/asistencia?fecha='+fecha;
            //$('#resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });*/

    $( "#date" ).val($( "#fecha" ).val());

  });

  $( "#grabar" ).on( "click", function() {
      var fecha = $('#fecha').val();
      var result = $('#result').val();

      if (result=='result2')
        var url = '/index.php/asistencia/grabar';
      else
        var url= '/index.php/asistencia/grabar';

      var data = $('#frmasistencia').serialize();
      $.ajax({
        url : url,
        data : {data : data},
        type : 'POST',
        dataType : 'json',
        success : function(json) {
              alert('Asistencia guardada correctamente');
              window.location.href = '/index.php/asistencia?fecha='+fecha;
            // history.pushState(null, "", url);
            // $('#frmasistencia #resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });
  });

});
<|endoftext|>


<commit_before>Elm.Native.Color = {};
Elm.Native.Color.make = function(localRuntime) {
    localRuntime.Native = localRuntime.Native || {};
    localRuntime.Native.Color = localRuntime.Native.Color || {};
    if (localRuntime.Native.Color.values)
    {
        return localRuntime.Native.Color.values;
    }

    function toCss(c) {
        var format = '';
        var colors = '';
        if (c.ctor === 'RGBA')
	{
            format = 'rgb';
            colors = c._0 + ', ' + c._1 + ', ' + c._2;
        }
        else
        {
            format = 'hsl';
            colors = (c._0 * 180 / Math.PI) + ', ' +
                     (c._1 * 100) + '%, ' +
                     (c._2 * 100) + '%';
        }
        if (c._3 === 1)
        {
            return format + '(' + colors + ')';
        }
        else
        {
            return format + 'a(' + colors + ', ' + c._3 + ')';
        }
    }

    return localRuntime.Native.Color.values = {
        toCss:toCss
    };

};
<commit_msg>Fix weird indentation<commit_after>Elm.Native.Color = {};
Elm.Native.Color.make = function(localRuntime) {
    localRuntime.Native = localRuntime.Native || {};
    localRuntime.Native.Color = localRuntime.Native.Color || {};
    if (localRuntime.Native.Color.values)
    {
        return localRuntime.Native.Color.values;
    }

    function toCss(c) {
        var format = '';
        var colors = '';
        if (c.ctor === 'RGBA')
        {
            format = 'rgb';
            colors = c._0 + ', ' + c._1 + ', ' + c._2;
        }
        else
        {
            format = 'hsl';
            colors = (c._0 * 180 / Math.PI) + ', ' +
                     (c._1 * 100) + '%, ' +
                     (c._2 * 100) + '%';
        }
        if (c._3 === 1)
        {
            return format + '(' + colors + ')';
        }
        else
        {
            return format + 'a(' + colors + ', ' + c._3 + ')';
        }
    }

    return localRuntime.Native.Color.values = {
        toCss:toCss
    };

};
<|endoftext|>


<commit_before>
var hostnameCache = {};
var hostCache = {};

// Globals shared across pages
var HOST;

function getHostname(url) {
	var elem = document.createElement('a');
	elem.href = url;
	return elem.hostname;
}

function dnsLookup(hostname, callback) {
	var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.shodan.io/dns/resolve?key=MM72AkzHXdHpC8iP65VVEEVrJjp7zkgd&hostnames=' + hostname, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
        	try {
	            var data = JSON.parse(xhr.responseText);

	            if (data[hostname]) {
	            	callback(data[hostname]);
	            }
            }
	        catch(e) {
	        	// pass
	        }
        }
    }
    xhr.send();
}

function hostLookup(ip, callback) {
	var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.shodan.io/shodan/host/' + ip + '?key=MM72AkzHXdHpC8iP65VVEEVrJjp7zkgd&minify=true', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
        	try {
	            var host = JSON.parse(xhr.responseText);
	            if (!host.error) {
	            	callback(host);
	            }
            }
	        catch(e) {
	        	// pass
	        }
        }
    }
    xhr.send();
}

function updateHost(host, tabId) {
	chrome.browserAction.enable(tabId);

	chrome.browserAction.setBadgeText({
		'text': String(host.ports.length)
	});

	// Update the globals so the popup can access the info collected in the background
	HOST = host;
}

function getHost() {
	return HOST;
}

function updateBrowserAction(tabId, url) {
	var host = null;
	var hostname;

	// If the URL doesn't start with http or https then we won't go any further
	if (url.indexOf('http') === -1 && url.indexOf('https') === -1) {
		return;
	}

	hostname = getHostname(url);

	// Disable the browser action button until we know that the current
	// hostname has some data.
	chrome.browserAction.disable(tabId);
	chrome.browserAction.setBadgeText({
		text: ''
	});

	// If we're switching tabs or the URL is already in the cache, try to look up the host information
	// from the cache.
	if (hostnameCache[tabId] && hostnameCache[tabId] === hostname) {
		// We've previously looked up the Shodan host information for this hostname, so use it
		if (hostCache[tabId]) {
			updateHost(hostCache[tabId], tabId);
		}
	}
	else {
		// Resolve the hostname to its IP address, which then gets passed to the actual Shodan host lookup
		dnsLookup(hostname, function(ip) {
			hostLookup(ip, function(host) {
				// Make sure we got a response back for the right ip
				if (host.ip_str === ip) {
					// Update the hostname cache so we know when the browseraction needs to get updated
					hostnameCache[tabId] = hostname;
					hostCache[tabId] = host;

					updateHost(host, tabId);
				}
			})
		});
	}
};

function contextMenuHandler(info, tab) {
	var shodanUrl = 'https://www.shodan.io';
	var checkUrl = null;

	// The user has selected some text
	if (info.selectionText) {
		shodanUrl += '/search?query=' + encodeURI(info.selectionText);
	}
	else if (info.linkUrl) {
		checkUrl = info.linkUrl;
	}
	else if (info.pageUrl) {
		checkUrl = info.pageUrl;
	}
	else if (info.frameUrl) {
		checkUrl = info.frameUrl;
	}

	if (checkUrl !== null) {
		var hostname = getHostname(checkUrl);

		// Strip any prepending 'www.' if present
		if (hostname.indexOf('www.') === 0) {
			hostname = hostname.substr(4);
		}

		shodanUrl += '/search?query=hostname:' + encodeURI(hostname);
	}

	// If the user's selection changed the base URL then open a new tab
	if (shodanUrl != 'https://www.shodan.io') {
		chrome.tabs.create({
			'url': shodanUrl
		});
	}
}

/*
 * Listen for changes in the URL in any of the tabs.
 */
chrome.tabs.onUpdated.addListener(function (id, info, tab) {
	if (tab.status === 'loading') {
		updateBrowserAction(id, tab.url);
	}
});

chrome.tabs.onActivated.addListener(function (activeInfo) {
	if (activeInfo.tabId) {
		chrome.tabs.get(activeInfo.tabId, function (tab) {
			updateBrowserAction(tab.id, tab.url);
		});
	}
});

// Cleanup the variables when a tab is closed
chrome.tabs.onRemoved.addListener(function (id) {
	delete hostnameCache[id];
	delete hostCache[id];
});

// Set the button to disabled until we get some actual data
chrome.browserAction.disable();

chrome.browserAction.setBadgeBackgroundColor({
	color: '#000'
});

// Add the ability to search Shodan using the right-click/ context menu
chrome.contextMenus.create({
	'title': 'Search Shodan for link',
	'contexts': ['link'],
	'onclick': contextMenuHandler
});
chrome.contextMenus.create({
	'title': 'Search Shodan for current website',
	'contexts': ['page'],
	'onclick': contextMenuHandler
});
chrome.contextMenus.create({
	'title': 'Search Shodan for "%s"',
	'contexts': ['selection'],
	'onclick': contextMenuHandler
});
<commit_msg>Update API key<commit_after>
var hostnameCache = {};
var hostCache = {};

// Globals shared across pages
var HOST;

function getHostname(url) {
	var elem = document.createElement('a');
	elem.href = url;
	return elem.hostname;
}

function dnsLookup(hostname, callback) {
	var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.shodan.io/dns/resolve?key=WagM7oXeNhWvQWjd9ePx2buFiHv2phhq&hostnames=' + hostname, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
        	try {
	            var data = JSON.parse(xhr.responseText);

	            if (data[hostname]) {
	            	callback(data[hostname]);
	            }
            }
	        catch(e) {
	        	// pass
	        }
        }
    }
    xhr.send();
}

function hostLookup(ip, callback) {
	var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.shodan.io/shodan/host/' + ip + '?key=WagM7oXeNhWvQWjd9ePx2buFiHv2phhq&minify=true', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
        	try {
	            var host = JSON.parse(xhr.responseText);
	            if (!host.error) {
	            	callback(host);
	            }
            }
	        catch(e) {
	        	// pass
	        }
        }
    }
    xhr.send();
}

function updateHost(host, tabId) {
	chrome.browserAction.enable(tabId);

	chrome.browserAction.setBadgeText({
		'text': String(host.ports.length)
	});

	// Update the globals so the popup can access the info collected in the background
	HOST = host;
}

function getHost() {
	return HOST;
}

function updateBrowserAction(tabId, url) {
	var host = null;
	var hostname;

	// If the URL doesn't start with http or https then we won't go any further
	if (url.indexOf('http') === -1 && url.indexOf('https') === -1) {
		return;
	}

	hostname = getHostname(url);

	// Disable the browser action button until we know that the current
	// hostname has some data.
	chrome.browserAction.disable(tabId);
	chrome.browserAction.setBadgeText({
		text: ''
	});

	// If we're switching tabs or the URL is already in the cache, try to look up the host information
	// from the cache.
	if (hostnameCache[tabId] && hostnameCache[tabId] === hostname) {
		// We've previously looked up the Shodan host information for this hostname, so use it
		if (hostCache[tabId]) {
			updateHost(hostCache[tabId], tabId);
		}
	}
	else {
		// Resolve the hostname to its IP address, which then gets passed to the actual Shodan host lookup
		dnsLookup(hostname, function(ip) {
			hostLookup(ip, function(host) {
				// Make sure we got a response back for the right ip
				if (host.ip_str === ip) {
					// Update the hostname cache so we know when the browseraction needs to get updated
					hostnameCache[tabId] = hostname;
					hostCache[tabId] = host;

					updateHost(host, tabId);
				}
			})
		});
	}
};

function contextMenuHandler(info, tab) {
	var shodanUrl = 'https://www.shodan.io';
	var checkUrl = null;

	// The user has selected some text
	if (info.selectionText) {
		shodanUrl += '/search?query=' + encodeURI(info.selectionText);
	}
	else if (info.linkUrl) {
		checkUrl = info.linkUrl;
	}
	else if (info.pageUrl) {
		checkUrl = info.pageUrl;
	}
	else if (info.frameUrl) {
		checkUrl = info.frameUrl;
	}

	if (checkUrl !== null) {
		var hostname = getHostname(checkUrl);

		// Strip any prepending 'www.' if present
		if (hostname.indexOf('www.') === 0) {
			hostname = hostname.substr(4);
		}

		shodanUrl += '/search?query=hostname:' + encodeURI(hostname);
	}

	// If the user's selection changed the base URL then open a new tab
	if (shodanUrl != 'https://www.shodan.io') {
		chrome.tabs.create({
			'url': shodanUrl
		});
	}
}

/*
 * Listen for changes in the URL in any of the tabs.
 */
chrome.tabs.onUpdated.addListener(function (id, info, tab) {
	if (tab.status === 'loading') {
		updateBrowserAction(id, tab.url);
	}
});

chrome.tabs.onActivated.addListener(function (activeInfo) {
	if (activeInfo.tabId) {
		chrome.tabs.get(activeInfo.tabId, function (tab) {
			updateBrowserAction(tab.id, tab.url);
		});
	}
});

// Cleanup the variables when a tab is closed
chrome.tabs.onRemoved.addListener(function (id) {
	delete hostnameCache[id];
	delete hostCache[id];
});

// Set the button to disabled until we get some actual data
chrome.browserAction.disable();

chrome.browserAction.setBadgeBackgroundColor({
	color: '#000'
});

// Add the ability to search Shodan using the right-click/ context menu
chrome.contextMenus.create({
	'title': 'Search Shodan for link',
	'contexts': ['link'],
	'onclick': contextMenuHandler
});
chrome.contextMenus.create({
	'title': 'Search Shodan for current website',
	'contexts': ['page'],
	'onclick': contextMenuHandler
});
chrome.contextMenus.create({
	'title': 'Search Shodan for "%s"',
	'contexts': ['selection'],
	'onclick': contextMenuHandler
});
<|endoftext|>