<commit_before>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import {getTrackCSS, getTrackLeft, getTrackAnimateCSS} from './trackHelper';
import assign from 'object-assign';

var helpers = {
  // supposed to start autoplay of slides
  initialize: function (props) {
    const slickList = ReactDOM.findDOMNode(this.list);

    var slideCount = React.Children.count(props.children);
    var listWidth = this.getWidth(slickList);
    var trackWidth = this.getWidth(ReactDOM.findDOMNode(this.track));
    var slideWidth;

    if (!props.vertical) {
      var centerPaddingAdj = props.centerMode && (parseInt(props.centerPadding) * 2);
      if (props.centerPadding.slice(-1) === '%') {
        centerPaddingAdj *= listWidth / 100
      }
      slideWidth = Math.ceil((this.getWidth(ReactDOM.findDOMNode(this)) - centerPaddingAdj)/props.slidesToShow)
    } else {
      slideWidth = Math.ceil(this.getWidth(ReactDOM.findDOMNode(this)))
    }

    const slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
    const listHeight = slideHeight * props.slidesToShow;

    var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide;

    this.setState({
      slideCount,
      slideWidth,
      listWidth,
      trackWidth,
      currentSlide,
      slideHeight,
      listHeight,
    }, function () {
      // this reference isn't lost due to mixin
      var targetLeft = getTrackLeft(assign({
        slideIndex: this.state.currentSlide,
        trackRef: this.track
      }, props, this.state));
      // getCSS function needs previously set state
      var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state));

      this.setState({trackStyle: trackStyle});

      this.autoPlay(); // once we're set up, trigger the initial autoplay.
    });
  },
  update: function (props) {
    const slickList = ReactDOM.findDOMNode(this.list);
    // This method has mostly same code as initialize method.
    // Refactor it
    var slideCount = React.Children.count(props.children);
    var listWidth = this.getWidth(slickList);
    var trackWidth = this.getWidth(ReactDOM.findDOMNode(this.track));
    var slideWidth;

    if (!props.vertical) {
      var centerPaddingAdj = props.centerMode && (parseInt(props.centerPadding) * 2);
      if (props.centerPadding.slice(-1) === '%') {
        centerPaddingAdj *= listWidth / 100
      }
      slideWidth = Math.ceil((this.getWidth(ReactDOM.findDOMNode(this)) - centerPaddingAdj)/props.slidesToShow)
    } else {
      slideWidth = Math.ceil(this.getWidth(ReactDOM.findDOMNode(this)))
    }

    const slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
    const listHeight = slideHeight * props.slidesToShow;

    // pause slider if autoplay is set to false
    if(!props.autoplay) {
      this.pause();
    } else {
      this.autoPlay(props.autoplay);
    }

    const lazyLoadedList = this.state.lazyLoadedList
    let startIndex, endIndex
    if (props.centerMode) {
      startIndex = this.state.currentSlide - props.slidesToShow / 2
      endIndex = this.state.currentSlide + props.slidesToShow / 2
    } else {
      startIndex = this.state.currentSlide
      endIndex = this.state.currentSlide + props.slidesToShow
    }
    for (let slideIndex = startIndex; slideIndex < endIndex; slideIndex += 1) {
      if (lazyLoadedList.indexOf(slideIndex) < 0) {
        lazyLoadedList.push(slideIndex)
      }
    }

    this.setState({
      slideCount,
      slideWidth,
      listWidth,
      trackWidth,
      slideHeight,
      listHeight,
      lazyLoadedList
    }, function () {

      var targetLeft = getTrackLeft(assign({
        slideIndex: this.state.currentSlide,
        trackRef: this.track
      }, props, this.state));
      // getCSS function needs previously set state
      var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state));

      this.setState({trackStyle: trackStyle});
    });
  },
  getWidth: function getWidth(elem) {
    return elem && (elem.getBoundingClientRect().width || elem.offsetWidth) || 0;
  },
  getHeight(elem) {
    return elem && (elem.getBoundingClientRect().height || elem.offsetHeight) || 0;
  },
  adaptHeight: function () {
    if (this.props.adaptiveHeight) {
      var selector = '[data-index="' + this.state.currentSlide +'"]';
      if (this.list) {
        var slickList = ReactDOM.findDOMNode(this.list);
        var elem = slickList.querySelector(selector) || {};
        slickList.style.height = (elem.offsetHeight || 0) + 'px';
      }
    }
  },
  canGoNext: function (opts){
    var canGo = true;
    if (!opts.infinite) {
      if (opts.centerMode) {
        // check if current slide is last slide
        if (opts.currentSlide >= (opts.slideCount - 1)) {
          canGo = false;
        }
      } else {
        // check if all slides are shown in slider
        if (opts.slideCount <= opts.slidesToShow ||
          opts.currentSlide >= (opts.slideCount - opts.slidesToShow)) {
          canGo = false;
        }
      }
    }
    return canGo;
  },
  slideHandler: function (index) {
    // index is target slide index

    // Functionality of animateSlide and postSlide is merged into this function
    var animationTargetSlide, finalTargetSlide;
    var animationTargetLeft, finalTargetLeft;
    var callback;

    if (this.props.waitForAnimate && this.state.animating) {
      return;
    }

    if (this.props.fade) {
      finalTargetSlide = this.state.currentSlide;

      // Don't change slide if infinite=false and target slide is out of range
      if(this.props.infinite === false &&
        (index < 0 || index >= this.state.slideCount)) {
        return;
      }

      //  Shifting animationTargetSlide back into the range
      if (index < 0) {
        animationTargetSlide = index + this.state.slideCount;
      } else if (index >= this.state.slideCount) {
        animationTargetSlide = index - this.state.slideCount;
      } else {
        animationTargetSlide = index;
      }

      if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(animationTargetSlide) < 0) {
        this.setState({
          lazyLoadedList: this.state.lazyLoadedList.concat(animationTargetSlide)
        });
      }

      callback = () => {
        this.setState({
          animating: false
        });
        if (this.props.afterChange) {
          this.props.afterChange(animationTargetSlide);
        }
        delete this.animationEndCallback;
        if (this.props.fade) {
          const focusableSlide = ReactDOM.findDOMNode(this.track).children[animationTargetSlide]
          focusableSlide.focus()
        }
      };

      this.setState({
        animating: true,
        currentSlide: animationTargetSlide
      }, function () {
        this.animationEndCallback = setTimeout(callback, this.props.speed);
      });

      if (this.props.beforeChange) {
        this.props.beforeChange(this.state.currentSlide, animationTargetSlide);
      }

      this.autoPlay();
      return;
    }

    animationTargetSlide = index;

    /*
      @TODO: Make sure to leave no bug in the code below
      start: critical checkpoint
    */
    if (animationTargetSlide < 0) {
      if(this.props.infinite === false) {
        finalTargetSlide = 0;
      } else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
        finalTargetSlide = this.state.slideCount - (this.state.slideCount % this.props.slidesToScroll);
      } else {
        finalTargetSlide = this.state.slideCount + animationTargetSlide;
      }
    } else if (this.props.centerMode && animationTargetSlide >= this.state.slideCount) {
      if(this.props.infinite === false) {
        animationTargetSlide = this.state.slideCount - 1
        finalTargetSlide = this.state.slideCount - 1
      } else {
        animationTargetSlide = this.state.slideCount
        finalTargetSlide = 0
      }
    } else if (animationTargetSlide >= this.state.slideCount) {
      if(this.props.infinite === false) {
        finalTargetSlide = this.state.slideCount - this.props.slidesToShow;
      } else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
        finalTargetSlide = 0;
      } else {
        finalTargetSlide = animationTargetSlide - this.state.slideCount;
      }
    } else if (this.state.currentSlide + this.slidesToShow < this.state.slideCount && animationTargetSlide + this.props.slidesToShow >= this.state.slideCount) {
      if (this.props.infinite === false) {
        finalTargetSlide = this.state.slideCount - this.props.slidesToShow
      } else {
        if ((this.state.slideCount - animationTargetSlide) % this.props.slidesToScroll !== 0) {
          finalTargetSlide = this.state.slideCount - this.props.slidesToShow
        } else {
          finalTargetSlide = animationTargetSlide
        }
      }
    } else {
      finalTargetSlide = animationTargetSlide;
    }

    /*
      stop: critical checkpoint
    */

    animationTargetLeft = getTrackLeft(assign({
      slideIndex: animationTargetSlide,
      trackRef: this.track
    }, this.props, this.state));

    finalTargetLeft = getTrackLeft(assign({
      slideIndex: finalTargetSlide,
      trackRef: this.track
    }, this.props, this.state));

    if (this.props.infinite === false) {
      if (animationTargetLeft === finalTargetLeft) {
        animationTargetSlide = finalTargetSlide;
      }
      animationTargetLeft = finalTargetLeft;
    }

    if (this.props.beforeChange) {
      this.props.beforeChange(this.state.currentSlide, finalTargetSlide);
    }

    if (this.props.lazyLoad) {
      var slidesToLoad = [];
      let slideCount = this.state.slideCount
      for (var i = animationTargetSlide; i < animationTargetSlide + this.props.slidesToShow; i++ ) {
        if (this.state.lazyLoadedList.indexOf(i) < 0) {
          slidesToLoad.push(i)
        }
        if (i >= slideCount && this.state.lazyLoadedList.indexOf(i - slideCount) < 0) {
          slidesToLoad.push(i - slideCount)
        }
        if (i < 0 && this.state.lazyLoadedList.indexOf(i + slideCount) < 0) {
          slidesToLoad.push(i + slideCount)
        }
      }
      if (slidesToLoad.length > 0) {
        this.setState({
          lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad)
        });
      }
    }

    // Slide Transition happens here.
    // animated transition happens to target Slide and
    // non - animated transition happens to current Slide
    // If CSS transitions are false, directly go the current slide.

    if (this.props.useCSS === false) {
      this.setState({
        currentSlide: finalTargetSlide,
        trackStyle: getTrackCSS(assign({left: finalTargetLeft}, this.props, this.state))
      }, function () {
        if (this.props.afterChange) {
          this.props.afterChange(finalTargetSlide);
        }
      });

    } else {

      var nextStateChanges = {
        animating: false,
        currentSlide: finalTargetSlide,
        trackStyle: getTrackCSS(assign({left: finalTargetLeft}, this.props, this.state)),
        swipeLeft: null
      };
      callback = () => {
        this.setState(nextStateChanges, () => {
          if (this.props.afterChange) {
            this.props.afterChange(finalTargetSlide);
          }
          delete this.animationEndCallback;
        });
      };

      this.setState({
        animating: true,
        currentSlide: finalTargetSlide,
        trackStyle: getTrackAnimateCSS(assign({left: animationTargetLeft}, this.props, this.state))
      }, function () {
        this.animationEndCallback = setTimeout(callback, this.props.speed);
      });

    }

    this.autoPlay();
  },
  swipeDirection: function (touchObject) {
    var xDist, yDist, r, swipeAngle;

    xDist = touchObject.startX - touchObject.curX;
    yDist = touchObject.startY - touchObject.curY;
    r = Math.atan2(yDist, xDist);

    swipeAngle = Math.round(r * 180 / Math.PI);
    if (swipeAngle < 0) {
        swipeAngle = 360 - Math.abs(swipeAngle);
    }
    if ((swipeAngle <= 45) && (swipeAngle >= 0) || (swipeAngle <= 360) && (swipeAngle >= 315)) {
        return 'left';
    }
    if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
        return 'right';
    }
    if (this.props.verticalSwiping === true) {
      if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
        return 'down';
      } else {
        return 'up';
      }
    }

    return 'vertical';
  },
  play: function(){
    var nextIndex;

    // if (!this.state.mounted) {
    //   return false
    // }

    if (this.props.rtl) {
      nextIndex = this.state.currentSlide - this.props.slidesToScroll;
    } else {
      if (this.canGoNext(Object.assign({}, this.props,this.state))) {
        nextIndex = this.state.currentSlide + this.props.slidesToScroll;
      } else {
        return false;
      }
    }

    this.slideHandler(nextIndex);
  },
  autoPlay: function (autoplay=false) {
    if (this.state.autoPlayTimer) {
      clearTimeout(this.state.autoPlayTimer);
    }
    if (autoplay || this.props.autoplay) {
      this.setState({
        autoPlayTimer: setTimeout(this.play, this.props.autoplaySpeed)
      });
    }
  },
  pause: function () {
    if (this.state.autoPlayTimer) {
      clearTimeout(this.state.autoPlayTimer);
      this.setState({
        autoPlayTimer: null
      });
    }
  }
};

