<commit_before>// modal pattern.
//
// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
// Depends: jquery.js patterns.js pickadate.js
//
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program 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 2 of the License.
//
// This program 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
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */
define([
  'jquery',
  'js/patterns/base',
  'js/patterns/backdrop',
  'jam/Patterns/src/registry'
], function($, Base, Backdrop, registry, undefined) {
  "use strict";

  var Modal = Base.extend({
    name: "modal",
    jqueryPlugin: "modal",
    defaults: {
      triggers: '',
      position: "center middle",
      width: "",
      height: "",
      margin: "20px",
      klass: "modal",
      klassWrapper: "modal-wrapper",
      klassWrapperInner: "modal-wrapper-inner",
      klassLoading: "modal-loading",
      klassActive: "active",
      backdrop: "body",
      backdropZIndex: "1000",
      backdropOpacity: "0.8",
      backdropKlass: "backdrop",
      backdropKlassActive: "backdrop-active",
      backdropCloseOnEsc: true,
      backdropCloseOnClick: true
    },
    init: function() {
      var self = this;

      self.backdrop = new Backdrop(self.$el.parents(self.options.backdrop), {
        zindex: self.options.backdropZIndex,
        klass: self.options.backdropKlass,
        klassActive: self.options.backdropKlassActive,
        styles: self.options.backdropStyles,
        opacity: self.options.backdropOpacity,
        closeOnEsc: self.options.backdropCloseOnEsc,
        closeOnClick: self.options.backdropCloseOnClick
      });
      self.backdrop.on('hidden', function(e) {
        self.hide();
      });

      self.$wrapper = $('> .' + self.options.klassWrapper, self.backdrop.$el);
      if (self.$wrapper.size() === 0) {
        self.$wrapper = $('
')
          .hide()
          .css({
            'z-index': parseInt(self.options.backdropZIndex, 10) + 1,
            'overflow-y': 'auto',
            'position': 'fixed',
            'height': '100%',
            'width': '100%',
            'bottom': '0',
            'left': '0',
            'right': '0',
            'top': '0'
          })
          .addClass(self.options.klassWrapper)
          .insertBefore(self.backdrop.$backdrop)
          .on('click', function(e) {
            e.stopPropagation();
            e.preventDefault();
            self.backdrop.hide();
          });
      }

      self.$wrapperInner = $('> .' + self.options.klassWrapperInner, self.$wrapper);
      if (self.$wrapperInner.size() === 0) {
        self.$wrapperInner = $('
')
          .addClass(self.options.klassWrapperInner)
          .css({
            'position': 'absolute',
            'bottom': '0',
            'left': '0',
            'right': '0',
            'top': '0'
          })
          .appendTo(self.$wrapper);
      }

      self.$loading = $('> .' + self.options.klassLoading, self.$wrapperInner);
      if (self.$loading.size() === 0) {
        self.$loading = $('
').hide()
          .addClass(self.options.klassLoading)
          .appendTo(self.$wrapperInner);
      }
      $(window.parent).resize(function() {
        self.positionModal();
      });

      if (self.options.triggers) {
        $.each(self.options.triggers, function(i, item) {
          item = item.split(' ');
          $(item[1] || self.$el).on(item[0], function() {
            self.show();
          });
        });
      }

      if (self.$el.is('a')) {
        if (self.$el.attr('href')) {
          if (!self.options.target && self.$el.attr('href').substr(0, 1) === '#') {
            self.options.target = self.$el.attr('href');
          }
          if (!self.options.ajaxUrl && self.$el.attr('href').substr(0, 1) !== '#') {
            self.options.ajaxUrl = self.$el.attr('href');
          }
        }
        self.$el.on('click', function(e) {
          e.stopPropagation();
          e.preventDefault();
          self.show();
        });
      }

      self.initModal();
      self.$wrapper.on('hidden', function(e) {
        e.stopPropagation();
        e.preventDefault();
        self.hide();
      });
    },
    initModalElement: function($modal) {
      var self = this;
      $modal
        .addClass(self.options.klass)
        .on('click', function(e) {
          e.stopPropagation();
          if ($.nodeName(e.target, 'a')) {
            e.preventDefault();
            // TODO: open links inside modal
          }
        })
        .on('destroy.modal.patterns', function(e) {
          e.stopPropagation();
          self.hide();
        })
        .on('resize.modal.patterns', function(e) {
          e.stopPropagation();
          e.preventDefault();
          self.positionModal(true);
        });
      return $modal;
    },
    initModal: function() {
      var self = this;
      if (self.options.ajaxUrl) {
        self.$modal = function() {
          self.trigger('before-ajax');
          self.$wrapper.parent().css('overflow', 'hidden');
          self.$wrapper.show();
          self.backdrop.show();
          self.$loading.show();
          self.positionLoading();
          self.ajaxXHR = $.ajax({
              url: self.options.ajaxUrl,
              type: self.options.ajaxType
          }).done(function(response, textStatus, xhr) {
            self.ajaxXHR = undefined;
            self.$loading.hide();
            self.$modal = self.initModalElement(
              $($((/]*>((.|[\n\r])*)<\/body>/im).exec(response)[0]
                .replace('<body', '<div').replace('', '
'))[0]))
              .appendTo(self.$wrapperInner);
            self.trigger('after-ajax', self, textStatus, xhr);
            self.show();
          });
        };
      } else if (self.options.target) {
        self.$modal = function() {
          self.$modal = self.initModalElement($('
'))
              .html($(self.options.target).clone())
              .appendTo(self.$wrapperInner);
          self.show();
        };
      } else {
        self.$modal = self.initModalElement($('
'))
              .html(self.$el.clone())
              .appendTo(self.$wrapperInner);
      }

    },
    positionLoading: function() {
      var self = this;
      self.$loading.css({
        'margin-left': self.$wrapper.width()/2 - self.$loading.width()/2,
        'margin-top': self.$wrapper.height()/2 - self.$loading.height()/2,
        'position': 'absolute',
        'bottom': '0',
        'left': '0',
        'right': '0',
        'top': '0'
      });
    },
    positionModal: function(preserve_top) {
      var self = this;
      if (typeof self.$modal !== 'function') {

        if (preserve_top) {
          preserve_top = self.$modal.css('top');
        }

        self.$modal.removeAttr('style');
        // if backdrop wrapper is set on body then wrapper should have height
        // of window so we can do scrolling of inner wrapper
        self.$wrapperInner.css({
          'height': '100%',
          'width': '100%'
        });
        if (self.$wrapper.parent().is('body')) {
          self.$wrapper.height($(window.parent).height());
        }

        // place modal at top left with desired width/height and margin
        self.$modal.css({
          'padding': '0',
          'margin': '0',
          'width': self.options.width,
          'height': self.options.height,
          'position': 'absolute',
          'top': preserve_top ? preserve_top : '0',
          'left': '0'
        });

        self.$modal.css({'margin': '0'});
        var modalOffsetBefore = self.$modal.offset();
        self.$modal.css({ 'margin': self.options.margin });
        var modalOffset = self.$modal.offset(),
            modalOuterWidth = self.$modal.outerWidth(true),
            modalInnerWidth = self.$modal.innerWidth(),
            modalOuterHeight = self.$modal.outerHeight(true),
            modalInnerHeight = self.$modal.innerHeight();
        self.$modal.css({ 'margin': '0' });

        var topMargin = modalOffset.top - modalOffsetBefore.top,
            bottomMargin = modalOuterHeight - modalInnerHeight - topMargin,
            leftMargin = modalOffset.left - modalOffsetBefore.left,
            rightMargin = modalOuterWidth - modalInnerWidth - leftMargin;

        // place modal in right position
        var positionHorizontal = self.options.position.split(' ')[0],
            positionVertical = self.options.position.split(' ')[1],
            positionTop, positionBottom, positionLeft, positionRight;

        if (positionHorizontal === 'left') {
          positionLeft = leftMargin + 'px';
          if (self.$wrapperInner.width() < self.$modal.width()) {
            positionRight = rightMargin + 'px';
          } else {
            positionRight = 'auto';
          }
        } else if (positionHorizontal === 'bottom') {
          positionRight = leftMargin + 'px';
          if (self.$wrapperInner.width() < self.$modal.width()) {
            positionLeft = leftMargin + 'px';
          } else {
            positionLeft = 'auto';
          }
        } else {
          if (self.$wrapperInner.width() < self.$modal.width() + leftMargin + rightMargin) {
            positionLeft = leftMargin + 'px';
            positionRight = rightMargin + 'px';
          } else {
            positionLeft = (self.$wrapperInner.innerWidth()/2 -
                self.$modal.outerWidth()/2 - leftMargin) + 'px';
            positionRight = (self.$wrapperInner.innerWidth()/2 -
                self.$modal.outerWidth()/2 - rightMargin) + 'px';
          }
        }
        self.$modal.css({
          'left': positionLeft,
          'right': positionRight,
          'width': self.$modal.width()
        });

        // if modal is bigger then wrapperInner then resize wrapperInner to
        // match modal height
        if (self.$wrapperInner.height() < self.$modal.height()) {
          self.$wrapperInner.height(self.$modal.height() + topMargin + bottomMargin);
        }

        if (preserve_top || positionVertical === 'top') {
          positionTop = topMargin + 'px';
          if (self.$wrapperInner.height() < self.$modal.height()) {
            positionBottom = bottomMargin + 'px';
          } else {
            positionBottom = 'auto';
          }
        } else if (positionVertical === 'bottom') {
          positionBottom = bottomMargin + 'px';
          if (self.$wrapperInner.height() < self.$modal.height()) {
            positionTop = topMargin + 'px';
          } else {
            positionTop= 'auto';
          }
        } else {
          if (self.$wrapperInner.height() < self.$modal.height()) {
            positionTop = topMargin + 'px';
            positionBottom = bottomMargin + 'px';
          } else {
            positionTop = positionBottom = (self.$wrapperInner.height()/2 -
                self.$modal.height()/2) + 'px';
          }
        }
        self.$modal.css({
          'top': positionTop,
          'bottom': positionBottom
        });

      }
    },
    show: function() {
      var self = this;
      if (!self.$el.hasClass(self.options.klassActive)) {
        if (typeof self.$modal === 'function') {
          self._$modal = self.$modal;
          self.$modal();
        } else {
          self.trigger('show');
          self.backdrop.show();
          self.$wrapper.show();
          self.$wrapper.parent().css('overflow', 'hidden');
          self.$el.addClass(self.options.klassActive);
          self.$modal.addClass(self.options.klassActive);
          registry.scan(self.$modal);
          self.positionModal();
          $(window.parent).on('resize.modal.patterns', function() {
            self.positionModal();
          });
          self.trigger('shown');
        }
      }
    },
    hide: function() {
      var self = this;
      if (self.ajaxXHR) {
        self.ajaxXHR.abort();
      }
      if (self.$el.hasClass(self.options.klassActive)) {
        self.trigger('hide');
        self.backdrop.hide();
        self.$wrapper.hide();
        self.$wrapper.parent().css('overflow', 'visible');
        self.$el.removeClass(self.options.klassActive);
        if (self.$modal.remove) {
          self.$modal.remove();
          self.initModal();
        }
        $(window.parent).off('resize.modal.patterns');
        self.trigger('hidden');
      }
    }
  });

  return Modal;

});
<commit_msg>resize/position modal again once all images are loaded, plone/plone.app.toolbar#98<commit_after>// modal pattern.
//
// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
// Depends: jquery.js patterns.js pickadate.js
//
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program 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 2 of the License.
//
// This program 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
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */
define([
  'jquery',
  'js/patterns/base',
  'js/patterns/backdrop',
  'jam/Patterns/src/registry'
], function($, Base, Backdrop, registry, undefined) {
  "use strict";

  var Modal = Base.extend({
    name: "modal",
    jqueryPlugin: "modal",
    defaults: {
      triggers: '',
      position: "center middle",
      width: "",
      height: "",
      margin: "20px",
      klass: "modal",
      klassWrapper: "modal-wrapper",
      klassWrapperInner: "modal-wrapper-inner",
      klassLoading: "modal-loading",
      klassActive: "active",
      backdrop: "body",
      backdropZIndex: "1000",
      backdropOpacity: "0.8",
      backdropKlass: "backdrop",
      backdropKlassActive: "backdrop-active",
      backdropCloseOnEsc: true,
      backdropCloseOnClick: true
    },
    init: function() {
      var self = this;

      self.backdrop = new Backdrop(self.$el.parents(self.options.backdrop), {
        zindex: self.options.backdropZIndex,
        klass: self.options.backdropKlass,
        klassActive: self.options.backdropKlassActive,
        styles: self.options.backdropStyles,
        opacity: self.options.backdropOpacity,
        closeOnEsc: self.options.backdropCloseOnEsc,
        closeOnClick: self.options.backdropCloseOnClick
      });
      self.backdrop.on('hidden', function(e) {
        self.hide();
      });

      self.$wrapper = $('> .' + self.options.klassWrapper, self.backdrop.$el);
      if (self.$wrapper.size() === 0) {
        self.$wrapper = $('
')
          .hide()
          .css({
            'z-index': parseInt(self.options.backdropZIndex, 10) + 1,
            'overflow-y': 'auto',
            'position': 'fixed',
            'height': '100%',
            'width': '100%',
            'bottom': '0',
            'left': '0',
            'right': '0',
            'top': '0'
          })
          .addClass(self.options.klassWrapper)
          .insertBefore(self.backdrop.$backdrop)
          .on('click', function(e) {
            e.stopPropagation();
            e.preventDefault();
            self.backdrop.hide();
          });
      }

      self.$wrapperInner = $('> .' + self.options.klassWrapperInner, self.$wrapper);
      if (self.$wrapperInner.size() === 0) {
        self.$wrapperInner = $('
')
          .addClass(self.options.klassWrapperInner)
          .css({
            'position': 'absolute',
            'bottom': '0',
            'left': '0',
            'right': '0',
            'top': '0'
          })
          .appendTo(self.$wrapper);
      }

      self.$loading = $('> .' + self.options.klassLoading, self.$wrapperInner);
      if (self.$loading.size() === 0) {
        self.$loading = $('
').hide()
          .addClass(self.options.klassLoading)
          .appendTo(self.$wrapperInner);
      }
      $(window.parent).resize(function() {
        self.positionModal();
      });

      if (self.options.triggers) {
        $.each(self.options.triggers, function(i, item) {
          item = item.split(' ');
          $(item[1] || self.$el).on(item[0], function() {
            self.show();
          });
        });
      }

      if (self.$el.is('a')) {
        if (self.$el.attr('href')) {
          if (!self.options.target && self.$el.attr('href').substr(0, 1) === '#') {
            self.options.target = self.$el.attr('href');
          }
          if (!self.options.ajaxUrl && self.$el.attr('href').substr(0, 1) !== '#') {
            self.options.ajaxUrl = self.$el.attr('href');
          }
        }
        self.$el.on('click', function(e) {
          e.stopPropagation();
          e.preventDefault();
          self.show();
        });
      }

      self.initModal();
      self.$wrapper.on('hidden', function(e) {
        e.stopPropagation();
        e.preventDefault();
        self.hide();
      });
    },
    initModalElement: function($modal) {
      var self = this;
      $modal
        .addClass(self.options.klass)
        .on('click', function(e) {
          e.stopPropagation();
          if ($.nodeName(e.target, 'a')) {
            e.preventDefault();
            // TODO: open links inside modal
          }
        })
        .on('destroy.modal.patterns', function(e) {
          e.stopPropagation();
          self.hide();
        })
        .on('resize.modal.patterns', function(e) {
          e.stopPropagation();
          e.preventDefault();
          self.positionModal(true);
        });
      return $modal;
    },
    initModal: function() {
      var self = this;
      if (self.options.ajaxUrl) {
        self.$modal = function() {
          self.trigger('before-ajax');
          self.$wrapper.parent().css('overflow', 'hidden');
          self.$wrapper.show();
          self.backdrop.show();
          self.$loading.show();
          self.positionLoading();
          self.ajaxXHR = $.ajax({
              url: self.options.ajaxUrl,
              type: self.options.ajaxType
          }).done(function(response, textStatus, xhr) {
            self.ajaxXHR = undefined;
            self.$loading.hide();
            self.$modal = self.initModalElement(
              $($((/]*>((.|[\n\r])*)<\/body>/im).exec(response)[0]
                .replace('<body', '<div').replace('', '
'))[0]))
              .appendTo(self.$wrapperInner);
            self.trigger('after-ajax', self, textStatus, xhr);
            self.show();
          });
        };
      } else if (self.options.target) {
        self.$modal = function() {
          self.$modal = self.initModalElement($('
'))
              .html($(self.options.target).clone())
              .appendTo(self.$wrapperInner);
          self.show();
        };
      } else {
        self.$modal = self.initModalElement($('
'))
              .html(self.$el.clone())
              .appendTo(self.$wrapperInner);
      }

    },
    positionLoading: function() {
      var self = this;
      self.$loading.css({
        'margin-left': self.$wrapper.width()/2 - self.$loading.width()/2,
        'margin-top': self.$wrapper.height()/2 - self.$loading.height()/2,
        'position': 'absolute',
        'bottom': '0',
        'left': '0',
        'right': '0',
        'top': '0'
      });
    },
    positionModal: function(preserve_top) {
      var self = this;
      if (typeof self.$modal !== 'function') {

        if (preserve_top) {
          preserve_top = self.$modal.css('top');
        }

        self.$modal.removeAttr('style');
        // if backdrop wrapper is set on body then wrapper should have height
        // of window so we can do scrolling of inner wrapper
        self.$wrapperInner.css({
          'height': '100%',
          'width': '100%'
        });
        if (self.$wrapper.parent().is('body')) {
          self.$wrapper.height($(window.parent).height());
        }

        // place modal at top left with desired width/height and margin
        self.$modal.css({
          'padding': '0',
          'margin': '0',
          'width': self.options.width,
          'height': self.options.height,
          'position': 'absolute',
          'top': preserve_top ? preserve_top : '0',
          'left': '0'
        });

        self.$modal.css({'margin': '0'});
        var modalOffsetBefore = self.$modal.offset();
        self.$modal.css({ 'margin': self.options.margin });
        var modalOffset = self.$modal.offset(),
            modalOuterWidth = self.$modal.outerWidth(true),
            modalInnerWidth = self.$modal.innerWidth(),
            modalOuterHeight = self.$modal.outerHeight(true),
            modalInnerHeight = self.$modal.innerHeight();
        self.$modal.css({ 'margin': '0' });

        var topMargin = modalOffset.top - modalOffsetBefore.top,
            bottomMargin = modalOuterHeight - modalInnerHeight - topMargin,
            leftMargin = modalOffset.left - modalOffsetBefore.left,
            rightMargin = modalOuterWidth - modalInnerWidth - leftMargin;

        // place modal in right position
        var positionHorizontal = self.options.position.split(' ')[0],
            positionVertical = self.options.position.split(' ')[1],
            positionTop, positionBottom, positionLeft, positionRight;

        if (positionHorizontal === 'left') {
          positionLeft = leftMargin + 'px';
          if (self.$wrapperInner.width() < self.$modal.width()) {
            positionRight = rightMargin + 'px';
          } else {
            positionRight = 'auto';
          }
        } else if (positionHorizontal === 'bottom') {
          positionRight = leftMargin + 'px';
          if (self.$wrapperInner.width() < self.$modal.width()) {
            positionLeft = leftMargin + 'px';
          } else {
            positionLeft = 'auto';
          }
        } else {
          if (self.$wrapperInner.width() < self.$modal.width() + leftMargin + rightMargin) {
            positionLeft = leftMargin + 'px';
            positionRight = rightMargin + 'px';
          } else {
            positionLeft = (self.$wrapperInner.innerWidth()/2 -
                self.$modal.outerWidth()/2 - leftMargin) + 'px';
            positionRight = (self.$wrapperInner.innerWidth()/2 -
                self.$modal.outerWidth()/2 - rightMargin) + 'px';
          }
        }
        self.$modal.css({
          'left': positionLeft,
          'right': positionRight,
          'width': self.$modal.width()
        });

        // if modal is bigger then wrapperInner then resize wrapperInner to
        // match modal height
        if (self.$wrapperInner.height() < self.$modal.height()) {
          self.$wrapperInner.height(self.$modal.height() + topMargin + bottomMargin);
        }

        if (preserve_top || positionVertical === 'top') {
          positionTop = topMargin + 'px';
          if (self.$wrapperInner.height() < self.$modal.height()) {
            positionBottom = bottomMargin + 'px';
          } else {
            positionBottom = 'auto';
          }
        } else if (positionVertical === 'bottom') {
          positionBottom = bottomMargin + 'px';
          if (self.$wrapperInner.height() < self.$modal.height()) {
            positionTop = topMargin + 'px';
          } else {
            positionTop= 'auto';
          }
        } else {
          if (self.$wrapperInner.height() < self.$modal.height()) {
            positionTop = topMargin + 'px';
            positionBottom = bottomMargin + 'px';
          } else {
            positionTop = positionBottom = (self.$wrapperInner.height()/2 -
                self.$modal.height()/2) + 'px';
          }
        }
        self.$modal.css({
          'top': positionTop,
          'bottom': positionBottom
        });

      }
    },
    show: function() {
      var self = this;
      if (!self.$el.hasClass(self.options.klassActive)) {
        if (typeof self.$modal === 'function') {
          self._$modal = self.$modal;
          self.$modal();
        } else {
          self.trigger('show');
          self.backdrop.show();
          self.$wrapper.show();
          self.$wrapper.parent().css('overflow', 'hidden');
          self.$el.addClass(self.options.klassActive);
          self.$modal.addClass(self.options.klassActive);
          registry.scan(self.$modal);
          self.positionModal();
          $('img', self.$modal).load(function() {
            self.positionModal();
          });
          $(window.parent).on('resize.modal.patterns', function() {
            self.positionModal();
          });
          self.trigger('shown');
        }
      }
    },
    hide: function() {
      var self = this;
      if (self.ajaxXHR) {
        self.ajaxXHR.abort();
      }
      if (self.$el.hasClass(self.options.klassActive)) {
        self.trigger('hide');
        self.backdrop.hide();
        self.$wrapper.hide();
        self.$wrapper.parent().css('overflow', 'visible');
        self.$el.removeClass(self.options.klassActive);
        if (self.$modal.remove) {
          self.$modal.remove();
          self.initModal();
        }
        $(window.parent).off('resize.modal.patterns');
        self.trigger('hidden');
      }
    }
  });

  return Modal;

});
<|endoftext|>


<commit_before>var curtemp = new TimeSeries();
var settemp = new TimeSeries();
var settempm = new TimeSeries();
var settempp = new TimeSeries();
var pterm = new TimeSeries();
var iterm = new TimeSeries();
var dterm = new TimeSeries();
var pidval = new TimeSeries();
var avgpid = new TimeSeries();
var lastreqdone = 1;

$(document).ready(function(){
  createTimeline();

  $(".adv").hide();
  $("#toggleadv").click(function(){
    $(".adv").toggle();
  });
});

setInterval(function() {
  if (lastreqdone == 1) {
    $.getJSON({
      url: "/allstats",
      timeout: 500,
      success: function ( resp ) {
        curtemp.append(new Date().getTime(), resp.tempf);
        settemp.append(new Date().getTime(), resp.settemp);
        settempm.append(new Date().getTime(), resp.settemp-4);
        settempp.append(new Date().getTime(), resp.settemp+4);
        pterm.append(new Date().getTime(), resp.pterm);
        iterm.append(new Date().getTime(), resp.iterm);
        dterm.append(new Date().getTime(), resp.dterm);
        pidval.append(new Date().getTime(), resp.pidval);
        avgpid.append(new Date().getTime(), resp.avgpid);
        $("#curtemp").html(resp.tempf.toFixed(2));
        $("#settemp").html(resp.settemp.toFixed(2));
        $("#pterm").html(resp.pterm.toFixed(2));
        $("#iterm").html(resp.iterm.toFixed(2));
        $("#dterm").html(resp.dterm.toFixed(2));
        $("#pidval").html(resp.pidval.toFixed(2));
        $("#avgpid").html(resp.avgpid.toFixed(2));
      },
      complete: function () {
        lastreqdone = 1;
      }
    });
    lastreqdone = 0;
  }
}, 200);

function createTimeline() {
  var chart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  chart.addTimeSeries(settemp, {lineWidth:1,strokeStyle:'#ffff00'});
  chart.addTimeSeries(settempm, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(settempp, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(curtemp, {lineWidth:3,strokeStyle:'#ff0000'});
  chart.streamTo(document.getElementById("chart"), 500);

  var pidchart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  pidchart.addTimeSeries(pterm, {lineWidth:2,strokeStyle:'#ff0000'});
  pidchart.addTimeSeries(iterm, {lineWidth:2,strokeStyle:'#00ff00'});
  pidchart.addTimeSeries(dterm, {lineWidth:2,strokeStyle:'#0000ff'});
  pidchart.addTimeSeries(pidval, {lineWidth:2,strokeStyle:'#ffff00'});
  pidchart.addTimeSeries(avgpid, {lineWidth:2,strokeStyle:'#00ffff'});
  pidchart.streamTo(document.getElementById("pidchart"), 500);
}
<commit_msg>changed ajax loop to 100ms<commit_after>var curtemp = new TimeSeries();
var settemp = new TimeSeries();
var settempm = new TimeSeries();
var settempp = new TimeSeries();
var pterm = new TimeSeries();
var iterm = new TimeSeries();
var dterm = new TimeSeries();
var pidval = new TimeSeries();
var avgpid = new TimeSeries();
var lastreqdone = 1;

$(document).ready(function(){
  createTimeline();

  $(".adv").hide();
  $("#toggleadv").click(function(){
    $(".adv").toggle();
  });
});

setInterval(function() {
  if (lastreqdone == 1) {
    $.getJSON({
      url: "/allstats",
      timeout: 500,
      success: function ( resp ) {
        curtemp.append(new Date().getTime(), resp.tempf);
        settemp.append(new Date().getTime(), resp.settemp);
        settempm.append(new Date().getTime(), resp.settemp-4);
        settempp.append(new Date().getTime(), resp.settemp+4);
        pterm.append(new Date().getTime(), resp.pterm);
        iterm.append(new Date().getTime(), resp.iterm);
        dterm.append(new Date().getTime(), resp.dterm);
        pidval.append(new Date().getTime(), resp.pidval);
        avgpid.append(new Date().getTime(), resp.avgpid);
        $("#curtemp").html(resp.tempf.toFixed(2));
        $("#settemp").html(resp.settemp.toFixed(2));
        $("#pterm").html(resp.pterm.toFixed(2));
        $("#iterm").html(resp.iterm.toFixed(2));
        $("#dterm").html(resp.dterm.toFixed(2));
        $("#pidval").html(resp.pidval.toFixed(2));
        $("#avgpid").html(resp.avgpid.toFixed(2));
      },
      complete: function () {
        lastreqdone = 1;
      }
    });
    lastreqdone = 0;
  }
}, 100);

function createTimeline() {
  var chart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  chart.addTimeSeries(settemp, {lineWidth:1,strokeStyle:'#ffff00'});
  chart.addTimeSeries(settempm, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(settempp, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(curtemp, {lineWidth:3,strokeStyle:'#ff0000'});
  chart.streamTo(document.getElementById("chart"), 500);

  var pidchart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  pidchart.addTimeSeries(pterm, {lineWidth:2,strokeStyle:'#ff0000'});
  pidchart.addTimeSeries(iterm, {lineWidth:2,strokeStyle:'#00ff00'});
  pidchart.addTimeSeries(dterm, {lineWidth:2,strokeStyle:'#0000ff'});
  pidchart.addTimeSeries(pidval, {lineWidth:2,strokeStyle:'#ffff00'});
  pidchart.addTimeSeries(avgpid, {lineWidth:2,strokeStyle:'#00ffff'});
  pidchart.streamTo(document.getElementById("pidchart"), 500);
}
<|endoftext|>


<commit_before>/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

// Tests for stepping through Babel's compile output.

async function breakpointSteps(dbg, fixture, { line, column }, steps) {
  const { selectors: { getBreakpoint, getBreakpoints }, getState } = dbg;

  const filename = `fixtures/${fixture}/input.js`;
  await waitForSources(dbg, filename);

  ok(true, "Original sources exist");
  const source = findSource(dbg, filename);

  await selectSource(dbg, source);

  // Test that breakpoint is not off by a line.
  await addBreakpoint(dbg, source, line);

  is(getBreakpoints(getState()).size, 1, "One breakpoint exists");
  ok(
    getBreakpoint(getState(), { sourceId: source.id, line, column }),
    "Breakpoint has correct line"
  );

  const fnName = fixture.replace(/-([a-z])/g, (s, c) => c.toUpperCase());

  const invokeResult = invokeInTab(fnName);

  let invokeFailed = await Promise.race([
    waitForPaused(dbg),
    invokeResult.then(() => new Promise(() => {}), () => true)
  ]);

  if (invokeFailed) {
    return invokeResult;
  }

  assertPausedLocation(dbg);

  await removeBreakpoint(dbg, source.id, line, column);

  is(getBreakpoints(getState()).size, 0, "Breakpoint reverted");

  await runSteps(dbg, source, steps);

  await resume(dbg);

  // If the invoke errored later somehow, capture here so the error is
  // reported nicely.
  await invokeResult;

  ok(true, `Ran tests for ${fixture} at line ${line} column ${column}`);
}

async function runSteps(dbg, source, steps) {
  const { selectors: { getVisibleSelectedFrame }, getState } = dbg;

  for (const [i, [type, position]] of steps.entries()) {
    switch (type) {
      case "stepOver":
        await stepOver(dbg);
        break;
      case "stepIn":
        await stepIn(dbg);
        break;
      default:
        throw new Error("Unknown stepping type");
    }

    const { location } = getVisibleSelectedFrame(getState());

    is(location.sourceId, source.id, `Step ${i} has correct sourceId`);
    is(location.line, position.line, `Step ${i} has correct line`);
    is(location.column, position.column, `Step ${i} has correct column`);

    assertPausedLocation(dbg);
  }
}

add_task(async function() {
  requestLongerTimeout(2);

  const dbg = await initDebugger("doc-babel.html");

  await breakpointSteps(dbg, "step-over-for-of", { line: 4, column: 2 }, [
    ["stepOver", { line: 6, column: 2 }],
    ["stepOver", { line: 7, column: 4 }],
    ["stepOver", { line: 6, column: 2 }],
    ["stepOver", { line: 7, column: 4 }],
    ["stepOver", { line: 6, column: 2 }],
    ["stepOver", { line: 10, column: 2 }]
  ]);

  // This codifies the current behavior, but stepping twice over the for
  // header isn't ideal.
  await breakpointSteps(dbg, "step-over-for-of-array", { line: 3, column: 2 }, [
    ["stepOver", { line: 5, column: 2 }],
    ["stepOver", { line: 5, column: 7 }],
    ["stepOver", { line: 6, column: 4 }],
    ["stepOver", { line: 5, column: 2 }],
    ["stepOver", { line: 5, column: 7 }],
    ["stepOver", { line: 6, column: 4 }],
    ["stepOver", { line: 5, column: 2 }],
    ["stepOver", { line: 9, column: 2 }]
  ]);

  // The closure means it isn't actually possible to step into the for body,
  // and Babel doesn't map the _loop() call, so we step past it automatically.
  await breakpointSteps(
    dbg,
    "step-over-for-of-closure",
    { line: 6, column: 2 },
    [
      ["stepOver", { line: 8, column: 2 }],
      ["stepOver", { line: 12, column: 2 }]
    ]
  );

  // Same as the previous, not possible to step into the body. The less
  // complicated array logic makes it possible to step into the header at least,
  // but this does end up double-visiting the for head.
  await breakpointSteps(
    dbg,
    "step-over-for-of-array-closure",
    { line: 3, column: 2 },
    [
      ["stepOver", { line: 5, column: 2 }],
      ["stepOver", { line: 5, column: 7 }],
      ["stepOver", { line: 5, column: 2 }],
      ["stepOver", { line: 5, column: 7 }],
      ["stepOver", { line: 5, column: 2 }],
      ["stepOver", { line: 9, column: 2 }]
    ]
  );

  await breakpointSteps(
    dbg,
    "step-over-function-params",
    { line: 6, column: 2 },
    [["stepOver", { line: 7, column: 2 }], ["stepIn", { line: 2, column: 2 }]]
  );

  await breakpointSteps(
    dbg,
    "step-over-regenerator-await",
    { line: 2, column: 2 },
    [
      // Won't work until a fix to regenerator lands and we rebuild.
      // https://github.com/facebook/regenerator/issues/342
      // ["stepOver", { line: 4, column: 2 }],
    ]
  );
});
<commit_msg>Clean up the stepping tests (#5551)<commit_after>/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

// Tests for stepping through Babel's compile output.

async function breakpointSteps(dbg, fixture, { line, column }, steps) {
  const { selectors: { getBreakpoint, getBreakpoints }, getState } = dbg;

  const filename = `fixtures/${fixture}/input.js`;
  await waitForSources(dbg, filename);

  ok(true, "Original sources exist");
  const source = findSource(dbg, filename);

  await selectSource(dbg, source);

  // Test that breakpoint is not off by a line.
  await addBreakpoint(dbg, source, line);

  is(getBreakpoints(getState()).size, 1, "One breakpoint exists");

  ok(
    getBreakpoint(getState(), { sourceId: source.id, line, column }),
    "Breakpoint has correct line"
  );

  const fnName = fixture.replace(/-([a-z])/g, (s, c) => c.toUpperCase());

  const invokeResult = invokeInTab(fnName);

  let invokeFailed = await Promise.race([
    waitForPaused(dbg),
    invokeResult.then(() => new Promise(() => {}), () => true)
  ]);

  if (invokeFailed) {
    return invokeResult;
  }

  assertPausedLocation(dbg);

  await removeBreakpoint(dbg, source.id, line, column);

  is(getBreakpoints(getState()).size, 0, "Breakpoint reverted");

  await runSteps(dbg, source, steps);

  await resume(dbg);

  // If the invoke errored later somehow, capture here so the error is
  // reported nicely.
  await invokeResult;

  ok(true, `Ran tests for ${fixture} at line ${line} column ${column}`);
}

async function runSteps(dbg, source, steps) {
  const { selectors: { getVisibleSelectedFrame }, getState } = dbg;

  for (const [i, [type, position]] of steps.entries()) {
    switch (type) {
      case "stepOver":
        await stepOver(dbg);
        break;
      case "stepIn":
        await stepIn(dbg);
        break;
      default:
        throw new Error("Unknown stepping type");
    }

    const { location } = getVisibleSelectedFrame(getState());

    is(location.sourceId, source.id, `Step ${i} has correct sourceId`);
    is(location.line, position.line, `Step ${i} has correct line`);
    is(location.column, position.column, `Step ${i} has correct column`);

    assertPausedLocation(dbg);
  }
}

function testStepOverForOf(dbg) {
  return breakpointSteps(dbg, "step-over-for-of", { line: 4, column: 2 }, [
    ["stepOver", { line: 6, column: 2 }],
    ["stepOver", { line: 7, column: 4 }],
    ["stepOver", { line: 6, column: 2 }],
    ["stepOver", { line: 7, column: 4 }],
    ["stepOver", { line: 6, column: 2 }],
    ["stepOver", { line: 10, column: 2 }]
  ]);
}

// This codifies the current behavior, but stepping twice over the for
// header isn't ideal.
function testStepOverForOfArray(dbg) {
  return breakpointSteps(dbg, "step-over-for-of-array", { line: 3, column: 2 }, [
    ["stepOver", { line: 5, column: 2 }],
    ["stepOver", { line: 5, column: 7 }],
    ["stepOver", { line: 6, column: 4 }],
    ["stepOver", { line: 5, column: 2 }],
    ["stepOver", { line: 5, column: 7 }],
    ["stepOver", { line: 6, column: 4 }],
    ["stepOver", { line: 5, column: 2 }],
    ["stepOver", { line: 9, column: 2 }]
  ]);
}

// The closure means it isn't actually possible to step into the for body,
// and Babel doesn't map the _loop() call, so we step past it automatically.
function testStepOveForOfClosure(dbg) {
  return breakpointSteps(
    dbg,
    "step-over-for-of-closure",
    { line: 6, column: 2 },
    [
      ["stepOver", { line: 8, column: 2 }],
      ["stepOver", { line: 8, column: 2 }],
      ["stepOver", { line: 8, column: 2 }],
      ["stepOver", { line: 12, column: 2 }]
    ]
  );
}

// Same as the previous, not possible to step into the body. The less
// complicated array logic makes it possible to step into the header at least,
// but this does end up double-visiting the for head.
function testStepOverForOfArrayClosure(dbg) {
  return breakpointSteps(
    dbg,
    "step-over-for-of-array-closure",
    { line: 3, column: 2 },
    [
      ["stepOver", { line: 5, column: 2 }],
      ["stepOver", { line: 5, column: 7 }],
      ["stepOver", { line: 5, column: 2 }],
      ["stepOver", { line: 5, column: 7 }],
      ["stepOver", { line: 5, column: 2 }],
      ["stepOver", { line: 9, column: 2 }]
    ]
  );
}

function testStepOverFunctionParams(dbg) {
  return breakpointSteps(
    dbg,
    "step-over-function-params",
    { line: 6, column: 2 },
    [["stepOver", { line: 7, column: 2 }], ["stepIn", { line: 2, column: 2 }]]
  );
}

function testStepOverRegeneratorAwait(dbg) {
  return breakpointSteps(
    dbg,
    "step-over-regenerator-await",
    { line: 2, column: 2 },
    [
      // Won't work until a fix to regenerator lands and we rebuild.
      // https://github.com/facebook/regenerator/issues/342
      // ["stepOver", { line: 4, column: 2 }],
    ]
  );
}

add_task(async function() {
  requestLongerTimeout(4);

  const dbg = await initDebugger("doc-babel.html");

  await testStepOverForOf(dbg);
  await testStepOverForOfArray(dbg);
  await testStepOveForOfClosure(dbg);
  await testStepOverForOfArrayClosure(dbg);
  await testStepOverFunctionParams(dbg);
  await testStepOverRegeneratorAwait(dbg);
});
<|endoftext|>


<commit_before>/*global describe, beforeEach, module, inject, it, spyOn, expect, $ */
describe('uiScroll', function () {
    'use strict';

    angular.module('ui.scroll.test', [])
        .factory('myEmptyDatasource', [
            '$log', '$timeout', '$rootScope', function(console, $timeout, $rootScope) {
                var current, get, loading, revision;
                get = function(index, count, success) {
                    success([]);
                };

                return {
                    get: get
                };
            }
        ])

        .factory('myOnePageDatasource', [
            '$log', '$timeout', '$rootScope', function(console, $timeout, $rootScope) {
                var current, get, loading, revision;
                get = function(index, count, success) {
                    if (index === 1) {
                        success(['one', 'two', 'three']);
					} else {
                        success([]);
					}
                };

                return {
                    get: get
                };
            }
        ])

        .factory('myMultipageDatasource', [
            '$log', '$timeout', '$rootScope', function(console, $timeout, $rootScope) {
                var current, get, loading, revision;
                get = function(index, count, success) {
                    var result = [];
                    if (index > 0 && index <= 20) {
                        for (var i = index; i<index+count && i<=20; i++) {
                            result.push('item' + i);
						}
                    }
                    success(result);
                };

                return {
                    get: get
                };
            }
        ]);

    var sandbox = angular.element('
');

    beforeEach(module('ui.scroll'));
    beforeEach(module('ui.scroll.test'));

	var runTest = function(html, runTest, cleanupTest) {
		inject(function($rootScope, $compile, $window, $timeout) {
				var scroller = angular.element(html);
				var scope = $rootScope.$new();
				var sandbox = angular.element('
');
				angular.element(document).find('body').append(sandbox);
				sandbox.append(scroller);
				$compile(scroller)(scope);
				scope.$apply();
				$timeout.flush();

				runTest($window, sandbox);

				scroller.remove();
				scope.$destroy();

				if (cleanupTest) {
					cleanupTest($window, scope);
				}
			}
		)
	}

	describe('basic setup', function() {
			var html = '
{{$index}}: {{item}}
';

				it('should bind to window scroll and resize events and unbind upon scope destroy', function(){
				spyOn($.fn, 'bind').andCallThrough();
				spyOn($.fn, 'unbind').andCallThrough();
				runTest(html,
					function($window) {
						expect($.fn.bind.calls.length).toBe(2);
						expect($.fn.bind.calls[0].args[0]).toBe('resize');
						expect($.fn.bind.calls[0].object[0]).toBe($window);
						expect($.fn.bind.calls[1].args[0]).toBe('scroll');
						expect($.fn.bind.calls[1].object[0]).toBe($window);
						expect($._data($window, 'events')).toBeDefined();
					},
					function($window) {
						expect($.fn.unbind.calls.length).toBe(2);
						expect($.fn.unbind.calls[0].args[0]).toBe('resize');
						expect($.fn.unbind.calls[0].object[0]).toBe($window);
						expect($.fn.unbind.calls[1].args[0]).toBe('scroll');
						expect($.fn.unbind.calls[1].object[0]).toBe($window);
					}
				);
			});

			it('should create 2 divs of 0 height', function() {
				runTest(html,
					function($window, sandbox) {
						expect(sandbox.children().length).toBe(2);

						var topPadding = sandbox.children()[0];
						expect(topPadding.tagName.toLowerCase()).toBe('div');
						expect(angular.element(topPadding).css('height')).toBe('0px');

						var bottomPadding = sandbox.children()[1];
						expect(bottomPadding.tagName.toLowerCase()).toBe('div');
						expect(angular.element(bottomPadding).css('height')).toBe('0px');

					}
				);
			});

			it('should call get on the datasource 1 time ', function() {
				var spy;
				inject(function(myEmptyDatasource){
					spy = spyOn(myEmptyDatasource, 'get').andCallThrough();
				});
				runTest(html,
					function() {
						expect(spy.calls.length).toBe(2);
						expect(spy.calls[0].args[0]).toBe(1);
						expect(spy.calls[1].args[0]).toBe(-9);

					}
				);
			});
		}
	);

	describe('datasource with only 3 elements', function () {

		var html = '
{{$index}}: {{item}}
';

		it('should create 3 divs with data (+ 2 padding divs)', function() {
			runTest(html,
				function($window, sandbox) {
					expect(sandbox.children().length).toBe(5);

					var row1 = sandbox.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = sandbox.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = sandbox.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');
				}
			);
		});

		it('should call get on the datasource 3 times ', function() {
			var spy;
			inject(function(myOnePageDatasource){
				spy = spyOn(myOnePageDatasource, 'get').andCallThrough();
			runTest(html,
				function() {
					expect(spy.calls.length).toBe(3);

					expect(spy.calls[0].args[0]).toBe(1);  // gets 3 rows
					expect(spy.calls[1].args[0]).toBe(4);  // gets eof
					expect(spy.calls[2].args[0]).toBe(-9); // gets bof
				});
			});

		});
	});

	describe('datasource with 20 elements default buffer size (10) - constrained viewport', function () {

		var html = '

{{$index}}: {{item}}

';

		it('should create 6 divs with data (+ 2 padding divs)', function() {
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					expect(scroller.children().length).toBe(8);

					for (var i = 1; i< 7; i++) {
						var row = scroller.children()[i];
						expect(row.tagName.toLowerCase()).toBe('div');
						expect(row.innerHTML).toBe(i + ': item' + i);
					}

				}
			);
		});

		it('should call get on the datasource 3 times ', function() {
			var spy;
			inject(function(myMultipageDatasource){
				spy = spyOn(myMultipageDatasource, 'get').andCallThrough();
			});
			runTest(html,
				function($window, sandbox) {
					expect(spy.calls.length).toBe(3);

					expect(spy.calls[0].args[0]).toBe(1);
					expect(spy.calls[1].args[0]).toBe(4);
					expect(spy.calls[2].args[0]).toBe(-2);

				}
			);
		});

	});

    describe('datasource with 20 elements default buffer size (10) - unconstrained viewport', function () {

        return;

        var HTML = '
{{$index}}: {{item}}
';

        it('should create 20 divs with data (+ 2 padding divs)', inject(
            function ($rootScope, $compile) {
                var scroller = angular.element(HTML);
                sandbox.append(scroller);
                $compile(scroller)($rootScope);
                $rootScope.$apply();

                expect(sandbox.children().length).toBe(22);

                for (var i = 1; i< 21; i++) {
                    var row = sandbox.children()[i];
                    expect(row.tagName.toLowerCase()).toBe('div');
                    expect(row.innerHTML).toBe(i + ': item' + i);
                }

            }));

        it('should call get on the datasource 4 times ', inject(
            function ($rootScope, $compile, myMultipageDatasource) {

                var spy = spyOn(myMultipageDatasource, 'get').andCallThrough();
                var scroller = angular.element(HTML);
                sandbox.append(scroller);
                $compile(scroller)($rootScope);
                $rootScope.$apply();

                expect(spy.calls.length).toBe(4);

                expect(spy.calls[0].args[0]).toBe(1);
                expect(spy.calls[1].args[0]).toBe(11);
                expect(spy.calls[2].args[0]).toBe(21);
                expect(spy.calls[3].args[0]).toBe(-9);

            }));
    });

    describe('datasource with 20 elements buffer size 7 - unconstrained viewport', function () {

        return;

        var HTML = '
{{$index}}: {{item}}
';

        it('should create 20 divs with data (+ 2 padding divs)', inject(
            function ($rootScope, $compile) {
                var scroller = angular.element(HTML);
                sandbox.append(scroller);
                $compile(scroller)($rootScope);
                $rootScope.$apply();

                expect(sandbox.children().length).toBe(22);

                for (var i = 1; i< 21; i++) {
                    var row = sandbox.children()[i];
                    expect(row.tagName.toLowerCase()).toBe('div');
                    expect(row.innerHTML).toBe(i + ': item' + i);
                }

            }));

        it('should call get on the datasource 4 times ', inject(
            function ($rootScope, $compile, myMultipageDatasource) {

                var spy = spyOn(myMultipageDatasource, 'get').andCallThrough();
                var scroller = angular.element(HTML);
                sandbox.append(scroller);
                $compile(scroller)($rootScope);
                $rootScope.$apply();

                expect(spy.calls.length).toBe(5);

                expect(spy.calls[0].args[0]).toBe(1);
                expect(spy.calls[1].args[0]).toBe(8);
                expect(spy.calls[2].args[0]).toBe(15);
                expect(spy.calls[3].args[0]).toBe(21);
                expect(spy.calls[4].args[0]).toBe(-6);

            }));
    });

});<commit_msg>A few additional tests<commit_after>/*global describe, beforeEach, module, inject, it, spyOn, expect, $ */
describe('uiScroll', function () {
    'use strict';

    angular.module('ui.scroll.test', [])
        .factory('myEmptyDatasource', [
            '$log', '$timeout', '$rootScope', function(console, $timeout, $rootScope) {
                var current, get, loading, revision;
                get = function(index, count, success) {
                    success([]);
                };

                return {
                    get: get
                };
            }
        ])

        .factory('myOnePageDatasource', [
            '$log', '$timeout', '$rootScope', function(console, $timeout, $rootScope) {
                var current, get, loading, revision;
                get = function(index, count, success) {
                    if (index === 1) {
                        success(['one', 'two', 'three']);
					} else {
                        success([]);
					}
                };

                return {
                    get: get
                };
            }
        ])

        .factory('myMultipageDatasource', [
            '$log', '$timeout', '$rootScope', function(console, $timeout, $rootScope) {
                var current, get, loading, revision;
                get = function(index, count, success) {
                    var result = [];
					for (var i = index; i<index+count; i++) {
						if (i>0 && i<=20)
							result.push('item' + i);
					}
                    success(result);
                };

                return {
                    get: get
                };
            }
        ]);

    var sandbox = angular.element('
');

    beforeEach(module('ui.scroll'));
    beforeEach(module('ui.scroll.test'));

	var runTest = function(html, runTest, cleanupTest) {
		inject(function($rootScope, $compile, $window, $timeout) {
				var scroller = angular.element(html);
				var scope = $rootScope.$new();
				var sandbox = angular.element('
');
				angular.element(document).find('body').append(sandbox);
				sandbox.append(scroller);
				$compile(scroller)(scope);
				scope.$apply();
				$timeout.flush();

				runTest($window, sandbox);

				sandbox.remove();
				scope.$destroy();

				if (cleanupTest) {
					cleanupTest($window, scope);
				}
			}
		)
	}

	describe('basic setup', function() {
			var html = '
{{$index}}: {{item}}
';

				it('should bind to window scroll and resize events and unbind upon scope destroy', function(){
				spyOn($.fn, 'bind').andCallThrough();
				spyOn($.fn, 'unbind').andCallThrough();
				runTest(html,
					function($window) {
						expect($.fn.bind.calls.length).toBe(2);
						expect($.fn.bind.calls[0].args[0]).toBe('resize');
						expect($.fn.bind.calls[0].object[0]).toBe($window);
						expect($.fn.bind.calls[1].args[0]).toBe('scroll');
						expect($.fn.bind.calls[1].object[0]).toBe($window);
						expect($._data($window, 'events')).toBeDefined();
					},
					function($window) {
						expect($.fn.unbind.calls.length).toBe(2);
						expect($.fn.unbind.calls[0].args[0]).toBe('resize');
						expect($.fn.unbind.calls[0].object[0]).toBe($window);
						expect($.fn.unbind.calls[1].args[0]).toBe('scroll');
						expect($.fn.unbind.calls[1].object[0]).toBe($window);
					}
				);
			});

			it('should create 2 divs of 0 height', function() {
				runTest(html,
					function($window, sandbox) {
						expect(sandbox.children().length).toBe(2);

						var topPadding = sandbox.children()[0];
						expect(topPadding.tagName.toLowerCase()).toBe('div');
						expect(angular.element(topPadding).css('height')).toBe('0px');

						var bottomPadding = sandbox.children()[1];
						expect(bottomPadding.tagName.toLowerCase()).toBe('div');
						expect(angular.element(bottomPadding).css('height')).toBe('0px');

					}
				);
			});

			it('should call get on the datasource 1 time ', function() {
				var spy;
				inject(function(myEmptyDatasource){
					spy = spyOn(myEmptyDatasource, 'get').andCallThrough();
				});
				runTest(html,
					function() {
						expect(spy.calls.length).toBe(2);
						expect(spy.calls[0].args[0]).toBe(1);
						expect(spy.calls[1].args[0]).toBe(-9);

					}
				);
			});
		}
	);

	describe('datasource with only 3 elements', function () {

		var html = '
{{$index}}: {{item}}
';

		it('should create 3 divs with data (+ 2 padding divs)', function() {
			runTest(html,
				function($window, sandbox) {
					expect(sandbox.children().length).toBe(5);

					var row1 = sandbox.children()[1];
					expect(row1.tagName.toLowerCase()).toBe('div');
					expect(row1.innerHTML).toBe('1: one');

					var row2 = sandbox.children()[2];
					expect(row2.tagName.toLowerCase()).toBe('div');
					expect(row2.innerHTML).toBe('2: two');

					var row3 = sandbox.children()[3];
					expect(row3.tagName.toLowerCase()).toBe('div');
					expect(row3.innerHTML).toBe('3: three');
				}
			);
		});

		it('should call get on the datasource 3 times ', function() {
			var spy;
			inject(function(myOnePageDatasource){
				spy = spyOn(myOnePageDatasource, 'get').andCallThrough();
			runTest(html,
				function() {
					expect(spy.calls.length).toBe(3);

					expect(spy.calls[0].args[0]).toBe(1);  // gets 3 rows
					expect(spy.calls[1].args[0]).toBe(4);  // gets eof
					expect(spy.calls[2].args[0]).toBe(-9); // gets bof
				});
			});

		});
	});

	describe('datasource with 20 elements default buffer size (10) - constrained viewport', function () {

		var html = '

{{$index}}: {{item}}

';

		it('should create 6 divs with data (+ 2 padding divs)', function() {
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					expect(scroller.children().length).toBe(8);
					expect(scroller.scrollTop()).toBe(0);
					expect(scroller.children().css('height')).toBe('0px');
					expect(angular.element(scroller.children()[7]).css('height')).toBe('0px');

					for (var i = 1; i< 7; i++) {
						var row = scroller.children()[i];
						expect(row.tagName.toLowerCase()).toBe('div');
						expect(row.innerHTML).toBe(i + ': item' + i);
					}

				}
			);
		});

		it('should call get on the datasource 3 times ', function() {
			var spy;
			inject(function(myMultipageDatasource){
				spy = spyOn(myMultipageDatasource, 'get').andCallThrough();
			});
			runTest(html,
				function($window, sandbox) {
					expect(spy.calls.length).toBe(3);

					expect(spy.calls[0].args[0]).toBe(1);
					expect(spy.calls[1].args[0]).toBe(4);
					expect(spy.calls[2].args[0]).toBe(-2);

				}
			);
		});

		it('should create 3 more divs (9 divs total) with data (+ 2 padding divs)', function() {
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					scroller.scrollTop(100);
					scroller.trigger('scroll');
					inject(function($timeout){
						$timeout.flush();
						expect(scroller.children().length).toBe(11);
						expect(scroller.scrollTop()).toBe(40);
						expect(scroller.children().css('height')).toBe('0px');
						expect(angular.element(scroller.children()[10]).css('height')).toBe('0px');

						for (var i = 1; i< 10; i++) {
							var row = scroller.children()[i];
							expect(row.tagName.toLowerCase()).toBe('div');
							expect(row.innerHTML).toBe(i + ': item' + i);
						}
					});

				}
			);
		});

		it('should call get on the datasource 1 extra time (4 total) ', function() {
			var spy;
			inject(function(myMultipageDatasource){
				spy = spyOn(myMultipageDatasource, 'get').andCallThrough();
			});
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					scroller.scrollTop(100);
					scroller.trigger('scroll');
					expect(spy.calls.length).toBe(4);

					expect(spy.calls[0].args[0]).toBe(1);
					expect(spy.calls[1].args[0]).toBe(4);
					expect(spy.calls[2].args[0]).toBe(-2);
					expect(spy.calls[3].args[0]).toBe(7);

				}
			);
		});

		it('should clip 3 divs from the top and add 3 more divs to the bottom (9 divs total) (+ 2 padding divs)', function() {
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					scroller.scrollTop(100);
					scroller.trigger('scroll');
					scroller.scrollTop(400);
					scroller.trigger('scroll');
					inject(function($timeout){
						$timeout.flush();
						expect(scroller.children().length).toBe(11);
						expect(scroller.scrollTop()).toBe(160);
						expect(scroller.children().css('height')).toBe('120px');
						expect(angular.element(scroller.children()[10]).css('height')).toBe('0px');

						for (var i = 1; i< 10; i++) {
							var row = scroller.children()[i];
							expect(row.tagName.toLowerCase()).toBe('div');
							expect(row.innerHTML).toBe((i+3) + ': item' + (i+3));
						}
					});

				}
			);
		});

		it('should call get on the datasource 1 more time (4 total) ', function() {
			var spy;
			inject(function(myMultipageDatasource){
				spy = spyOn(myMultipageDatasource, 'get').andCallThrough();
			});
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					scroller.scrollTop(100);
					scroller.trigger('scroll');
					scroller.scrollTop(400);
					scroller.trigger('scroll');
					inject(function($timeout){
						$timeout.flush();
						expect(spy.calls.length).toBe(5);

						expect(spy.calls[0].args[0]).toBe(1);
						expect(spy.calls[1].args[0]).toBe(4);
						expect(spy.calls[2].args[0]).toBe(-2);
						expect(spy.calls[3].args[0]).toBe(7);
						expect(spy.calls[4].args[0]).toBe(10);
					});

				}
			);
		});

		it('should re-add 3 divs at the top and clip 3 divs from the bottom (9 divs total) (+ 2 padding divs)', function() {
			var flush;
			inject(function($timeout){flush = $timeout.flush;})
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					scroller.scrollTop(100);
					scroller.trigger('scroll');
					flush();
					scroller.scrollTop(400);
					scroller.trigger('scroll');
					flush();
					scroller.scrollTop(0);
					scroller.trigger('scroll');
					flush();

					//debugger

					expect(scroller.children().length).toBe(8);
					expect(scroller.scrollTop()).toBe(0);
					expect(scroller.children().css('height')).toBe('0px');
					expect(angular.element(scroller.children()[7]).css('height')).toBe('240px');

					for (var i = 1; i< 7; i++) {
						var row = scroller.children()[i];
						expect(row.tagName.toLowerCase()).toBe('div');
						//expect(row.innerHTML).toBe((i) + ': item' + (i));
					}

				}
			);
		});

		it('should call get on the datasource 1 more time (4 total) ', function() {
			var spy;
			inject(function(myMultipageDatasource){
				spy = spyOn(myMultipageDatasource, 'get').andCallThrough();
			});
			var flush;
			inject(function($timeout){flush = $timeout.flush;})
			runTest(html,
				function($window, sandbox) {
					var scroller = sandbox.children();
					scroller.scrollTop(100);
					scroller.trigger('scroll');
					flush();
					scroller.scrollTop(400);
					scroller.trigger('scroll');
					flush();
					scroller.scrollTop(0);
					scroller.trigger('scroll');
					flush();
					expect(spy.calls.length).toBe(7);

					expect(spy.calls[0].args[0]).toBe(1);
					expect(spy.calls[1].args[0]).toBe(4);
					expect(spy.calls[2].args[0]).toBe(-2);
					expect(spy.calls[3].args[0]).toBe(7);
					expect(spy.calls[4].args[0]).toBe(10);
					expect(spy.calls[5].args[0]).toBe(1);
					expect(spy.calls[6].args[0]).toBe(-2);

				}
			);
		});

	});

});<|endoftext|>


<commit_before>'use strict';

goog.require('goog.Promise');

describe('ContributionStatus', function(){
  let describedClass = KeepMeContributing.ContributionStatus;
  let describedInstanceFor = function(username, opt_format){
    let github = new KeepMeContributing.Github({
      username: username,
      // access to development server on test
      apiUrl: '/test/fixtures/github.com',
      format: opt_format
    });
    return new describedClass(github);
  };

  describe('#queryHasContributedAt', function(){

    let returnsTrueOrFalseBasedOnContributionsCount = function(describedInstance){

      let expectTheResultToBe = function(date, expected) {
        return describedInstance.queryHasContributedAt(date)
          .then(function(actual){ expect(actual).to.be(expected); });
      };

      context("the argument date's contribution count is 0", function(){
        it('returns false', function(){
          return expectTheResultToBe(new Date('2015-07-31'), false);
        });
      });

      context("the argument date's contribution count is 2", function(){
        it('returns true', function(){
          return expectTheResultToBe(new Date('2015-07-23'), true);
        });
      });

      context("the argument date's contribution count is 1", function(){
        it('returns true', function(){
          return expectTheResultToBe(new Date('2015-07-29'), true);
        });
      });

      context("the argument date's contribution count is not present", function(){
        it('returns false', function(){
          return expectTheResultToBe(new Date('2015-08-01'), false);
        });
      });

    };

    context('given a response of https://github.com/users/igrep/contributions', function(){
      let describedInstance = describedInstanceFor('igrep');
      returnsTrueOrFalseBasedOnContributionsCount(describedInstance);

      it('has correct endpoint URL', function(){
        expect(describedInstance.getEndpointUrl()).to.match(
          new RegExp('github\\.com/users/igrep/contributions$')
        );
      });
    });

    context('given a response of https://github.com/users/igrep/contributions.json', function(){
      let describedInstance = describedInstanceFor('igrep', KeepMeContributing.Github.Formats.JSON);
      returnsTrueOrFalseBasedOnContributionsCount(describedInstance);

      it('has correct endpoint URL', function(){
        expect(describedInstance.getEndpointUrl()).to.match(
          new RegExp('github\\.com/users/igrep/contributions\\.json$')
        );
      });
    });

    context('given no response from github.com', function(){
      let username = 'non_existing_user';
      let describedInstance = describedInstanceFor(username);

      it('throws an error to show the reponse was unavailable.', function(){
        return describedInstance.queryHasContributedAt(new Date())
          .then(
            function(){ expect().fail(); },
            function(error){
              expect(error.toString()).to.match(
                new RegExp(`Error: Couldn't get contribution calendar of ${username}`)
              );
            }.bind(this)
          )
        ;
      });

    });
  });

  /**
   * FIXME: complex test code.
   * Maybe I should test this method on the view model with less stubbed objects.
   */
  describe('startPolling', function(){
    // Immediately timeout to show failure when the specified event doesn't occur.
    this.timeout(100);

    before(function(){

      this.describedInstance = describedInstanceFor('igrep');

      this.stubQuery = sinon.stub(describedClass.prototype, 'queryHasContributedAt');

      this.expectTheDipatchedEventToBe = function(expectedEvent, done){

        goog.events.listen(this.describedInstance, expectedEvent, function(){
          expect(expectedEvent).to.be(expectedEvent);
          done();
        });
        this.describedInstance.startPolling(1);
      }.bind(this);
    });
    after(function(){
      this.stubQuery.restore();
    });

    context('when querying contribution status successfully', function(){
      before(function(){
        this.stubQueryResultAs = function(result){
          this.stubQuery.returns(new goog.Promise(function(resolve){ resolve(result); }));
        };
      });

      context('the answer is true', function(){
        before(function(){ this.stubQueryResultAs(true); });
        it('dispatches a contributed event', function(done){
          this.expectTheDipatchedEventToBe(KeepMeContributing.ContributionStatus.Events.CONTRIBUTED, done);
        });
      });

      context('the answer is false', function(){
        before(function(){ this.stubQueryResultAs(false); });
        it('dispatches a not_yet event', function(done){
          this.expectTheDipatchedEventToBe(KeepMeContributing.ContributionStatus.Events.NOT_YET, done);
        });
      });
    });

    context('when failed to query contribution status', function(){
      before(function(){
        this.stubQuery.returns(
          new goog.Promise(function(_, reject){
            reject(new Error('error caused by test'));
          })
        );
      });

      it('dispatches an error event', function(done){
        this.expectTheDipatchedEventToBe(KeepMeContributing.ContributionStatus.Events.ERROR, done);
      });

    });

  });
});
<commit_msg>delete fixme that I'm not going to fix<commit_after>'use strict';

goog.require('goog.Promise');

describe('ContributionStatus', function(){
  let describedClass = KeepMeContributing.ContributionStatus;
  let describedInstanceFor = function(username, opt_format){
    let github = new KeepMeContributing.Github({
      username: username,
      // access to development server on test
      apiUrl: '/test/fixtures/github.com',
      format: opt_format
    });
    return new describedClass(github);
  };

  describe('#queryHasContributedAt', function(){

    let returnsTrueOrFalseBasedOnContributionsCount = function(describedInstance){

      let expectTheResultToBe = function(date, expected) {
        return describedInstance.queryHasContributedAt(date)
          .then(function(actual){ expect(actual).to.be(expected); });
      };

      context("the argument date's contribution count is 0", function(){
        it('returns false', function(){
          return expectTheResultToBe(new Date('2015-07-31'), false);
        });
      });

      context("the argument date's contribution count is 2", function(){
        it('returns true', function(){
          return expectTheResultToBe(new Date('2015-07-23'), true);
        });
      });

      context("the argument date's contribution count is 1", function(){
        it('returns true', function(){
          return expectTheResultToBe(new Date('2015-07-29'), true);
        });
      });

      context("the argument date's contribution count is not present", function(){
        it('returns false', function(){
          return expectTheResultToBe(new Date('2015-08-01'), false);
        });
      });

    };

    context('given a response of https://github.com/users/igrep/contributions', function(){
      let describedInstance = describedInstanceFor('igrep');
      returnsTrueOrFalseBasedOnContributionsCount(describedInstance);

      it('has correct endpoint URL', function(){
        expect(describedInstance.getEndpointUrl()).to.match(
          new RegExp('github\\.com/users/igrep/contributions$')
        );
      });
    });

    context('given a response of https://github.com/users/igrep/contributions.json', function(){
      let describedInstance = describedInstanceFor('igrep', KeepMeContributing.Github.Formats.JSON);
      returnsTrueOrFalseBasedOnContributionsCount(describedInstance);

      it('has correct endpoint URL', function(){
        expect(describedInstance.getEndpointUrl()).to.match(
          new RegExp('github\\.com/users/igrep/contributions\\.json$')
        );
      });
    });

    context('given no response from github.com', function(){
      let username = 'non_existing_user';
      let describedInstance = describedInstanceFor(username);

      it('throws an error to show the reponse was unavailable.', function(){
        return describedInstance.queryHasContributedAt(new Date())
          .then(
            function(){ expect().fail(); },
            function(error){
              expect(error.toString()).to.match(
                new RegExp(`Error: Couldn't get contribution calendar of ${username}`)
              );
            }.bind(this)
          )
        ;
      });

    });
  });

  describe('startPolling', function(){
    // Immediately timeout to show failure when the specified event doesn't occur.
    this.timeout(100);

    before(function(){

      this.describedInstance = describedInstanceFor('igrep');

      this.stubQuery = sinon.stub(describedClass.prototype, 'queryHasContributedAt');

      this.expectTheDipatchedEventToBe = function(expectedEvent, done){

        goog.events.listen(this.describedInstance, expectedEvent, function(){
          expect(expectedEvent).to.be(expectedEvent);
          done();
        });
        this.describedInstance.startPolling(1);
      }.bind(this);
    });
    after(function(){
      this.stubQuery.restore();
    });

    context('when querying contribution status successfully', function(){
      before(function(){
        this.stubQueryResultAs = function(result){
          this.stubQuery.returns(new goog.Promise(function(resolve){ resolve(result); }));
        };
      });

      context('the answer is true', function(){
        before(function(){ this.stubQueryResultAs(true); });
        it('dispatches a contributed event', function(done){
          this.expectTheDipatchedEventToBe(KeepMeContributing.ContributionStatus.Events.CONTRIBUTED, done);
        });
      });

      context('the answer is false', function(){
        before(function(){ this.stubQueryResultAs(false); });
        it('dispatches a not_yet event', function(done){
          this.expectTheDipatchedEventToBe(KeepMeContributing.ContributionStatus.Events.NOT_YET, done);
        });
      });
    });

    context('when failed to query contribution status', function(){
      before(function(){
        this.stubQuery.returns(
          new goog.Promise(function(_, reject){
            reject(new Error('error caused by test'));
          })
        );
      });

      it('dispatches an error event', function(done){
        this.expectTheDipatchedEventToBe(KeepMeContributing.ContributionStatus.Events.ERROR, done);
      });

    });

  });
});
<|endoftext|>


<commit_before>"use strict";
var StepNC = require('../../../../../StepNCNode/build/Release/StepNC');
var find = new StepNC.Finder();

function exeFromId(id){
	let ws = {
		"id": id,
		"name": find.GetExecutableName(id)
	}
	if (find.IsWorkingstep(id)) {
		ws["type"] = "workingstep";
		return ws;
	} else if (find.IsSelective(id)) {
		ws["type"] = "selective";
	} else if (find.IsWorkplan(id)) {
		ws["type"] = "workplan";
	}
	ws["children"] = find.GetNestedExecutableAll(id).map(exeFromId);
	return ws;
}

function _getExeFromId(req,res){
	if(req.params.ncId && req.params.wsId){
		let ncId = req.params.ncId;
		let wsId = req.params.wsId;
		var id_new = parseInt(wsId);
		find.OpenProject(ncId);
		res.status(200).send(exeFromId(id_new));
	}
}

function _getMwp(req,res){
	if(req.params.ncId){
		let ncId = req.params.ncId;
		find.OpenProject(ncId);
		var mwpId = find.GetMainWorkplan();
		res.status(200).send(exeFromId(mwpId));
	}
}

module.exports = function(app){
	//FIXME: Route currently only works for a model that is in StepNCViewers root directory
	//ncId will have to be used to find the path in the future

	//This route gets the executable given an Id and returns a JSON object with its
	//name, id and all its children (and children's children, etc.)
	app.router.get('/v2/nc/projects/:ncId/workplan/:wsId',_getExeFromId);

	//This route gets the main workplan for the project that is specified by
	//ncId
	app.router.get('/v2/nc/projects/:ncId/workplan',_getMwp);
	//app.router.get('/v2/nc/projects',_getprojs);
}
<commit_msg>Fixed some spacing in step.js<commit_after>"use strict";
var StepNC = require('../../../../../StepNCNode/build/Release/StepNC');
var find = new StepNC.Finder();

function exeFromId(id) {
	let ws = {
		"id": id,
		"name": find.GetExecutableName(id)
	}
	if (find.IsWorkingstep(id)) {
		ws["type"] = "workingstep";
		return ws;
	} else if (find.IsSelective(id)) {
		ws["type"] = "selective";
	} else if (find.IsWorkplan(id)) {
		ws["type"] = "workplan";
	}
	ws["children"] = find.GetNestedExecutableAll(id).map(exeFromId);
	return ws;
}

function _getExeFromId(req, res) {
	if (req.params.ncId && req.params.wsId){
		let ncId = req.params.ncId;
		let wsId = req.params.wsId;
		var id_new = parseInt(wsId);
		find.OpenProject(ncId);
		res.status(200).send(exeFromId(id_new));
	}
}

function _getMwp(req, res) {
	if (req.params.ncId) {
		let ncId = req.params.ncId;
		find.OpenProject(ncId);
		var mwpId = find.GetMainWorkplan();
		res.status(200).send(exeFromId(mwpId));
	}
}

module.exports = function(app) {
	//FIXME: Route currently only works for a model that is in StepNCViewers root directory
	//ncId will have to be used to find the path in the future

	//This route gets the executable given an Id and returns a JSON object with its
	//name, id and all its children (and children's children, etc.)
	app.router.get('/v2/nc/projects/:ncId/workplan/:wsId',_getExeFromId);

	//This route gets the main workplan for the project that is specified by
	//ncId
	app.router.get('/v2/nc/projects/:ncId/workplan',_getMwp);
	//app.router.get('/v2/nc/projects',_getprojs);
}
<|endoftext|>