export default helpers;
<commit_msg>renamed autoPlayTimer to autoplayTimer and removed it from state<commit_after>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import {getTrackCSS, getTrackLeft, getTrackAnimateCSS} from './trackHelper';
import assign from 'object-assign';

var helpers = {
  // supposed to start autoplay of slides
  initialize: function (props) {
    const slickList = ReactDOM.findDOMNode(this.list);

    var slideCount = React.Children.count(props.children);
    var listWidth = this.getWidth(slickList);
    var trackWidth = this.getWidth(ReactDOM.findDOMNode(this.track));
    var slideWidth;

    if (!props.vertical) {
      var centerPaddingAdj = props.centerMode && (parseInt(props.centerPadding) * 2);
      if (props.centerPadding.slice(-1) === '%') {
        centerPaddingAdj *= listWidth / 100
      }
      slideWidth = Math.ceil((this.getWidth(ReactDOM.findDOMNode(this)) - centerPaddingAdj)/props.slidesToShow)
    } else {
      slideWidth = Math.ceil(this.getWidth(ReactDOM.findDOMNode(this)))
    }

    const slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
    const listHeight = slideHeight * props.slidesToShow;

    var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide;

    this.setState({
      slideCount,
      slideWidth,
      listWidth,
      trackWidth,
      currentSlide,
      slideHeight,
      listHeight,
    }, function () {
      // this reference isn't lost due to mixin
      var targetLeft = getTrackLeft(assign({
        slideIndex: this.state.currentSlide,
        trackRef: this.track
      }, props, this.state));
      // getCSS function needs previously set state
      var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state));

      this.setState({trackStyle: trackStyle});

      this.autoPlay(); // once we're set up, trigger the initial autoplay.
    });
  },
  update: function (props) {
    const slickList = ReactDOM.findDOMNode(this.list);
    // This method has mostly same code as initialize method.
    // Refactor it
    var slideCount = React.Children.count(props.children);
    var listWidth = this.getWidth(slickList);
    var trackWidth = this.getWidth(ReactDOM.findDOMNode(this.track));
    var slideWidth;

    if (!props.vertical) {
      var centerPaddingAdj = props.centerMode && (parseInt(props.centerPadding) * 2);
      if (props.centerPadding.slice(-1) === '%') {
        centerPaddingAdj *= listWidth / 100
      }
      slideWidth = Math.ceil((this.getWidth(ReactDOM.findDOMNode(this)) - centerPaddingAdj)/props.slidesToShow)
    } else {
      slideWidth = Math.ceil(this.getWidth(ReactDOM.findDOMNode(this)))
    }

    const slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
    const listHeight = slideHeight * props.slidesToShow;

    // pause slider if autoplay is set to false
    if(!props.autoplay) {
      this.pause();
    } else {
      this.autoPlay(props.autoplay);
    }

    const lazyLoadedList = this.state.lazyLoadedList
    let startIndex, endIndex
    if (props.centerMode) {
      startIndex = this.state.currentSlide - props.slidesToShow / 2
      endIndex = this.state.currentSlide + props.slidesToShow / 2
    } else {
      startIndex = this.state.currentSlide
      endIndex = this.state.currentSlide + props.slidesToShow
    }
    for (let slideIndex = startIndex; slideIndex < endIndex; slideIndex += 1) {
      if (lazyLoadedList.indexOf(slideIndex) < 0) {
        lazyLoadedList.push(slideIndex)
      }
    }

    this.setState({
      slideCount,
      slideWidth,
      listWidth,
      trackWidth,
      slideHeight,
      listHeight,
      lazyLoadedList
    }, function () {

      var targetLeft = getTrackLeft(assign({
        slideIndex: this.state.currentSlide,
        trackRef: this.track
      }, props, this.state));
      // getCSS function needs previously set state
      var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state));

      this.setState({trackStyle: trackStyle});
    });
  },
  getWidth: function getWidth(elem) {
    return elem && (elem.getBoundingClientRect().width || elem.offsetWidth) || 0;
  },
  getHeight(elem) {
    return elem && (elem.getBoundingClientRect().height || elem.offsetHeight) || 0;
  },
  adaptHeight: function () {
    if (this.props.adaptiveHeight) {
      var selector = '[data-index="' + this.state.currentSlide +'"]';
      if (this.list) {
        var slickList = ReactDOM.findDOMNode(this.list);
        var elem = slickList.querySelector(selector) || {};
        slickList.style.height = (elem.offsetHeight || 0) + 'px';
      }
    }
  },
  canGoNext: function (opts){
    var canGo = true;
    if (!opts.infinite) {
      if (opts.centerMode) {
        // check if current slide is last slide
        if (opts.currentSlide >= (opts.slideCount - 1)) {
          canGo = false;
        }
      } else {
        // check if all slides are shown in slider
        if (opts.slideCount <= opts.slidesToShow ||
          opts.currentSlide >= (opts.slideCount - opts.slidesToShow)) {
          canGo = false;
        }
      }
    }
    return canGo;
  },
  slideHandler: function (index) {
    // index is target slide index

    // Functionality of animateSlide and postSlide is merged into this function
    var animationTargetSlide, finalTargetSlide;
    var animationTargetLeft, finalTargetLeft;
    var callback;

    if (this.props.waitForAnimate && this.state.animating) {
      return;
    }

    if (this.props.fade) {
      finalTargetSlide = this.state.currentSlide;

      // Don't change slide if infinite=false and target slide is out of range
      if(this.props.infinite === false &&
        (index < 0 || index >= this.state.slideCount)) {
        return;
      }

      //  Shifting animationTargetSlide back into the range
      if (index < 0) {
        animationTargetSlide = index + this.state.slideCount;
      } else if (index >= this.state.slideCount) {
        animationTargetSlide = index - this.state.slideCount;
      } else {
        animationTargetSlide = index;
      }

      if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(animationTargetSlide) < 0) {
        this.setState({
          lazyLoadedList: this.state.lazyLoadedList.concat(animationTargetSlide)
        });
      }

      callback = () => {
        this.setState({
          animating: false
        });
        if (this.props.afterChange) {
          this.props.afterChange(animationTargetSlide);
        }
        delete this.animationEndCallback;
        if (this.props.fade) {
          const focusableSlide = ReactDOM.findDOMNode(this.track).children[animationTargetSlide]
          focusableSlide.focus()
        }
      };

      this.setState({
        animating: true,
        currentSlide: animationTargetSlide
      }, function () {
        this.animationEndCallback = setTimeout(callback, this.props.speed);
      });

      if (this.props.beforeChange) {
        this.props.beforeChange(this.state.currentSlide, animationTargetSlide);
      }

      this.autoPlay();
      return;
    }

    animationTargetSlide = index;

    /*
      @TODO: Make sure to leave no bug in the code below
      start: critical checkpoint
    */
    if (animationTargetSlide < 0) {
      if(this.props.infinite === false) {
        finalTargetSlide = 0;
      } else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
        finalTargetSlide = this.state.slideCount - (this.state.slideCount % this.props.slidesToScroll);
      } else {
        finalTargetSlide = this.state.slideCount + animationTargetSlide;
      }
    } else if (this.props.centerMode && animationTargetSlide >= this.state.slideCount) {
      if(this.props.infinite === false) {
        animationTargetSlide = this.state.slideCount - 1
        finalTargetSlide = this.state.slideCount - 1
      } else {
        animationTargetSlide = this.state.slideCount
        finalTargetSlide = 0
      }
    } else if (animationTargetSlide >= this.state.slideCount) {
      if(this.props.infinite === false) {
        finalTargetSlide = this.state.slideCount - this.props.slidesToShow;
      } else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
        finalTargetSlide = 0;
      } else {
        finalTargetSlide = animationTargetSlide - this.state.slideCount;
      }
    } else if (this.state.currentSlide + this.slidesToShow < this.state.slideCount && animationTargetSlide + this.props.slidesToShow >= this.state.slideCount) {
      if (this.props.infinite === false) {
        finalTargetSlide = this.state.slideCount - this.props.slidesToShow
      } else {
        if ((this.state.slideCount - animationTargetSlide) % this.props.slidesToScroll !== 0) {
          finalTargetSlide = this.state.slideCount - this.props.slidesToShow
        } else {
          finalTargetSlide = animationTargetSlide
        }
      }
    } else {
      finalTargetSlide = animationTargetSlide;
    }

    /*
      stop: critical checkpoint
    */

    animationTargetLeft = getTrackLeft(assign({
      slideIndex: animationTargetSlide,
      trackRef: this.track
    }, this.props, this.state));

    finalTargetLeft = getTrackLeft(assign({
      slideIndex: finalTargetSlide,
      trackRef: this.track
    }, this.props, this.state));

    if (this.props.infinite === false) {
      if (animationTargetLeft === finalTargetLeft) {
        animationTargetSlide = finalTargetSlide;
      }
      animationTargetLeft = finalTargetLeft;
    }

    if (this.props.beforeChange) {
      this.props.beforeChange(this.state.currentSlide, finalTargetSlide);
    }

    if (this.props.lazyLoad) {
      var slidesToLoad = [];
      let slideCount = this.state.slideCount
      for (var i = animationTargetSlide; i < animationTargetSlide + this.props.slidesToShow; i++ ) {
        if (this.state.lazyLoadedList.indexOf(i) < 0) {
          slidesToLoad.push(i)
        }
        if (i >= slideCount && this.state.lazyLoadedList.indexOf(i - slideCount) < 0) {
          slidesToLoad.push(i - slideCount)
        }
        if (i < 0 && this.state.lazyLoadedList.indexOf(i + slideCount) < 0) {
          slidesToLoad.push(i + slideCount)
        }
      }
      if (slidesToLoad.length > 0) {
        this.setState({
          lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad)
        });
      }
    }

    // Slide Transition happens here.
    // animated transition happens to target Slide and
    // non - animated transition happens to current Slide
    // If CSS transitions are false, directly go the current slide.

    if (this.props.useCSS === false) {
      this.setState({
        currentSlide: finalTargetSlide,
        trackStyle: getTrackCSS(assign({left: finalTargetLeft}, this.props, this.state))
      }, function () {
        if (this.props.afterChange) {
          this.props.afterChange(finalTargetSlide);
        }
      });

    } else {

      var nextStateChanges = {
        animating: false,
        currentSlide: finalTargetSlide,
        trackStyle: getTrackCSS(assign({left: finalTargetLeft}, this.props, this.state)),
        swipeLeft: null
      };
      callback = () => {
        this.setState(nextStateChanges, () => {
          if (this.props.afterChange) {
            this.props.afterChange(finalTargetSlide);
          }
          delete this.animationEndCallback;
        });
      };

      this.setState({
        animating: true,
        currentSlide: finalTargetSlide,
        trackStyle: getTrackAnimateCSS(assign({left: animationTargetLeft}, this.props, this.state))
      }, function () {
        this.animationEndCallback = setTimeout(callback, this.props.speed);
      });

    }

    this.autoPlay();
  },
  swipeDirection: function (touchObject) {
    var xDist, yDist, r, swipeAngle;

    xDist = touchObject.startX - touchObject.curX;
    yDist = touchObject.startY - touchObject.curY;
    r = Math.atan2(yDist, xDist);

    swipeAngle = Math.round(r * 180 / Math.PI);
    if (swipeAngle < 0) {
        swipeAngle = 360 - Math.abs(swipeAngle);
    }
    if ((swipeAngle <= 45) && (swipeAngle >= 0) || (swipeAngle <= 360) && (swipeAngle >= 315)) {
        return 'left';
    }
    if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
        return 'right';
    }
    if (this.props.verticalSwiping === true) {
      if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
        return 'down';
      } else {
        return 'up';
      }
    }

    return 'vertical';
  },
  play: function(){
    var nextIndex;

    // if (!this.state.mounted) {
    //   return false
    // }

    if (this.props.rtl) {
      nextIndex = this.state.currentSlide - this.props.slidesToScroll;
    } else {
      if (this.canGoNext(Object.assign({}, this.props,this.state))) {
        nextIndex = this.state.currentSlide + this.props.slidesToScroll;
      } else {
        return false;
      }
    }

    this.slideHandler(nextIndex);
  },
  autoPlay: function (autoplay=false) {
    if (this.autoplayTimer) {
      clearTimeout(this.autoplayTimer)
    }
    if (autoplay || this.props.autoplay) {
      this.autoplayTimer = setTimeout(this.play, this.props.autoplaySpeed)
    }
  },
  pause: function () {
    if (this.autoplayTimer) {
      clearTimeout(this.autoplayTimer)
      this.autoplayTimer = null
    }
  }
};

export default helpers;
<|endoftext|>


<commit_before>// At max, each shard should have ~2500 servers
// This is used for when you get your bot on a ton of servers.

const Discord = require("discord.js");
const Manager = new Discord.ShardingManager("./swgohBot.js");   // Tell it what the main file we'd otherwise run the bot with is
Manager.spawn(5);   // Tell it that we want 5 shards (Approx. 1100 servers per shard)

<commit_msg>Update the sharding file to use the config<commit_after>// At max, each shard can have 2500 servers
const config = require("./config.js");

const Discord = require("discord.js");
const Manager = new Discord.ShardingManager("./swgohBot.js",{
    totalShards: config.shardCount  // Tell it how many shards we want (Approx. 1100 servers per shard)
});
Manager.spawn();

Manager.on("launch", (shard) => {
    console.log(`Launching Shard ${shard.id} (${shard.id + 1}/${Manager.totalShards})`);
});
<|endoftext|>


<commit_before>/**
 * background.js
 */

/* shared */
import { throwErr } from './common.js';
import {
  extractClickedData, handleActiveTab, handleCmd, handleMsg, handleUpdatedTab,
  setVars, startup
} from './main.js';
import { handleMenusOnShown } from './menu.js';

/* api */
const { commands, runtime, storage, tabs } = browser;
const menus = browser.menus || browser.contextMenus;

/* listeners */
commands.onCommand.addListener(cmd =>
  handleCmd(cmd).catch(throwErr)
);
menus.onClicked.addListener((info, tab) =>
  extractClickedData(info, tab).catch(throwErr)
);
menus.onShown?.addListener((info, tab) =>
  handleMenusOnShown(info, tab).catch(throwErr)
);
storage.onChanged.addListener(data =>
  setVars(data).catch(throwErr)
);
runtime.onInstalled.addListener(() => startup().catch(throwErr));
runtime.onMessage.addListener((msg, sender) =>
  handleMsg(msg, sender).catch(throwErr)
);
runtime.onStartup.addListener(() => startup().catch(throwErr));
tabs.onActivated.addListener(info =>
  handleActiveTab(info).catch(throwErr)
);
tabs.onUpdated.addListener((tabId, info, tab) =>
  handleUpdatedTab(tabId, info, tab).catch(throwErr)
);
<commit_msg>Update background.js<commit_after>/**
 * background.js
 */

/* shared */
import { throwErr } from './common.js';
import {
  extractClickedData, handleActiveTab, handleCmd, handleMsg, handleUpdatedTab,
  setVars, startup
} from './main.js';
import { handleMenusOnShown } from './menu.js';

/* api */
const { commands, runtime, storage, tabs } = browser;
const menus = browser.menus || browser.contextMenus;

/* listeners */
commands.onCommand.addListener(cmd =>
  handleCmd(cmd).catch(throwErr)
);
menus.onClicked.addListener((info, tab) =>
  extractClickedData(info, tab).catch(throwErr)
);
menus.onShown?.addListener((info, tab) =>
  handleMenusOnShown(info, tab).catch(throwErr)
);
storage.onChanged.addListener((data, area) =>
  setVars(data, area).catch(throwErr)
);
runtime.onInstalled.addListener(() => startup().catch(throwErr));
runtime.onMessage.addListener((msg, sender) =>
  handleMsg(msg, sender).catch(throwErr)
);
runtime.onStartup.addListener(() => startup().catch(throwErr));
tabs.onActivated.addListener(info =>
  handleActiveTab(info).catch(throwErr)
);
tabs.onUpdated.addListener((tabId, info, tab) =>
  handleUpdatedTab(tabId, info, tab).catch(throwErr)
);
<|endoftext|>


<commit_before>var config = {};

config.data_file = "data/somefile.csv";
config.column_title = "Some_Column";

config.map_height = "400px";
config.map_width = "800px";

config.color_scale = "blue";
config.color_multiplier = 5;
<commit_msg>Update config.js<commit_after>var config = {};

config.data_file = "data/population.csv";
config.column_title = "Population";

config.map_height = "400px";
config.map_width = "800px";

config.color_scale = "blue";
config.color_multiplier = 5;
<|endoftext|>


<commit_before>// TODO: this file will contain system helpers.<commit_msg>Various methods added to system.js.<commit_after>var os = require('os');
var fs = require('fs');

// TODO: this file will contain system helpers.

// Determines whether system functionality has been initialized.
var initialized = false;

// Ensures that the system-related functionality has been initialized.
var init = exports.init = function init() {
    if (initialized) return;
    initializeTempStorage();
    initialized = true;
};

// Sets up the temp storage if it's not there.
function initializeTempStorage() {
    var path = os.tmpdir() + '/' + tempStorageName();
    fs.mkdirSync(path);
}

// Gets a name for the temp storage folder. This is a deterministic name,
// made from the pid, such as 'avisynth.js-1234'.
function tempStorageName() {
    return 'avisynth.js-' + process.pid;
}
<|endoftext|>


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

var maptalks;

var nodeEnv = typeof module !== 'undefined' && module.exports;
if (nodeEnv)  {
    maptalks = require('maptalks');
} else {
    maptalks = window.maptalks;
}

maptalks.HeatLayer = maptalks.Layer.extend({
    options: {
        'renderer' : 'canvas'
    },

    initialize : function(id, heats, options) {
        this.setId(id);
        this._heats = heats;
        maptalks.Util.setOptions(this, options);
    },

    getData:function() {
        return this._heats;
    },

    setData : function(heats) {
        this._heats = heats;
        return this._redraw();
    },

    addPoint : function(heat) {
        this._heats.push(heat);
        return this._redraw();
    },

    redraw : function() {
        this._getRenderer.render();
        return this;
    },

    isEmpty:function() {
        if (!this._heats || !this._heats.length) {
            return true;
        }
        return false;
    }

});

/**
 * Export the HeatLayer's profile JSON.
 * @return {Object} layer's profile JSON
 */
maptalks.HeatLayer.prototype.toJSON=function() {
    var profile = {
        "type"      : 'HeatLayer',
        "id"        : this.getId(),
        "options"   : this.config(),
        "data"      : this.getData()
    };
    return profile;
}

/**
 * Reproduce a HeatLayer from layer's profile JSON.
 * @param  {Object} layerJSON - layer's profile JSON
 * @return {maptalks.HeatLayer}
 * @static
 * @private
 * @function
 */
maptalks.HeatLayer._fromJSON=function(layerJSON) {
    if (!layerJSON || layerJSON['type'] !== 'HeatLayer') {return null;}
    return new maptalks.HeatLayer(layerJSON['id'], layerJSON['data'], layerJSON['options']);
}

maptalks.Util.extend(maptalks.HeatLayer, maptalks.Renderable);

maptalks.renderer.heatlayer = {};

maptalks.renderer.heatlayer.Canvas=maptalks.renderer.Canvas.extend({

    initialize:function(layer) {
        this._layer = layer;
        this._registerEvents();
    },

    render:function() {
        var map = this.getMap();
        if (!map) {
            return;
        }
        if (!this._layer.isVisible() || this._layer.isEmpty()) {
            this._fireLoadedEvent();
            return;
        }
        var layer = this.getLayer();
        var viewExtent = map._getViewExtent();
        var maskViewExtent = this._prepareCanvas(viewExtent);
        if (maskViewExtent) {
            //out of layer mask
            if (!maskViewExtent.intersects(viewExtent)) {
                this._fireLoadedEvent();
                return;
            }
            viewExtent = viewExtent.intersection(maskViewExtent);
        }
        var viewMin = viewExtent.getMin();

        if (!this._heater) {
            this._heater = simpleheat(this._canvas);
            this._heater.radius(layer.options['radius'] || this._heater.defaultRadius, layer.options['blur']);
        }
        this._canvasFullExtent = viewExtent;
        //a cache of heat points' viewpoints.
        if (!this._heatViews) {
            this._heatViews = [];
        }

        var heats = layer._heats;
        var data = [],
            r = this._heater._r,
            size = map.getSize(),
            heatExtent = viewExtent.expand(r),
            max = layer.options['max'] === undefined ? 1 : layer.options['max'],
            maxZoom = maptalks.Util.isNil(layer.options['maxZoom']) ? map.getMaxZoom() : layer.options['maxZoom'],
            v = 1 / Math.pow(2, Math.max(0, Math.min(maxZoom - map.getZoom(), 12))),
            cellSize = r / 2,
            grid = [],
            panePos = map.offsetPlatform(),
            offsetX = panePos.x % cellSize,
            offsetY = panePos.y % cellSize,
            i, len, heat, p, alt, cell, x, y, j, len2, k;
        // console.time('process');
        for (i = 0, len = heats.length; i < len; i++) {
            heat = heats[i];
            if (!this._heatViews[i]) {
                this._heatViews[i] = map.coordinateToViewPoint(new maptalks.Coordinate(heat[0], heat[1]));
            }
            p = this._heatViews[i];
            if (heatExtent.contains(p)) {
                x = Math.floor((p.x - viewMin.x - offsetX) / cellSize) + 2;
                y = Math.floor((p.y - viewMin.y - offsetY) / cellSize) + 2;

                alt =
                    heat.alt !== undefined ? heat.alt :
                    heat[2] !== undefined ? +heat[2] : 1;
                k = alt * v;

                grid[y] = grid[y] || [];
                cell = grid[y][x];

                if (!cell) {
                    grid[y][x] = [p.x - viewMin.x, p.y - viewMin.y, k];

                } else {
                    cell[0] = (cell[0] * cell[2] + (p.x - viewMin.x) * k) / (cell[2] + k); // x
                    cell[1] = (cell[1] * cell[2] + (p.y - viewMin.y)* k) / (cell[2] + k); // y
                    cell[2] += k; // cumulated intensity value
                }
            }
        }
        for (i = 0, len = grid.length; i < len; i++) {
            if (grid[i]) {
                for (j = 0, len2 = grid[i].length; j < len2; j++) {
                    cell = grid[i][j];
                    if (cell) {
                        data.push([
                            Math.round(cell[0]),
                            Math.round(cell[1]),
                            Math.min(cell[2], max)
                        ]);
                    }
                }
            }
        }
        // console.timeEnd('process');

        // console.time('draw ' + data.length);
        this._heater.data(data).draw(layer.options['minOpacity']);
        // console.timeEnd('draw ' + data.length);
        //
        this._fireLoadedEvent();
        this._requestMapToRender();
    },

    getCanvasImage:function() {
        if (!this._canvasFullExtent || this._layer.isEmpty()) {
            return null;
        }
        var size = this._canvasFullExtent.getSize();
        var point = this._canvasFullExtent.getMin();
        return {'image':this._canvas,'layer':this._layer,'point':this.getMap().viewPointToContainerPoint(point),'size':size};
    },

    _registerEvents:function() {
        var map = this.getMap();
        map.on('_moveend _zoomstart _zoomend _resize',this._onMapEvent,this);
    },

    _onMapEvent:function(param) {
        if (param['type'] === '_zoomend') {
            delete this._heatViews;
            this.render();
        } else if (param['type'] === '_moveend') {
            this.render();
        } else if (param['type'] === '_resize') {
            this._resizeCanvas();
            this._heater._width  = this._canvas.width;
            this._heater._height = this._canvas.height;
            this.render();
        }
    }
});

maptalks.HeatLayer.registerRenderer('canvas', maptalks.renderer.heatlayer.Canvas);

/*
 (c) 2014, Vladimir Agafonkin
 simpleheat, a tiny JavaScript library for drawing heatmaps with Canvas
 https://github.com/mourner/simpleheat
*/
function simpleheat(canvas) {
    if (!(this instanceof simpleheat)) return new simpleheat(canvas);

    this._canvas = canvas = typeof canvas === 'string' ? document.getElementById(canvas) : canvas;

    this._ctx = canvas.getContext('2d');
    this._width = canvas.width;
    this._height = canvas.height;

    this._max = 1;
    this._data = [];
}

simpleheat.prototype = {

    defaultRadius: 25,

    defaultGradient: {
        0.4: 'blue',
        0.6: 'cyan',
        0.7: 'lime',
        0.8: 'yellow',
        1.0: 'red'
    },

    data: function (data) {
        this._data = data;
        return this;
    },

    max: function (max) {
        this._max = max;
        return this;
    },

    add: function (point) {
        this._data.push(point);
        return this;
    },

    clear: function () {
        this._data = [];
        return this;
    },

    radius: function (r, blur) {
        blur = blur === undefined ? 15 : blur;

        // create a grayscale blurred circle image that we'll use for drawing points
        var circle = this._circle = document.createElement('canvas'),
            ctx = circle.getContext('2d'),
            r2 = this._r = r + blur;

        circle.width = circle.height = r2 * 2;

        ctx.shadowOffsetX = ctx.shadowOffsetY = r2 * 2;
        ctx.shadowBlur = blur;
        ctx.shadowColor = 'black';

        ctx.beginPath();
        ctx.arc(-r2, -r2, r, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fill();

        return this;
    },

    resize: function () {
        this._width = this._canvas.width;
        this._height = this._canvas.height;
    },

    gradient: function (grad) {
        // create a 256x1 gradient that we'll use to turn a grayscale heatmap into a colored one
        var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            gradient = ctx.createLinearGradient(0, 0, 0, 256);

        canvas.width = 1;
        canvas.height = 256;

        for (var i in grad) {
            gradient.addColorStop(i, grad[i]);
        }

        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, 1, 256);

        this._grad = ctx.getImageData(0, 0, 1, 256).data;

        return this;
    },

    draw: function (minOpacity) {
        if (!this._circle) this.radius(this.defaultRadius);
        if (!this._grad) this.gradient(this.defaultGradient);

        var ctx = this._ctx;

        ctx.clearRect(0, 0, this._width, this._height);

        // draw a grayscale heatmap by putting a blurred circle at each data point
        for (var i = 0, len = this._data.length, p; i < len; i++) {
            p = this._data[i];
            ctx.globalAlpha = Math.max(p[2] / this._max, minOpacity === undefined ? 0.05 : minOpacity);
            ctx.drawImage(this._circle, p[0] - this._r, p[1] - this._r);
        }

        // colorize the heatmap, using opacity value of each pixel to get the right color from our gradient
        var colored = ctx.getImageData(0, 0, this._width, this._height);
        this._colorize(colored.data, this._grad);
        ctx.putImageData(colored, 0, 0);

        return this;
    },

    _colorize: function (pixels, gradient) {
        for (var i = 0, len = pixels.length, j; i < len; i += 4) {
            j = pixels[i + 3] * 4; // get gradient color from opacity value

            if (j) {
                pixels[i] = gradient[j];
                pixels[i + 1] = gradient[j + 1];
                pixels[i + 2] = gradient[j + 2];
            }
        }
    }
};

if (nodeEnv) {
    exports = module.exports = maptalks.HeatLayer;
}
})();
<commit_msg>node it<commit_after>
(function() {
"use strict";

var maptalks;

var nodeEnv = typeof module !== 'undefined' && module.exports;
if (nodeEnv)  {
    maptalks = require('maptalks');
} else {
    maptalks = window.maptalks;
}

maptalks.HeatLayer = maptalks.Layer.extend({
    options: {
        'renderer' : 'canvas'
    },

    initialize : function(id, heats, options) {
        this.setId(id);
        this._heats = heats;
        maptalks.Util.setOptions(this, options);
    },

    getData:function() {
        return this._heats;
    },

    setData : function(heats) {
        this._heats = heats;
        return this.redraw();
    },

    addPoint : function(heat) {
        this._heats.push(heat);
        return this.redraw();
    },

    redraw : function() {
        this._getRenderer().render();
        return this;
    },

    isEmpty:function() {
        if (!this._heats || !this._heats.length) {
            return true;
        }
        return false;
    },

    _getHeatRadius:function() {
        if (!this._getRenderer()) {
            return null;
        }
        return this._getRenderer()._heatRadius;
    }
});

/**
 * Export the HeatLayer's profile JSON.
 * @return {Object} layer's profile JSON
 */
maptalks.HeatLayer.prototype.toJSON=function(options) {
    if (!options) {
        options = {};
    }
    var profile = {
        "type"      : 'HeatLayer',
        "id"        : this.getId(),
        "options"   : this.config()
    };
    var data = this.getData();
    if (options['clipExtent']) {
        var clipExtent = new maptalks.Extent(options['clipExtent']);
        var r = this._getHeatRadius();
        if (r) {
            clipExtent = clipExtent._expand(r);
        }
        var clipped = [];
        for (var i = 0, len = data.length; i < len; i++) {
            if (clipExtent.contains(new maptalks.Coordinate(data[i][0], data[i][1]))) {
                clipped.push(data[i]);
            }
        }
        profile['data'] = clipped;
    } else {
        profile['data'] = data;
    }

    return profile;
}

/**
 * Reproduce a HeatLayer from layer's profile JSON.
 * @param  {Object} layerJSON - layer's profile JSON
 * @return {maptalks.HeatLayer}
 * @static
 * @private
 * @function
 */
maptalks.HeatLayer._fromJSON=function(layerJSON) {
    if (!layerJSON || layerJSON['type'] !== 'HeatLayer') {return null;}
    return new maptalks.HeatLayer(layerJSON['id'], layerJSON['data'], layerJSON['options']);
}

maptalks.Util.extend(maptalks.HeatLayer, maptalks.Renderable);

maptalks.renderer.heatlayer = {};

maptalks.renderer.heatlayer.Canvas=maptalks.renderer.Canvas.extend({

    initialize:function(layer) {
        this._layer = layer;
        this._registerEvents();
    },

    render:function() {
        var map = this.getMap();
        if (!map) {
            return;
        }
        if (!this._layer.isVisible() || this._layer.isEmpty()) {
            this._fireLoadedEvent();
            return;
        }
        var layer = this.getLayer();
        var viewExtent = map._getViewExtent();
        var maskViewExtent = this._prepareCanvas(viewExtent);
        if (maskViewExtent) {
            //out of layer mask
            if (!maskViewExtent.intersects(viewExtent)) {
                this._fireLoadedEvent();
                return;
            }
            viewExtent = viewExtent.intersection(maskViewExtent);
        }
        var viewMin = viewExtent.getMin();

        if (!this._heater) {
            this._heater = simpleheat(this._canvas);
            this._heater.radius(layer.options['radius'] || this._heater.defaultRadius, layer.options['blur']);
        }
        this._canvasFullExtent = viewExtent;
        //a cache of heat points' viewpoints.
        if (!this._heatViews) {
            this._heatViews = [];
        }

        var heats = layer._heats;
        var data = [],
            r = this._heater._r,
            size = map.getSize(),
            heatExtent = viewExtent.expand(r),
            max = layer.options['max'] === undefined ? 1 : layer.options['max'],
            maxZoom = maptalks.Util.isNil(layer.options['maxZoom']) ? map.getMaxZoom() : layer.options['maxZoom'],
            v = 1 / Math.pow(2, Math.max(0, Math.min(maxZoom - map.getZoom(), 12))),
            cellSize = r / 2,
            grid = [],
            panePos = map.offsetPlatform(),
            offsetX = panePos.x % cellSize,
            offsetY = panePos.y % cellSize,
            i, len, heat, p, alt, cell, x, y, j, len2, k;

        this._heatRadius = r;
        // console.time('process');
        for (i = 0, len = heats.length; i < len; i++) {
            heat = heats[i];
            if (!this._heatViews[i]) {
                this._heatViews[i] = map.coordinateToViewPoint(new maptalks.Coordinate(heat[0], heat[1]));
            }
            p = this._heatViews[i];
            if (heatExtent.contains(p)) {
                x = Math.floor((p.x - viewMin.x - offsetX) / cellSize) + 2;
                y = Math.floor((p.y - viewMin.y - offsetY) / cellSize) + 2;

                alt =
                    heat.alt !== undefined ? heat.alt :
                    heat[2] !== undefined ? +heat[2] : 1;
                k = alt * v;

                grid[y] = grid[y] || [];
                cell = grid[y][x];

                if (!cell) {
                    grid[y][x] = [p.x - viewMin.x, p.y - viewMin.y, k];

                } else {
                    cell[0] = (cell[0] * cell[2] + (p.x - viewMin.x) * k) / (cell[2] + k); // x
                    cell[1] = (cell[1] * cell[2] + (p.y - viewMin.y)* k) / (cell[2] + k); // y
                    cell[2] += k; // cumulated intensity value
                }
            }
        }
        for (i = 0, len = grid.length; i < len; i++) {
            if (grid[i]) {
                for (j = 0, len2 = grid[i].length; j < len2; j++) {
                    cell = grid[i][j];
                    if (cell) {
                        data.push([
                            Math.round(cell[0]),
                            Math.round(cell[1]),
                            Math.min(cell[2], max)
                        ]);
                    }
                }
            }
        }
        // console.timeEnd('process');

        // console.time('draw ' + data.length);
        this._heater.data(data).draw(layer.options['minOpacity']);
        // console.timeEnd('draw ' + data.length);
        //
        this._fireLoadedEvent();
        this._requestMapToRender();
    },

    getCanvasImage:function() {
        if (!this._canvasFullExtent || this._layer.isEmpty()) {
            return null;
        }
        var size = this._canvasFullExtent.getSize();
        var point = this._canvasFullExtent.getMin();
        return {'image':this._canvas,'layer':this._layer,'point':this.getMap().viewPointToContainerPoint(point),'size':size};
    },

    _registerEvents:function() {
        var map = this.getMap();
        map.on('_moveend _zoomstart _zoomend _resize',this._onMapEvent,this);
    },

    _onMapEvent:function(param) {
        if (param['type'] === '_zoomend') {
            delete this._heatViews;
            this.render();
        } else if (param['type'] === '_moveend') {
            this.render();
        } else if (param['type'] === '_resize') {
            this._resizeCanvas();
            this._heater._width  = this._canvas.width;
            this._heater._height = this._canvas.height;
            this.render();
        }
    }
});

maptalks.HeatLayer.registerRenderer('canvas', maptalks.renderer.heatlayer.Canvas);

/*
 (c) 2014, Vladimir Agafonkin
 simpleheat, a tiny JavaScript library for drawing heatmaps with Canvas
 https://github.com/mourner/simpleheat
*/
function simpleheat(canvas) {
    if (!(this instanceof simpleheat)) return new simpleheat(canvas);

    this._canvas = canvas = ( typeof canvas === 'string' && typeof document !== 'undefined' ) ? document.getElementById(canvas) : canvas;

    this._ctx = canvas.getContext('2d');
    this._width = canvas.width;
    this._height = canvas.height;

    this._max = 1;
    this._data = [];
}

simpleheat.prototype = {

    defaultRadius: 25,

    defaultGradient: {
        0.4: 'blue',
        0.6: 'cyan',
        0.7: 'lime',
        0.8: 'yellow',
        1.0: 'red'
    },

    data: function (data) {
        this._data = data;
        return this;
    },

    max: function (max) {
        this._max = max;
        return this;
    },

    add: function (point) {
        this._data.push(point);
        return this;
    },

    clear: function () {
        this._data = [];
        return this;
    },

    radius: function (r, blur) {
        blur = blur === undefined ? 15 : blur;

        // create a grayscale blurred circle image that we'll use for drawing points
        var circle = this._circle = this._createCanvas(),
            ctx = circle.getContext('2d'),
            r2 = this._r = r + blur;

        circle.width = circle.height = r2 * 2;

        ctx.shadowOffsetX = ctx.shadowOffsetY = r2 * 2;
        ctx.shadowBlur = blur;
        ctx.shadowColor = 'black';

        ctx.beginPath();
        ctx.arc(-r2, -r2, r, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fill();

        return this;
    },

    resize: function () {
        this._width = this._canvas.width;
        this._height = this._canvas.height;
    },

    gradient: function (grad) {
        // create a 256x1 gradient that we'll use to turn a grayscale heatmap into a colored one
        var canvas = this._createCanvas(),
            ctx = canvas.getContext('2d'),
            gradient = ctx.createLinearGradient(0, 0, 0, 256);

        canvas.width = 1;
        canvas.height = 256;

        for (var i in grad) {
            gradient.addColorStop(parseFloat(i), grad[i]);
        }

        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, 1, 256);

        this._grad = ctx.getImageData(0, 0, 1, 256).data;

        return this;
    },

    draw: function (minOpacity) {
        if (!this._circle) this.radius(this.defaultRadius);
        if (!this._grad) this.gradient(this.defaultGradient);

        var ctx = this._ctx;

        ctx.clearRect(0, 0, this._width, this._height);

        // draw a grayscale heatmap by putting a blurred circle at each data point
        for (var i = 0, len = this._data.length, p; i < len; i++) {
            p = this._data[i];
            ctx.globalAlpha = Math.max(p[2] / this._max, minOpacity === undefined ? 0.05 : minOpacity);
            ctx.drawImage(this._circle, p[0] - this._r, p[1] - this._r);
        }

        // colorize the heatmap, using opacity value of each pixel to get the right color from our gradient
        var colored = ctx.getImageData(0, 0, this._width, this._height);
        this._colorize(colored.data, this._grad);
        ctx.putImageData(colored, 0, 0);

        return this;
    },

    _colorize: function (pixels, gradient) {
        for (var i = 0, len = pixels.length, j; i < len; i += 4) {
            j = pixels[i + 3] * 4; // get gradient color from opacity value

            if (j) {
                pixels[i] = gradient[j];
                pixels[i + 1] = gradient[j + 1];
                pixels[i + 2] = gradient[j + 2];
            }
        }
    },

    _createCanvas:function() {
        if (typeof document !== 'undefined') {
            return document.createElement('canvas');
        } else {
            //node-canvas
            return new this._canvas.constructor(1, 1);
        }
    }
};

if (nodeEnv) {
    exports = module.exports = maptalks.HeatLayer;
}
})();
<|endoftext|>


<commit_before>/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import Calendar from './Calendar';
import CalendarMonth from './CalendarMonth';
import CalendarYear from './CalendarYear';
import DateDisplay from './DateDisplay';
import {addMonths, dateTimeFormat} from './dateUtils';
import getMuiTheme from '../styles/getMuiTheme';

describe('<Calendar />', () => {
  const muiTheme = getMuiTheme();
  const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});

  describe('Next Month Button', () => {
    it('should initially be disabled if the current month is the same as the month in the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const maxDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should initially be disabled if the current month is after the month in the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let maxDate = new Date(initialDate.toDateString());
      maxDate = addMonths(maxDate, -1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should initially enable the next month button if the current month is before the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let maxDate = new Date(initialDate.toDateString());
      maxDate = addMonths(maxDate, 1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      assert.ok(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should reenable the next month button when the current month is before the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const maxDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      wrapper.instance().handleMonthChange(-1);
      wrapper.update();

      assert.ok(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should redisable the next month button when the current month is the same as the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let maxDate = new Date(initialDate.toDateString());
      maxDate = addMonths(maxDate, 1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      wrapper.instance().handleMonthChange(1);
      wrapper.update();

      assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });
  });

  describe('Previous Month Button', () => {
    it(`should initially disable the previous month button if the current month
      is the same as the minDate month prop`, () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const minDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it(`should initially disable the previous month button if the current month
      is before the minDate month prop`, () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let minDate = new Date(initialDate.toDateString());
      minDate = addMonths(initialDate, 1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it('should initially enable the previous month button if the current month is after the minDate month prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let minDate = new Date(initialDate.toDateString());
      minDate = addMonths(initialDate, -1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      assert.ok(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it('should enable the previous month button when the current month is after the minDate month prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const minDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      wrapper.instance().handleMonthChange(1);
      wrapper.update();

      assert.ok(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it('should disable the previous month button when the current month is the same as the minDate month prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let minDate = new Date(initialDate.toDateString());
      minDate = addMonths(minDate, -1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      wrapper.instance().handleMonthChange(-1);
      wrapper.update();

      assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });
  });

  describe('Date Display', () => {
    it('should be visible by default', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          mode="landscape"
        />
      );

      assert.strictEqual(wrapper.find(DateDisplay).length, 1, 'should show date display');
      assert.strictEqual(wrapper.props().style.width, 479, 'should allow space for date display');
    });

    it('should be hidden when hideCalendarDate is set', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          mode="landscape"
          hideCalendarDate={true}
        />
      );

      assert.strictEqual(wrapper.find(DateDisplay).length, 0, 'should hide date display');
      assert.strictEqual(wrapper.props().style.width, 310, 'should not allow space for date display');
    });
  });

  describe('initial state', () => {
    it('should display the month day pick view by default', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
        />
      );

      assert.strictEqual(wrapper.find(CalendarMonth).length, 1, 'should have the calendar month select');
    });

    it('should display the year selection view when openToYearSelection is true', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          openToYearSelection={true}
        />
      );

      assert.strictEqual(wrapper.find(CalendarYear).length, 1, 'should have the year select');
    });
  });
});
<commit_msg>Calendar - added ID tests (issue #163)<commit_after>/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import Calendar from './Calendar';
import CalendarMonth from './CalendarMonth';
import CalendarYear from './CalendarYear';
import DateDisplay from './DateDisplay';
import {addMonths, dateTimeFormat} from './dateUtils';
import getMuiTheme from '../styles/getMuiTheme';

describe('<Calendar />', () => {
  const muiTheme = getMuiTheme();
  const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});

  describe('Next Month Button', () => {
    it('should initially be disabled if the current month is the same as the month in the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const maxDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should initially be disabled if the current month is after the month in the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let maxDate = new Date(initialDate.toDateString());
      maxDate = addMonths(maxDate, -1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should initially enable the next month button if the current month is before the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let maxDate = new Date(initialDate.toDateString());
      maxDate = addMonths(maxDate, 1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      assert.ok(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should reenable the next month button when the current month is before the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const maxDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      wrapper.instance().handleMonthChange(-1);
      wrapper.update();

      assert.ok(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });

    it('should redisable the next month button when the current month is the same as the maxDate prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let maxDate = new Date(initialDate.toDateString());
      maxDate = addMonths(maxDate, 1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          maxDate={maxDate}
        />
      );

      wrapper.instance().handleMonthChange(1);
      wrapper.update();

      assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
    });
  });

  describe('Previous Month Button', () => {
    it(`should initially disable the previous month button if the current month
      is the same as the minDate month prop`, () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const minDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it(`should initially disable the previous month button if the current month
      is before the minDate month prop`, () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let minDate = new Date(initialDate.toDateString());
      minDate = addMonths(initialDate, 1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it('should initially enable the previous month button if the current month is after the minDate month prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let minDate = new Date(initialDate.toDateString());
      minDate = addMonths(initialDate, -1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      assert.ok(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it('should enable the previous month button when the current month is after the minDate month prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      const minDate = new Date(initialDate.toDateString());

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      wrapper.instance().handleMonthChange(1);
      wrapper.update();

      assert.ok(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });

    it('should disable the previous month button when the current month is the same as the minDate month prop', () => {
      const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
      let minDate = new Date(initialDate.toDateString());
      minDate = addMonths(minDate, -1);

      const wrapper = shallowWithContext(
        <Calendar
          initialDate={initialDate}
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          minDate={minDate}
        />
      );

      wrapper.instance().handleMonthChange(-1);
      wrapper.update();

      assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
    });
  });

  describe('Date Display', () => {
    it('should be visible by default', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          mode="landscape"
        />
      );

      assert.strictEqual(wrapper.find(DateDisplay).length, 1, 'should show date display');
      assert.strictEqual(wrapper.props().style.width, 479, 'should allow space for date display');
    });

    it('should be hidden when hideCalendarDate is set', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          mode="landscape"
          hideCalendarDate={true}
        />
      );

      assert.strictEqual(wrapper.find(DateDisplay).length, 0, 'should hide date display');
      assert.strictEqual(wrapper.props().style.width, 310, 'should not allow space for date display');
    });
  });

  describe('initial state', () => {
    it('should display the month day pick view by default', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
        />
      );

      assert.strictEqual(wrapper.find(CalendarMonth).length, 1, 'should have the calendar month select');
    });

    it('should display the year selection view when openToYearSelection is true', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          openToYearSelection={true}
        />
      );

      assert.strictEqual(wrapper.find(CalendarYear).length, 1, 'should have the year select');
    });

    it('should produce an ID when one has not been provided', () => {
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
        />
      );

      assert.ok(wrapper.prop('id'), 'an ID value should be generated');
    });

    it('should use the given ID', () => {
      const id = 'methuselah';
      const wrapper = shallowWithContext(
        <Calendar
          DateTimeFormat={dateTimeFormat}
          locale="en-US"
          id={id}
        />
      );

      assert.strictEqual(wrapper.prop('id'), id, `the provided id ${id} was not used`);
    });
  });
});
<|endoftext|>


<commit_before>const babylon = require("babylon");
const sourceMap = require("source-map");

const { Generator } = require("..");

const INPUT_FILE = "example.js";
const OUTPUT_FILE = "example.bundle.js";

exports.generate = (source, singleExpression = false) => {
  const getAst = src => {
    const rootAst = babylon.parse(src, {
      allowReturnOutsideFunction: true,
      allowImportExportEverywhere: true,
      sourceFilename: INPUT_FILE,
      plugins: [
        "jsx",
        "flow",
        "doExpressions",
        "objectRestSpread",
        "decorators",
        "classProperties",
        "exportExtensions",
        "asyncGenerators",
        "functionBind",
        "functionSent"
      ]
    });
    return singleExpression ? rootAst.program.body[0].expression : rootAst;
  }

  const ast = getAst(source);

  const g = new Generator({ outputFilename: OUTPUT_FILE });
  g.addSourceFile(INPUT_FILE, source);
  g.generate(ast);

  const { code, map } = g;

  const astIsEqual = () => {
    const astFromGeneratedCode = getAst(code);
    const astStrA = JSON.stringify(ast);
    const astStrB = JSON.stringify(astFromGeneratedCode);
    return astStrA === astStrB;
  };

  return {
    map: JSON.parse(map),
    code,
    ast,
    astIsEqual
  };
};

exports.dedent = (by, str) => str
  .split("\n")
  .filter(line => line.length >= by)
  .map(line => line.slice(by))
  .join("\n");
<commit_msg>Readability.<commit_after>const babylon = require("babylon");
const sourceMap = require("source-map");

const { Generator } = require("..");

const INPUT_FILE = "example.js";
const OUTPUT_FILE = "example.bundle.js";

exports.generate = (source, singleExpression = false) => {
  const getAst = src => {
    const rootAst = babylon.parse(src, {
      allowReturnOutsideFunction: true,
      allowImportExportEverywhere: true,
      sourceFilename: INPUT_FILE,
      plugins: [
        "jsx",
        "flow",
        "doExpressions",
        "objectRestSpread",
        "decorators",
        "classProperties",
        "exportExtensions",
        "asyncGenerators",
        "functionBind",
        "functionSent"
      ]
    });
    return singleExpression ? rootAst.program.body[0].expression : rootAst;
  }

  const ast = getAst(source);

  const generator = new Generator({ outputFilename: OUTPUT_FILE });
  generator.addSourceFile(INPUT_FILE, source);
  generator.generate(ast);

  const { code, map } = generator;

  const astIsEqual = () => {
    const astFromGeneratedCode = getAst(code);
    const astStrA = JSON.stringify(ast);
    const astStrB = JSON.stringify(astFromGeneratedCode);
    return astStrA === astStrB;
  };

  return {
    map: JSON.parse(map),
    code,
    ast,
    astIsEqual
  };
};

exports.dedent = (by, str) => str
  .split("\n")
  .filter(line => line.length >= by)
  .map(line => line.slice(by))
  .join("\n");
<|endoftext|>


<commit_before>/*  This file is part of Iain Hamiltons Isometric HTML5 App.

    Iain Hamiltons Isometric HTML5 App is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Iain Hamiltons Isometric HTML5 App is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Iain Hamiltons Isometric HTML5 App.  If not, see <http://www.gnu.org/licenses/>. */

function url(){
	this._path = function(part) {
			var url = window.location.href;
			var url_parts = url.split('/');
			return url_parts[part+3];

	}
}<commit_msg>Update url.js<commit_after>/*  Copyright 2013 Iain Hamitlon & Edward Smyth

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

function url(){
	this._path = function(part) {
			var url = window.location.href;
			var url_parts = url.split('/');
			return url_parts[part+3];

	}
}
<|endoftext|>


<commit_before>AUI().add(
	'io-ajax',
	function(A) {
		var Lang = A.Lang,

			getClassName = A.ClassNameManager.getClassName,

			NAME = 'ajax';

		var Ajax = function() {
			Ajax.superclass.constructor.apply(this, arguments);
		};

		Ajax.NAME = NAME;

		Ajax.ATTRS = {
			autoLoad: {
				value: true
			},
			uri: {
				value: null,
				getter: function(value) {
					var instance = this;

					var cache = instance.get('cache');

					if (!cache) {
						value += (value.indexOf('?') == -1) ? '?' : '&';

						var timestamp = (+ new Date);

						if (value.indexOf('_AUI_t=') > -1) {
							value = value.replace(/(_AUI_t=)\d+/, '$1' + timestamp);
						}
						else {
							value += '_AUI_t=' + timestamp;
						}
					}

					return value;
				},
				setter: AUI.defaults.io.uriFormatter,
				validator: Lang.isString
			},
			method: {
				value: AUI.defaults.io.method,
				setter: function(value) {
					var instance = this;

					if (instance._originalConfig) {
						instance._originalConfig.method = value;
					}
				}
			},
			dataType: {
				value: null,
				setter: function(value) {
					return value && value.toLowerCase();
				}
			},
			responseData: {
				value: null,
				setter: function(value) {
					var instance = this;

					var dataType = instance.get('dataType');

					try {
						if (value && value.responseText) {
							var xhr = value;

							if (dataType == 'xml' ||
								xhr.getResponseHeader('content-type').indexOf('xml') > -1) {

								value = xhr.responseXML;

								dataType = 'xml';
							}
							else {
								value = xhr.responseText;
							}
						}

						if (AUI.defaults.io.dataFormatter) {
							value = AUI.defaults.io.dataFormatter(value);
						}

						if (dataType == 'json') {
							value = A.JSON.parse(value);
						}
					}
					catch (e) {
						throw new Error('Parser error: dataType: "' + dataType + '" is not correctly parsing');

						value = A.Attribute.INVALID_VALUE;
					}

					return value;
				}
			},
			cache: {
				value: true,
				validator: function(value) {
					var instance = this;

					return Lang.isBoolean(value) && instance.get('method').toLowerCase() == 'get';
				}
			}
		};

		A.extend(
			Ajax,
			A.Base,
			{
				initializer: function(config) {
					var instance = this;

					instance._createEvents();

					config = A.mix(
						{
							method: instance.get('method'),
							on: {
								complete: A.bind(instance._handleComplete, instance),
								end: A.bind(instance.fire, instance, 'end'),
								failure: A.bind(instance.fire, instance, 'failure'),
								start: A.bind(instance.fire, instance, 'start'),
								success: A.bind(instance._handleSuccess, instance)
							}
						},
						config
					);

					instance._originalConfig = config;

					if (instance.get('autoLoad')) {
						instance.start();
					}
				},

				destructor: function() {
					var instance = this;

					instance.stop();

					instance.transaction = null;
					instance.xhr = null;
				},

				start: function(config) {
					var instance = this;

					instance.xhr = null;

					var originalConfig = instance._originalConfig;

					A.mix(originalConfig, config, true);

					if (config) {
						instance.setAttrs(originalConfig);
					}

					instance.fire('initialize', originalConfig);
				},

				stop: function() {
					var instance = this;

					if (instance.transaction) {
						instance.transaction.abort();
					}
				},

				_createEvents: function() {
					var instance = this;

					instance.publish('complete');
					instance.publish('end');
					instance.publish('failure');

					instance.publish(
						'initialize',
						{
							defaultFn: instance._defInitializeHandler
						}
					);

					instance.publish(
						'start',
						{
							preventedFn: instance._preventConnection
						}
					);

					instance.publish(
						'success',
						{
							defaultFn: instance._defSuccessHandler
						}
					);
				},

				_defInitializeHandler: function(event) {
					var instance = this;

					var uri = instance.get('uri');

					var config = event.details[0];

					instance.transaction = A.io(uri, config);
				},

				_handleComplete: function(id, obj) {
					var instance = this;

					instance.xhr = obj;

					instance.fire('complete', id, obj);
				},

				_handleSuccess: function(id, obj) {
					var instance = this;

					instance.set('responseData', obj);

					instance.fire('success', id, obj);
				},

				_preventConnection: function() {
					var instance = this;

					if (instance.transaction) {
						instance.transaction.abort();
					}
				}
			}
		);

		A.namespace('Plugin').IOAjax = Ajax;

		A.io.ajax = function(config) {
			return new A.Plugin.IOAjax(config);
		};
	},
	'@VERSION',
	{
		requires: ['base', 'io', 'json']
	}
);<commit_msg>Minor changes (call to defaults.* must be called within a function to be properly overwritten, and moving the IOAjax class out of the Plugin namespace to avoid confusion)<commit_after>AUI().add(
	'io-ajax',
	function(A) {
		var Lang = A.Lang,

			getClassName = A.ClassNameManager.getClassName,

			NAME = 'ajax';

		var Ajax = function() {
			Ajax.superclass.constructor.apply(this, arguments);
		};

		Ajax.NAME = NAME;

		Ajax.ATTRS = {
			autoLoad: {
				value: true
			},
			uri: {
				value: null,
				getter: function(value) {
					var instance = this;

					var cache = instance.get('cache');

					if (!cache) {
						value += (value.indexOf('?') == -1) ? '?' : '&';

						var timestamp = (+ new Date);

						if (value.indexOf('_AUI_t=') > -1) {
							value = value.replace(/(_AUI_t=)\d+/, '$1' + timestamp);
						}
						else {
							value += '_AUI_t=' + timestamp;
						}
					}

					return value;
				},
				getter: function(value) {
					return AUI.defaults.io.uriFormatter(value);
				},
				validator: Lang.isString
			},
			method: {
				valueFn: function() {
					return AUI.defaults.io.method;
				},
				setter: function(value) {
					var instance = this;

					if (instance._originalConfig) {
						instance._originalConfig.method = value;
					}
				}
			},
			dataType: {
				value: null,
				setter: function(value) {
					return value && value.toLowerCase();
				}
			},
			responseData: {
				value: null,
				setter: function(value) {
					var instance = this;

					var dataType = instance.get('dataType');

					try {
						if (value && value.responseText) {
							var xhr = value;

							if (dataType == 'xml' ||
								xhr.getResponseHeader('content-type').indexOf('xml') > -1) {

								value = xhr.responseXML;

								dataType = 'xml';
							}
							else {
								value = xhr.responseText;
							}
						}

						if (AUI.defaults.io.dataFormatter) {
							value = AUI.defaults.io.dataFormatter(value);
						}

						if (dataType == 'json') {
							value = A.JSON.parse(value);
						}
					}
					catch (e) {
						throw new Error('Parser error: dataType: "' + dataType + '" is not correctly parsing');

						value = A.Attribute.INVALID_VALUE;
					}

					return value;
				}
			},
			cache: {
				value: true,
				validator: function(value) {
					var instance = this;

					return Lang.isBoolean(value) && instance.get('method').toLowerCase() == 'get';
				}
			}
		};

		A.extend(
			Ajax,
			A.Base,
			{
				initializer: function(config) {
					var instance = this;

					instance._createEvents();

					config = A.mix(
						{
							method: instance.get('method'),
							on: {
								complete: A.bind(instance._handleComplete, instance),
								end: A.bind(instance.fire, instance, 'end'),
								failure: A.bind(instance.fire, instance, 'failure'),
								start: A.bind(instance.fire, instance, 'start'),
								success: A.bind(instance._handleSuccess, instance)
							}
						},
						config
					);

					instance._originalConfig = config;

					if (instance.get('autoLoad')) {
						instance.start();
					}
				},

				destructor: function() {
					var instance = this;

					instance.stop();

					instance.transaction = null;
					instance.xhr = null;
				},

				start: function(config) {
					var instance = this;

					instance.xhr = null;

					var originalConfig = instance._originalConfig;

					A.mix(originalConfig, config, true);

					if (config) {
						instance.setAttrs(originalConfig);
					}

					instance.fire('initialize', originalConfig);
				},

				stop: function() {
					var instance = this;

					if (instance.transaction) {
						instance.transaction.abort();
					}
				},

				_createEvents: function() {
					var instance = this;

					instance.publish('complete');
					instance.publish('end');
					instance.publish('failure');

					instance.publish(
						'initialize',
						{
							defaultFn: instance._defInitializeHandler
						}
					);

					instance.publish(
						'start',
						{
							preventedFn: instance._preventConnection
						}
					);

					instance.publish(
						'success',
						{
							defaultFn: instance._defSuccessHandler
						}
					);
				},

				_defInitializeHandler: function(event) {
					var instance = this;

					var uri = instance.get('uri');

					var config = event.details[0];

					instance.transaction = A.io(uri, config);
				},

				_handleComplete: function(id, obj) {
					var instance = this;

					instance.xhr = obj;

					instance.fire('complete', id, obj);
				},

				_handleSuccess: function(id, obj) {
					var instance = this;

					instance.set('responseData', obj);

					instance.fire('success', id, obj);
				},

				_preventConnection: function() {
					var instance = this;

					if (instance.transaction) {
						instance.transaction.abort();
					}
				}
			}
		);

		A.IOAjax = Ajax;

		A.io.ajax = function(config) {
			return new A.IOAjax(config);
		};
	},
	'@VERSION',
	{
		requires: ['base', 'io', 'json']
	}
);<|endoftext|>


<commit_before>var autodafe = require('../../autodafe'),
    http = require('http'),
    httpAuth = require('http-auth'),
    HTTPRequest = require('./HTTPRequest');

/**
 * HTTPConnection is a component that provides access to the application through the HTTP protocol
 * @class HTTPConnection
 * @extends Component
 * @param {number} [options.port=80] Port for http server
 * @param {string} [options.uploadPath='/tmp'] Path to upload files, related to {@link Application._basePath} or root of
 * your system if path is preceded by the slash todo: not implemented
 * @param {object} [options.basicAuth] options for basic HTTP authentication
 * @param {string} [options.basicAuth.message] The message will be shown if user is not authorized; if not specified
 * {@link HTTPConnection._defaultBasicAuthMessage} will be used
 * @param {object.<string, string>} [options.basicAuth.users={}] object that contained allowed user names as keys and
 * them passwords as values
 */
var HTTPConnection = module.exports = autodafe.Component.extend(/**@lends HTTPConnection*/{
    /**
     * @protected
     * @type {string}
     */
    _name: 'http',

    /**
     * @protected
     */
    _props: function () {
        this._super();

        /**
         * The port for http server
         * @type {number}
         * @private
         * @default 80
         */
        this._port = this._options.port || 80;

        /**
         * The absolute path to directory for file uploading
         * @type {string}
         * @private
         */
//        this._uploadPath = this._options.uploadPath || '/tmp';

        /**
         * @type {http.Server}
         * @see http.Server in node docs
         * @private
         */
        this._server = null;

        /**
         * @type {?object}
         * @private
         */
        this._basicAuth = null;

        /**
         * Default message for not passed basic HTTP authentication
         * @type {string}
         * @private
         * @defaults "Not authorized"
         */
        this._defaultBasicAuthMessage = 'Not authorized';
    },

    /**
     * @constructs
     * @private
     */
    _init: function () {
        this._super();

        this._initBasicAuth(this._options.basicAuth);
        this._initServer();
    },

    /**
     * @param {{message:?string, users:object.<string, string>}} [basicAuthOptions]
     * @private
     */
    _initBasicAuth: function (basicAuthOptions) {
        if (!basicAuthOptions) {
            return;
        }

        var message = basicAuthOptions.message || this._defaultBasicAuthMessage,
            users = basicAuthOptions.users,
            usersWithPasswords = [];

        for (var user in users) {
            if (users.hasOwnProperty(user)) {
                usersWithPasswords.push(user + ':' + users[user]);
            }
        }

//        this._basicAuth = httpAuth.basic({
//            authRealm: message,
//            authList: usersWithPasswords
//        });
    },

    /**
     * @private
     */
    _initServer: function () {
        this._server = http.createServer()
            .listen(this._port)
            .on('request', this._onServerRequest.bind(this))
            .on('close', this._onServerClose.bind(this));

//        this.log('HTTP server started at port ' + this._port, 'info');
    },

    /**
     * @listens http.Server#request
     * @param {http.ServerRequest} request
     * @param {http.ServerResponse} response
     * @private
     */
    _onServerRequest: function (request, response) {
        if (this._basicAuth) {
            this._basicAuth.apply(request, response, this._processRequest.bind(this, request, response));
        }
        else {
            this._processRequest(request, response);
        }
    },

    /**
     * @param {http.ServerRequest} request
     * @param {http.ServerResponse} response
     * @private
     */
    _processRequest: function (request, response) {
        new HTTPRequest({
            request: request,
            response: response,
            basePath: this._app.getBasePath()
        });
    },

    /**
     * @listens http.Server#close
     * @param {number} errorNumber
     * @private
     */
    _onServerClose: function (errorNumber) {
        this._server.off('request').off('close');
        this.emit('close', errorNumber);
    },

    /**
     * Closes the server
     */
    close: function () {
        this._server.close();
    }
});<commit_msg>log messages for HTTPConnection, Application, Component<commit_after>var autodafe = require('../../autodafe'),
    http = require('http'),
    httpAuth = require('http-auth'),
    HTTPRequest = require('./HTTPRequest');

/**
 * HTTPConnection is a component that provides access to the application through the HTTP protocol
 * @class HTTPConnection
 * @extends Component
 * @param {number} [options.port=80] Port for http server
 * @param {string} [options.uploadPath='/tmp'] Path to upload files, related to {@link Application._basePath} or root of
 * your system if path is preceded by the slash todo: not implemented
 * @param {object} [options.basicAuth] options for basic HTTP authentication
 * @param {string} [options.basicAuth.message] The message will be shown if user is not authorized; if not specified
 * {@link HTTPConnection._defaultBasicAuthMessage} will be used
 * @param {object.<string, string>} [options.basicAuth.users={}] object that contained allowed user names as keys and
 * them passwords as values
 */
var HTTPConnection = module.exports = autodafe.Component.extend(/**@lends HTTPConnection*/{
    /**
     * @protected
     * @type {string}
     */
    _name: 'http',

    /**
     * @protected
     */
    _props: function () {
        this._super();

        /**
         * The port for http server
         * @type {number}
         * @private
         * @default 80
         */
        this._port = this._options.port || 80;

        /**
         * The absolute path to directory for file uploading
         * @type {string}
         * @private
         */
//        this._uploadPath = this._options.uploadPath || '/tmp';

        /**
         * @type {http.Server}
         * @see http.Server in node docs
         * @private
         */
        this._server = null;

        /**
         * @type {?object}
         * @private
         */
        this._basicAuth = null;

        /**
         * Default message for not passed basic HTTP authentication
         * @type {string}
         * @private
         * @defaults "Not authorized"
         */
        this._defaultBasicAuthMessage = 'Not authorized';
    },

    /**
     * @constructs
     * @private
     */
    _init: function () {
        this._super();

        this._initBasicAuth(this._options.basicAuth);
        this._initServer();
    },

    /**
     * @param {{message:?string, users:object.<string, string>}} [basicAuthOptions]
     * @private
     */
    _initBasicAuth: function (basicAuthOptions) {
        if (!basicAuthOptions) {
            return;
        }

        this.log('Enable basic HTTP authentication');
        var message = basicAuthOptions.message || this._defaultBasicAuthMessage,
            users = basicAuthOptions.users,
            usersWithPasswords = [];

        for (var user in users) {
            if (users.hasOwnProperty(user)) {
                usersWithPasswords.push(user + ':' + users[user]);
            }
        }

//        this._basicAuth = httpAuth.basic({
//            authRealm: message,
//            authList: usersWithPasswords
//        });
        this.log('Basic HTTP authentication is enabled for following users:', Object.keys(users).join(', '), 'info');
    },

    /**
     * @private
     */
    _initServer: function () {
        this._server = http.createServer()
            .listen(this._port)
            .on('request', this._onServerRequest.bind(this))
            .on('close', this._onServerClose.bind(this))
            .on('error', this._onServerError.bind(this));

        this.log('HTTP server started at port', this._port, 'info');
    },

    /**
     * @listens http.Server#request
     * @param {http.ServerRequest} request
     * @param {http.ServerResponse} response
     * @private
     */
    _onServerRequest: function (request, response) {
        if (this._basicAuth) {
            this._basicAuth.apply(request, response, this._processRequest.bind(this, request, response));
        }
        else {
            this._processRequest(request, response);
        }
    },

    /**
     * @param {http.ServerRequest} request
     * @param {http.ServerResponse} response
     * @private
     */
    _processRequest: function (request, response) {
        new HTTPRequest({
            request: request,
            response: response,
            basePath: this._app.getBasePath()
        });
    },

    _onServerError: function (e) {
        console.log(e);
    },

    /**
     * @listens http.Server#close
     * @param {number} errorNumber
     * @private
     */
    _onServerClose: function (errorNumber) {
        this._server.off('request').off('close');
        this.emit('close', errorNumber);
    },

    /**
     * Closes the server
     */
    close: function () {
        this._server.close();
    }
});<|endoftext|>


<commit_before>var categoryList = "#first,#second,#third,#archive";

var hide_lists = function (cb) {
    $('.category').fadeOut(300);
    $('.category-btn').removeClass('disabled');
};

function show_category(categoryName) {
    $('.category-btn').removeClass('disabled');
    $('.category').hide();

    fadeOutList = categoryList.repace("#" + categoryName);

 $('#' + categoryName).fadeIn(300);

    $('#' + categoryName + '-btn').addClass('disabled');
}
<commit_msg>fix category script<commit_after>var categoryList = "#start,#first,#second,#third,#archive,#end";

var hide_lists = function (cb) {
    $('.category').fadeOut(300);
    $('.category-btn').removeClass('disabled');
};

function show_category(categoryName) {
    $('.category-btn').removeClass('disabled');
    $('.category').hide();

    var fadeOutList = categoryList.replace("#" + categoryName + ",", "");

    $(fadeOutList).fadeOut(300, function () {
      $('#' + categoryName).fadeIn(300);
    });

    $('#' + categoryName + '-btn').addClass('disabled');
}
<|endoftext|>


<commit_before>(function() {
    var site = {
        platform: 'windows'
    };

    if(navigator.platform.indexOf("Win32") != -1 ||
       navigator.platform.indexOf("Win64") != -1) {
        site.platform = 'windows';
    }
    else if(navigator.platform.indexOf("Linux") != -1) {
        site.platform = 'linux';
    }
    else if (navigator.userAgent.indexOf("Mac OS X") != -1) {
        site.platform = 'osx';
    }
    else if (navigator.userAgent.indexOf("MSIE 5.2") != -1) {
        site.platform = 'osx';
    }
    else if (navigator.platform.indexOf("Mac") != -1) {
        site.platform = 'mac';
    }
    else {
        site.platform = 'other';
    }

    function init() {
        // Add the platform as a class name immediately to avoid lots
        // of flickering
        var b = document.body;
        b.className = b.className.replace("windows", site.platform);
    }

    init();
    window.site = site;
})();<commit_msg>remove whitespace<commit_after>(function() {
    var site = {
        platform: 'windows'
    };

    if(navigator.platform.indexOf("Win32") != -1 ||
       navigator.platform.indexOf("Win64") != -1) {
        site.platform = 'windows';
    }
    else if(navigator.platform.indexOf("Linux") != -1) {
        site.platform = 'linux';
    }
    else if (navigator.userAgent.indexOf("Mac OS X") != -1) {
        site.platform = 'osx';
    }
    else if (navigator.userAgent.indexOf("MSIE 5.2") != -1) {
        site.platform = 'osx';
    }
    else if (navigator.platform.indexOf("Mac") != -1) {
        site.platform = 'mac';
    }
    else {
        site.platform = 'other';
    }

    function init() {
        // Add the platform as a class name immediately to avoid lots
        // of flickering
        var b = document.body;
        b.className = b.className.replace("windows", site.platform);
    }

    init();
    window.site = site;
})();<|endoftext|>


<commit_before>exports.name = '.fq';
exports.hidden = true;
exports.enabled = true;
exports.matchStart = true;
exports.handler = function(data) {
    if (admincheck(data.userid)) {
        for (i in usersList) {
            if (usersList[i].name.toLowerCase() == data.text.substring(4)) {
                waitlist.unshift(usersList[i].name);
                output({text: usersList[i].name + ' has been added to the start of the queue.',
                    destination: data.source, userid: data.userid});
            }
        }
    }
}<commit_msg>Fixes #62<commit_after>exports.name = '.fq';
exports.hidden = true;
exports.enabled = true;
exports.matchStart = true;
exports.handler = function(data) {
    if (admincheck(data.userid)) {
        for (i in usersList) {
            if (usersList[i].name.toLowerCase() == data.text.substring(4)) {
                waitlist.unshift({name: usersList[i].name, id: data.userid});
                output({text: usersList[i].name + ' has been added to the start of the queue.',
                    destination: data.source, userid: data.userid});
            }
        }
    }
}<|endoftext|>