<commit_before>
let iframe; // Store on the script level
let spacer; // Store on the script level
let notification; // Store on the script level
const expandedHeight = '100%';
const defaultHeight = '47px';
const TIMEOUT_NOTIFICATION = 3000;

/**
 * createIframe
 * @return {object} iframe DOM Element
 */
function createIframe(){
  let iframe = document.createElement('iframe');
  iframe.id="wwinject"
  iframe.src='chrome-extension://'+chrome.runtime.id+'/main.html';
  iframe.style.width = '100%';
  iframe.style.position = 'fixed';
  iframe.style.left = 0;
  iframe.style.bottom = 0;
  iframe.style.border = 'none';
  iframe.style.height = defaultHeight; /* 45px height corresponds with plugin height in stylesheet. We're using 46 here to account for the borderTop/boxShadowTop */
  iframe.style.zIndex = '2147483647';
  iframe.style.display = 'block';
  iframe.style.opacity = '1';
  iframe.style.margin = '0px';
  iframe.style.visibility = 'visible';
  iframe.style.top = 'initial';
  iframe.style.right = 'initial';
  iframe.style.transition = 'all 250ms ease-in-out'
  document.body.append(iframe);
  return iframe;
}

/**
 * createFooterSpacer
 * @return {object} div DOM Element
 */
function createFooterSpacer(){
  let paddingFooterDiv = document.createElement('div');
  paddingFooterDiv.style.height = defaultHeight;
  document.body.append(paddingFooterDiv);
  return paddingFooterDiv;
}

/**
 * createNotification
 * @return {object} div DOM Element
 */
function createNotification(text) {
  const notificationDiv = document.createElement('div');
  /* don't split into multi-line. will break. @mceoin */
  notificationDiv.innerHTML = "
"+text+"
"
  document.body.append(notificationDiv);
  return notificationDiv;
}

/**
 * removeNotification
 * @return {object} div DOM Element
 */
function removeNotification() {
  if (notification !== undefined) { notification.remove(); };
}

/**
 * initApp
 */
function initApp() {
  iframe = createIframe();
  spacer = createFooterSpacer();
}

/**
 * destroyApp
 */
function destroyApp() {
  iframe.remove();
  spacer.remove();
  iframe = undefined;
  spacer = undefined;
}

/**
 * Add listener to remove and create the iframe.
 */
 chrome.storage.onChanged.addListener(
  (sender) => {
    const { wikiwebFooterActive } = sender;
    if (wikiwebFooterActive && !wikiwebFooterActive.newValue) {
      destroyApp();
      removeNotification();
      notification = createNotification(
        'WikiWeb turned OFF'
      );
      setTimeout(function() {
        removeNotification();
      }, TIMEOUT_NOTIFICATION);
    } else if (wikiwebFooterActive) {
      removeNotification();
      notification = createNotification(
        'WikiWeb turned ON'
      );
      setTimeout(function() {
        removeNotification()
      }, TIMEOUT_NOTIFICATION);
      initApp();
    }
  }
);

/**
 * getLocalStore State
 * @param  {Function} cb
 */
function getLocalStore (cb) {
  chrome.storage.local.get(['wikiwebFooterActive', 'wikiwebExpanded'], function (res) {
    var { wikiwebFooterActive, wikiwebExpanded } = res;
    const err = false;
    cb(
      err,
      wikiwebFooterActive,
      wikiwebExpanded
    );
  });
}

/** Set the inital extension button state **/
getLocalStore(function(err, wikiwebFooterActive) {
  if (wikiwebFooterActive){
    initApp();
  } else if ( wikiwebFooterActive === undefined ){ // App loadd for first time
    initApp();
    chrome.storage.local.set({ wikiwebFooterActive: true });
    notification = createNotification(
      'WikiWeb turned ON'
    );
    setTimeout(function() {
      removeNotification()
    }, TIMEOUT_NOTIFICATION);
  }
});
/** Kick Off the App on Page Load **/

chrome.runtime.onMessage.addListener(
  function(request, sender) {
    console.log(request, sender);
    const wikiwebExpanded = request.wikiwebExpanded;
    if (iframe && wikiwebExpanded){
      iframe.style.height = expandedHeight;
      document.body.style.overflow = 'hidden';
   } else if (iframe && !wikiwebExpanded) {
     iframe.style.height = defaultHeight;
     document.body.style.overflow = '';
   }
});
<commit_msg>Killing console log.<commit_after>
let iframe; // Store on the script level
let spacer; // Store on the script level
let notification; // Store on the script level
const expandedHeight = '100%';
const defaultHeight = '47px';
const TIMEOUT_NOTIFICATION = 3000;

/**
 * createIframe
 * @return {object} iframe DOM Element
 */
function createIframe(){
  let iframe = document.createElement('iframe');
  iframe.id="wwinject"
  iframe.src='chrome-extension://'+chrome.runtime.id+'/main.html';
  iframe.style.width = '100%';
  iframe.style.position = 'fixed';
  iframe.style.left = 0;
  iframe.style.bottom = 0;
  iframe.style.border = 'none';
  iframe.style.height = defaultHeight; /* 45px height corresponds with plugin height in stylesheet. We're using 46 here to account for the borderTop/boxShadowTop */
  iframe.style.zIndex = '2147483647';
  iframe.style.display = 'block';
  iframe.style.opacity = '1';
  iframe.style.margin = '0px';
  iframe.style.visibility = 'visible';
  iframe.style.top = 'initial';
  iframe.style.right = 'initial';
  iframe.style.transition = 'all 250ms ease-in-out'
  document.body.append(iframe);
  return iframe;
}

/**
 * createFooterSpacer
 * @return {object} div DOM Element
 */
function createFooterSpacer(){
  let paddingFooterDiv = document.createElement('div');
  paddingFooterDiv.style.height = defaultHeight;
  document.body.append(paddingFooterDiv);
  return paddingFooterDiv;
}

/**
 * createNotification
 * @return {object} div DOM Element
 */
function createNotification(text) {
  const notificationDiv = document.createElement('div');
  /* don't split into multi-line. will break. @mceoin */
  notificationDiv.innerHTML = "
"+text+"
"
  document.body.append(notificationDiv);
  return notificationDiv;
}

/**
 * removeNotification
 * @return {object} div DOM Element
 */
function removeNotification() {
  if (notification !== undefined) { notification.remove(); };
}

/**
 * initApp
 */
function initApp() {
  iframe = createIframe();
  spacer = createFooterSpacer();
}

/**
 * destroyApp
 */
function destroyApp() {
  iframe.remove();
  spacer.remove();
  iframe = undefined;
  spacer = undefined;
}

/**
 * Add listener to remove and create the iframe.
 */
 chrome.storage.onChanged.addListener(
  (sender) => {
    const { wikiwebFooterActive } = sender;
    if (wikiwebFooterActive && !wikiwebFooterActive.newValue) {
      destroyApp();
      removeNotification();
      notification = createNotification(
        'WikiWeb turned OFF'
      );
      setTimeout(function() {
        removeNotification();
      }, TIMEOUT_NOTIFICATION);
    } else if (wikiwebFooterActive) {
      removeNotification();
      notification = createNotification(
        'WikiWeb turned ON'
      );
      setTimeout(function() {
        removeNotification()
      }, TIMEOUT_NOTIFICATION);
      initApp();
    }
  }
);

/**
 * getLocalStore State
 * @param  {Function} cb
 */
function getLocalStore (cb) {
  chrome.storage.local.get(['wikiwebFooterActive', 'wikiwebExpanded'], function (res) {
    var { wikiwebFooterActive, wikiwebExpanded } = res;
    const err = false;
    cb(
      err,
      wikiwebFooterActive,
      wikiwebExpanded
    );
  });
}

/** Set the inital extension button state **/
getLocalStore(function(err, wikiwebFooterActive) {
  if (wikiwebFooterActive){
    initApp();
  } else if ( wikiwebFooterActive === undefined ){ // App loadd for first time
    initApp();
    chrome.storage.local.set({ wikiwebFooterActive: true });
    notification = createNotification(
      'WikiWeb turned ON'
    );
    setTimeout(function() {
      removeNotification()
    }, TIMEOUT_NOTIFICATION);
  }
});
/** Kick Off the App on Page Load **/

chrome.runtime.onMessage.addListener(
  function(request, sender) {
    const wikiwebExpanded = request.wikiwebExpanded;
    if (iframe && wikiwebExpanded){
      iframe.style.height = expandedHeight;
      document.body.style.overflow = 'hidden';
   } else if (iframe && !wikiwebExpanded) {
     iframe.style.height = defaultHeight;
     document.body.style.overflow = '';
   }
});
<|endoftext|>


<commit_before>apos.define('apostrophe-attachments-crop-editor', {
  extend: 'apostrophe-modal',
  source: 'crop-editor',
  construct: function(self, options) {
    self.attachment = options.attachment;

    // Use afterShow so that .width() works
    self.afterShow = function() {

      self.$cropImage = self.$el.find('[data-crop-image]');
      self.cropWidth = self.$cropImage.width();
      self.$saveButton = self.$el.find('[data-apos-save]');
      self.busy(true);
      self.$cropImage.attr('src', apos.attachments.url(self.attachment));
      self.viewWidth = self.scaleDown(self.attachment.width);
      self.viewHeight = self.scaleDown(self.attachment.height);
      self.$cropImage.css('width', self.viewWidth + 'px');
      self.$cropImage.css('height', self.viewHeight + 'px');
      self.initCropper();
      self.busy(false);
    };

    self.initCropper = function() {
      var cropperOpts = { viewMode: 1, autoCropArea: 1 };
      if (options.aspectRatio) {
        cropperOpts.aspectRatio = options.aspectRatio[0] / options.aspectRatio[1];
      }
      if (options.minSize) {
        cropperOpts.minCropBoxWidth = self.scaleDown(options.minSize[0]);
        cropperOpts.minCropBoxHeight = self.scaleDown(options.minSize[1]);
      }
      if (options.crop) {
        cropperOpts.data = self.deserializeCrop(options.crop);
      }
      self.$cropImage.cropper(cropperOpts);
    };

    self.getCropperData = function() {
      if (!self.$cropImage) {
        return null;
      }
      return self.$cropImage.cropper("getData", true);
    };

    self.saveContent = function(callback) {
      // Ask the server to render this crop
      self.busy(true);
      self.attachment.crop = self.serializeCrop(self.getCropperData());
      self.api('crop', { _id: self.attachment._id, crop: self.attachment.crop }, function(data) {
        if (data.status !== 'ok') {
          alert('An error occurred.');
          return callback('fail');
        }
        self.busy(false);
        self.options.cropped(self.attachment.crop);
        return callback(null);
      }, function() {
        self.busy(false);
        alert('Server error, please retry');
        return callback('fail');
      });
    };

    self.scaleDown = function(coord) {
      return Math.round(coord * self.cropWidth / self.attachment.width);
    };

    self.scaleUp = function(coord) {
      return Math.round(coord * self.attachment.width / self.cropWidth);
    };

    self.deserializeCrop = function(data) {
      return {
        y: data.top,
        x: data.left,
        width: data.width,
        height: data.height
      };
    };

    self.serializeCrop = function(data) {
      return {
        top: data.y,
        left: data.x,
        width: data.width,
        height: data.height
      };
    };

    self.busy = function(state) {
      self.$saveButton.attr('data-busy', state ? '1' : '0');
    };
  }
});
<commit_msg>fixed bug in image cropper that occured when original src image was larger than 'full' size.  fixed by requesting 'original' size attachment for cropper, and by reimplementing scaleUp/scaleDown serialize methods<commit_after>apos.define('apostrophe-attachments-crop-editor', {
  extend: 'apostrophe-modal',
  source: 'crop-editor',
  construct: function(self, options) {
    self.attachment = options.attachment;

    // Use afterShow so that .width() works
    self.afterShow = function() {

      self.$cropImage = self.$el.find('[data-crop-image]');
      self.cropWidth = self.$cropImage.width();
      self.$saveButton = self.$el.find('[data-apos-save]');
      self.busy(true);
      self.$cropImage.attr('src', apos.attachments.url(self.attachment, {size: 'original'} ));
      self.viewWidth = self.scaleDown(self.attachment.width);
      self.viewHeight = self.scaleDown(self.attachment.height);
      self.$cropImage.css('width', self.viewWidth + 'px');
      self.$cropImage.css('height', self.viewHeight + 'px');
      self.initCropper();
      self.busy(false);
    };

    self.initCropper = function() {
      var cropperOpts = { viewMode: 1, autoCropArea: 1 };
      if (options.aspectRatio) {
        cropperOpts.aspectRatio = options.aspectRatio[0] / options.aspectRatio[1];
      }
      if (options.minSize) {
        cropperOpts.minCropBoxWidth = self.scaleDown(options.minSize[0]);
        cropperOpts.minCropBoxHeight = self.scaleDown(options.minSize[1]);
      }
      if (options.crop) {
        cropperOpts.data = self.deserializeCrop(options.crop);
      }
      self.$cropImage.cropper(cropperOpts);
    };

    self.getCropperData = function() {
      if (!self.$cropImage) {
        return null;
      }
      return self.$cropImage.cropper("getData", true);
    };

    self.saveContent = function(callback) {
      // Ask the server to render this crop
      self.busy(true);
      self.attachment.crop = self.serializeCrop(self.getCropperData());
      self.api('crop', { _id: self.attachment._id, crop: self.attachment.crop }, function(data) {
        if (data.status !== 'ok') {
          alert('An error occurred.');
          return callback('fail');
        }
        self.busy(false);
        self.options.cropped(self.attachment.crop);
        return callback(null);
      }, function() {
        self.busy(false);
        alert('Server error, please retry');
        return callback('fail');
      });
    };

    self.scaleDown = function(coord) {
      return Math.round(coord * self.cropWidth / self.attachment.width);
    };

    self.scaleUp = function(coord) {
      return Math.round(coord * self.attachment.width / self.cropWidth);
    };

    self.deserializeCrop = function(data) {
      return {
        y: self.scaleDown(data.top),
        x: self.scaleDown(data.left),
        width: self.scaleDown(data.width),
        height: self.scaleDown(data.height)
      };
    };

    self.serializeCrop = function(data) {
      return {
        top: self.scaleUp(data.y),
        left: self.scaleUp(data.x),
        width: self.scaleUp(data.width),
        height: self.scaleUp(data.height)
      };
    };

    self.busy = function(state) {
      self.$saveButton.attr('data-busy', state ? '1' : '0');
    };
  }
});
<|endoftext|>


<commit_before>/**
 * Courses view. Displays courses and their sections
 * @param {HTMLElement} target- The element in which this view should be rendered
 * @param {Object} params - API params for this view
 * @return {undefined}
 * @memberOf Yacs.views
 */
Yacs.views.courses = function (target, params) {
  params.show_sections = params.show_periods = true;

  /**
   * When a section is clicked, toggle whether it is selected.
   * Uses Yacs.user for POT of selections
   * When a course is clicked, toggle its sections as selected.
   * Uses CSS for POT of selections
   */
  var bindListeners = function () {
    Yacs.on('click', target.querySelectorAll('section'), function (section) {
      Yacs.user.removeSelection(section.dataset.id) ||
        Yacs.user.addSelection(section.dataset.id);
    });

    Yacs.on('click', target.querySelectorAll('course-info'), function (courseInfo) {
      var courseSelected = courseInfo.parentElement.classList.contains('selected');
      if (courseSelected) {
        var sections = courseInfo.parentElement.querySelectorAll('section');
        Yacs.user.removeSelections(map(sections, function (section) {
          return section.dataset.id;
        }));
      } else {
        var sections = courseInfo.parentElement.querySelectorAll('section:not(.closed)');
        Yacs.user.addSelections(map(sections, function (section) {
          return section.dataset.id;
        }));
      }
    });
  };

  /**
   * Update selected status (class) of sections and courses. If all open
   * sections of a course are selected, the course is considered selected.
   */
  var updateSelected = function () {
    var selected = Yacs.user.getSelections();
    each(target.querySelectorAll('course'), function (course) {
      var courseSelected = false;
      var sections = course.querySelectorAll('section');
      if (sections.length > 0) {
        courseSelected = true;
        each(sections, function (section) {
          var sectionSelected = selected.indexOf(section.dataset.id) !== -1;
          section.classList.toggle('selected', sectionSelected);
          if (!sectionSelected && !section.classList.contains('closed'))
            courseSelected = false;
        });
      }
      course.classList.toggle('selected', courseSelected);
    });
  };

  Yacs.models.courses.query(params, function (data, success) {
    if (success) {
      Yacs.render(target, 'courses', data)
      Yacs.observe('selection', document.querySelector('courses'), updateSelected);
      bindListeners();
      updateSelected();
    }
  });
};
<commit_msg>Fixed missing semicolon<commit_after>/**
 * Courses view. Displays courses and their sections
 * @param {HTMLElement} target- The element in which this view should be rendered
 * @param {Object} params - API params for this view
 * @return {undefined}
 * @memberOf Yacs.views
 */
Yacs.views.courses = function (target, params) {
  params.show_sections = params.show_periods = true;

  /**
   * When a section is clicked, toggle whether it is selected.
   * Uses Yacs.user for POT of selections
   * When a course is clicked, toggle its sections as selected.
   * Uses CSS for POT of selections
   */
  var bindListeners = function () {
    Yacs.on('click', target.querySelectorAll('section'), function (section) {
      Yacs.user.removeSelection(section.dataset.id) ||
        Yacs.user.addSelection(section.dataset.id);
    });

    Yacs.on('click', target.querySelectorAll('course-info'), function (courseInfo) {
      var courseSelected = courseInfo.parentElement.classList.contains('selected');
      if (courseSelected) {
        var sections = courseInfo.parentElement.querySelectorAll('section');
        Yacs.user.removeSelections(map(sections, function (section) {
          return section.dataset.id;
        }));
      } else {
        var sections = courseInfo.parentElement.querySelectorAll('section:not(.closed)');
        Yacs.user.addSelections(map(sections, function (section) {
          return section.dataset.id;
        }));
      }
    });
  };

  /**
   * Update selected status (class) of sections and courses. If all open
   * sections of a course are selected, the course is considered selected.
   */
  var updateSelected = function () {
    var selected = Yacs.user.getSelections();
    each(target.querySelectorAll('course'), function (course) {
      var courseSelected = false;
      var sections = course.querySelectorAll('section');
      if (sections.length > 0) {
        courseSelected = true;
        each(sections, function (section) {
          var sectionSelected = selected.indexOf(section.dataset.id) !== -1;
          section.classList.toggle('selected', sectionSelected);
          if (!sectionSelected && !section.classList.contains('closed'))
            courseSelected = false;
        });
      }
      course.classList.toggle('selected', courseSelected);
    });
  };

  Yacs.models.courses.query(params, function (data, success) {
    if (success) {
      Yacs.render(target, 'courses', data);
      Yacs.observe('selection', document.querySelector('courses'), updateSelected);
      bindListeners();
      updateSelected();
    }
  });
};
<|endoftext|>


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

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  };

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    // scrollElements = $('[data-scroll-element]');
    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      console.log("Set visibility");
      console.log("nextOffset", nextOffset);
      console.log("limit", limit);
      if(inValidRange(nextOffset, limit)) {
        // element.removeClass('disabled');
        my_removeClass(element, 'disabled');
      } else {
        // element.addClass('disabled');
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      console.log("setVisibilityAll");
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
          clipboard,
          notification;

      clipboard = new Clipboard(this);

      var notify = function(clipboardNotification, notificationText) {
          notification = $($(clipboardNotification));
          notification.text(notificationText);
          notification.addClass('in').delay(1400).queue(function() {
              notification.removeClass('in');
              $(this).dequeue();
          })
      };

      var notifySuccess = function(e) {
          notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
          //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
          notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;

      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });
    })

    each(document.querySelectorAll('[data-moment]'), function(el) {
      console.log(el);
      var time = moment(parseInt(el.textContent));
      console.log(time);
      el.textcontent = time.fromNow();
    });

    // $('[data-moment]').each(function() {
    //   var $this;
    //
    //   $this = $(this);
    //
    //   var time = moment(parseInt($this.text()));
    //   $this.text(time.fromNow());
    // });
  });

})();
<commit_msg>each for moment elements<commit_after>(function() {
  'use strict';

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  };

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    // scrollElements = $('[data-scroll-element]');
    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      console.log("Set visibility");
      console.log("nextOffset", nextOffset);
      console.log("limit", limit);
      if(inValidRange(nextOffset, limit)) {
        // element.removeClass('disabled');
        my_removeClass(element, 'disabled');
      } else {
        // element.addClass('disabled');
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      console.log("setVisibilityAll");
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
          clipboard,
          notification;

      clipboard = new Clipboard(this);

      var notify = function(clipboardNotification, notificationText) {
          notification = $($(clipboardNotification));
          notification.text(notificationText);
          notification.addClass('in').delay(1400).queue(function() {
              notification.removeClass('in');
              $(this).dequeue();
          })
      };

      var notifySuccess = function(e) {
          notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
          //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
          notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;

      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });
    })

    each(document.querySelectorAll('[data-moment]'), function(el) {
      // console.log(el);
      var time = moment(parseInt(el.textContent));
      // console.log(time);
      el.textcontent = time.fromNow();
    });

    $('[data-moment]').each(function() {
      var $this;

      $this = $(this);

      console.log($this);

      var time = moment(parseInt($this.text()));
      console.log(time);
      $this.text(time.fromNow());
    });
  });

})();
<|endoftext|>


<commit_before>// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Great success! All the File APIs are supported.
} else {
  alert('The File APIs are not fully supported in this browser.');
}

function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0];
    var fileDisplayArea = document.getElementById('fileDisplayArea');
    if (f) {
      var reader = new FileReader();
      reader.onload = function(e) {
	      var contents = e.target.result;
        alert( "Got the file.n"
              +"name: " + f.name + "n"
              +"type: " + f.type + "n"
              +"size: " + f.size + " bytesn"
              + "starts with: " + contents.substr(1, contents.indexOf("n"))
        );
        fileDisplayArea.innerText = reader.result;
        parseData(reader.result);
      }
      reader.readAsText(f);
    }
    else {
       alert("Failed to load file");
    }
}

function parseData(inputfile) {

        var ESParray = [];
        var chartType = document.getElementById("chartType");

        ESParray = tsvToArray(inputfile);

        var sensortype = ESParray.map(function(elem){
            return elem[0]
        });

        var data = ESParray.map(function(elem){
            return elem[2]
        });

        var temparray = ESParray.filter(function(elem){
            return elem[0] == "temp"
        });
        var tempdata = temparray.map(function(elem){
            return elem[2]
        });

        var humiarray = ESParray.filter(function(elem){
            return elem[0] == "humi"
        });
        var humidata = humiarray.map(function(elem){
            return elem[2]
        });

        var timevalue = temparray.map(function(elem){
            var dateString = moment.unix(elem[4]/1000).format('MM/DD/YYYY HH:mm');
            return dateString;
        });

        console.log(tempdata)

        sensortype  = sensortype.filter(function(elem, i, sensortype) {
                return sensortype.indexOf(elem) === i;
            }
        );

        sensortype.map(function(elem){
            var o = document.createElement("option");
            o.value = elem;
            o.text = elem;
            chartType.appendChild(o);
        });

        console.log(timevalue);
        console.log(sensortype);
        drawChart(timevalue, tempdata);
}

function tsvToArray (tsv) {
    rows  = tsv.split("\n");
    return rows.map(function (row) {
    	return row.split("\t");
    });
};

function httpGetAsync(theUrl, callback){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
httpGetAsync("/meshygarden.tsv.example", parseData);

var chartOptions = {
  legend: {
    display: true,
    position: 'top',
    labels: {
      boxWidth: 80,
      fontColor: 'black'
    }
  },
  scales: {
    xAxes: [{
      type: "time",
      time: {
        format: 'MM/DD/YYYY HH:mm'
     }
    }],
  }
};

function drawChart(x, y1){
    var ctx = document.getElementById('myChart').getContext('2d');

    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: x,
            datasets: [{
                label: 'temp',
                data: y1,
                backgroundColor: "rgba(153,255,51,0.4)"
            }/*, {
                label: 'humidity',
                data: y2,
                backgroundColor: "rgba(255,153,0,0.4)"
            }*/]
        },
        options: chartOptions
    });

var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");

select1.onchange = function() {
    // empty select2
    while (select2.firstChild) {
        select2.removeChild(select2.firstChild);
    }
    if (select1.selectedIndex == 0) {
        return;
    }
    for (var i = select1.selectedIndex; i < select1.options.length; i++) {
        var o = document.createElement("option");
        o.value = select1.options[i].value;
        o.text = select1.options[i].text;
        select2.appendChild(o);
    }
}

}
<commit_msg>Grab tsv file for chart from peoplesopen.net instead of local file system.<commit_after>// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Great success! All the File APIs are supported.
} else {
  alert('The File APIs are not fully supported in this browser.');
}

function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0];
    var fileDisplayArea = document.getElementById('fileDisplayArea');
    if (f) {
      var reader = new FileReader();
      reader.onload = function(e) {
	      var contents = e.target.result;
        alert( "Got the file.n"
              +"name: " + f.name + "n"
              +"type: " + f.type + "n"
              +"size: " + f.size + " bytesn"
              + "starts with: " + contents.substr(1, contents.indexOf("n"))
        );
        fileDisplayArea.innerText = reader.result;
        parseData(reader.result);
      }
      reader.readAsText(f);
    }
    else {
       alert("Failed to load file");
    }
}

function parseData(inputfile) {

        var ESParray = [];
        var chartType = document.getElementById("chartType");

        ESParray = tsvToArray(inputfile);

        var sensortype = ESParray.map(function(elem){
            return elem[0]
        });

        var data = ESParray.map(function(elem){
            return elem[2]
        });

        var temparray = ESParray.filter(function(elem){
            return elem[0] == "temp"
        });
        var tempdata = temparray.map(function(elem){
            return elem[2]
        });

        var humiarray = ESParray.filter(function(elem){
            return elem[0] == "humi"
        });
        var humidata = humiarray.map(function(elem){
            return elem[2]
        });

        var timevalue = temparray.map(function(elem){
            var dateString = moment.unix(elem[4]/1000).format('MM/DD/YYYY HH:mm');
            return dateString;
        });

        console.log(tempdata)

        sensortype  = sensortype.filter(function(elem, i, sensortype) {
                return sensortype.indexOf(elem) === i;
            }
        );

        sensortype.map(function(elem){
            var o = document.createElement("option");
            o.value = elem;
            o.text = elem;
            chartType.appendChild(o);
        });

        console.log(timevalue);
        console.log(sensortype);
        drawChart(timevalue, tempdata);
}

function tsvToArray (tsv) {
    rows  = tsv.split("\n");
    return rows.map(function (row) {
    	return row.split("\t");
    });
};

function httpGetAsync(theUrl, callback){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
httpGetAsync("https://peoplesopen.net/meshygarden.tsv", parseData);

var chartOptions = {
  legend: {
    display: true,
    position: 'top',
    labels: {
      boxWidth: 80,
      fontColor: 'black'
    }
  },
  scales: {
    xAxes: [{
      type: "time",
      time: {
        format: 'MM/DD/YYYY HH:mm'
     }
    }],
  }
};

function drawChart(x, y1){
    var ctx = document.getElementById('myChart').getContext('2d');

    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: x,
            datasets: [{
                label: 'temp',
                data: y1,
                backgroundColor: "rgba(153,255,51,0.4)"
            }/*, {
                label: 'humidity',
                data: y2,
                backgroundColor: "rgba(255,153,0,0.4)"
            }*/]
        },
        options: chartOptions
    });

var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");

select1.onchange = function() {
    // empty select2
    while (select2.firstChild) {
        select2.removeChild(select2.firstChild);
    }
    if (select1.selectedIndex == 0) {
        return;
    }
    for (var i = select1.selectedIndex; i < select1.options.length; i++) {
        var o = document.createElement("option");
        o.value = select1.options[i].value;
        o.text = select1.options[i].text;
        select2.appendChild(o);
    }
}

}
<|endoftext|>


<commit_before>Ext.BLANK_IMAGE_URL = '/assets/ext/resources/images/default/s.gif';

Ext.namespace(
'Vps', 'Vpc',
'Vps.Component',
'Vps.User.Login',
'Vps.Auto',
'Vps.Form'
);

Ext.applyIf(Array.prototype, {

    //to use array.each directly
    each : function(fn, scope){
        Ext.each(this, fn, scope);
    },

    //add is alias for push
    add : function() {
        this.push.apply(this, arguments);
    }
});

Ext.onReady(function()
{
//     Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    if (Ext.QuickTips) {
        Ext.QuickTips.init();
    }

    if (Ext.isIE6) {
        Ext.each(Ext.DomQuery.select('.addHover'), function(el) {
            var extEl = Ext.fly(el);
            extEl.hover(
                function() { this.addClass('hover'); },
                function() { this.removeClass('hover'); },
                extEl
            );
        });
    }
});

Vps.application = { version: '{$application.version}' };

Vps.callWithErrorHandler = function(fn, scope) {
    if (Vps.debug) {
        //call without error handler
        return fn.call(scope || window);
    }
    try {
        return fn.call(scope || window);
    } catch(e) {
        if (e.toString) e = e.toString();
        if (e.message) e = e.message;
        if(Ext.get('loading')) {
            Ext.get('loading').fadeOut({remove: true});
        }
        if (Ext.Msg) {
            Ext.Msg.alert('Error', "Ein Fehler ist aufgetreten.");
        }
        Ext.Ajax.request({
            url: '/vps/error/error/jsonMail',
            params: {msg: e}
        });
    }
};

Vps.include =  function(url, restart) {
    Ext.Ajax.request({
        url: url,
        success: function(response, options)  {
            s = document.createElement('script');
            s.setAttribute('type', 'text/javascript');
            s.appendChild(document.createTextNode(response.responseText));
            document.getElementsByTagName("head")[0].appendChild(s);
            if (restart) Vps.restart();
        }
    });
};
Vps.restart = function() {
    if (Vps.currentViewport) {
        Vps.currentViewport.onDestroy();
        delete Vps.currentViewport;
    }
    Vps.main();
};

var restart = Vps.restart;
var include = Vps.include;<commit_msg>css dateien auch  nachladen<commit_after>Ext.BLANK_IMAGE_URL = '/assets/ext/resources/images/default/s.gif';

Ext.namespace(
'Vps', 'Vpc',
'Vps.Component',
'Vps.User.Login',
'Vps.Auto',
'Vps.Form'
);

Ext.applyIf(Array.prototype, {

    //to use array.each directly
    each : function(fn, scope){
        Ext.each(this, fn, scope);
    },

    //add is alias for push
    add : function() {
        this.push.apply(this, arguments);
    }
});

Ext.onReady(function()
{
//     Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    if (Ext.QuickTips) {
        Ext.QuickTips.init();
    }

    if (Ext.isIE6) {
        Ext.each(Ext.DomQuery.select('.addHover'), function(el) {
            var extEl = Ext.fly(el);
            extEl.hover(
                function() { this.addClass('hover'); },
                function() { this.removeClass('hover'); },
                extEl
            );
        });
    }
});

Vps.application = { version: '{$application.version}' };

Vps.callWithErrorHandler = function(fn, scope) {
    if (Vps.debug) {
        //call without error handler
        return fn.call(scope || window);
    }
    try {
        return fn.call(scope || window);
    } catch(e) {
        if (e.toString) e = e.toString();
        if (e.message) e = e.message;
        if(Ext.get('loading')) {
            Ext.get('loading').fadeOut({remove: true});
        }
        if (Ext.Msg) {
            Ext.Msg.alert('Error', "Ein Fehler ist aufgetreten.");
        }
        Ext.Ajax.request({
            url: '/vps/error/error/jsonMail',
            params: {msg: e}
        });
    }
};

Vps.include =  function(url, restart) {
    Ext.Ajax.request({
        url: url,
        success: function(response, options)  {
            if (url.substr(-4) == '.css') {
                var s = document.createElement('style');
                s.setAttribute('type', 'text/css');
            } else {
                var s = document.createElement('script');
                s.setAttribute('type', 'text/javascript');
            }
            s.appendChild(document.createTextNode(response.responseText));
            document.getElementsByTagName("head")[0].appendChild(s);
            if (restart) Vps.restart();
        }
    });
};
Vps.restart = function() {
    if (Vps.currentViewport) {
        Vps.currentViewport.onDestroy();
        delete Vps.currentViewport;
    }
    Vps.main();
};

var restart = Vps.restart;
var include = Vps.include;<|endoftext|>


<commit_before>/**
 * Dependencies
 */

var _ = require("lodash");
var path = require("path");

var gulp = require("gulp");
var gutil = require("gulp-util");

var clean = require("gulp-clean");
var stylus = require("gulp-stylus");
var prefix = require("gulp-autoprefixer");
var connect = require("gulp-connect");
var gutil = require("gulp-util");
var jshint = require("gulp-jshint");
var stylish = require("jshint-stylish");

var mochaPhantomJS = require("gulp-mocha-phantomjs");
var karma = require("gulp-karma");

var webpack = require("webpack");

/**
 * App Configuration
 */

var config = {
  src: "app",
  dest: "dist",
  test: "dist-test",
  srcFullPath: path.join(__dirname, "app"),
  destFullPath: path.join(__dirname, "dist"),
  testFullPath: path.join(__dirname, "dist-test"),
  root: __dirname,

  js: "js",
  assets: "assets",
  styles: "styles",

  port: 3000,
  testPort: 3001
};

config.webpack = {
  context: config.srcFullPath,
  cache: true,
  entry: {
    main: "./js/main.js"
  },
  output: {
    path: path.join(config.destFullPath, config.js),
    publicPath: config.js + "/",
    filename: "[name].bundle.js",
    chunkFilename: "[id].bundle.js",
    sourceMapFilename: "[file].map"
  },
  module: {
    loaders: [
      { test: /\.css$/, loader: "style-loader!css-loader" },
    ]
  },
  resolve: {
    alias: {
      "underscore": "lodash"
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      jQuery: "jquery",
      $: "jquery",
      _: "lodash"
    })
  ]
};

/**
 * Composite Tasks
 */

gulp.task("default", ["watch"], function () {});

gulp.task("build", ["lint", "test-phantom"], function () {
  gulp.run("clean");
  gulp.run("copy");
  gulp.run("build:css");
  gulp.run("build:js");
});

gulp.task("build-dev", ["clean", "copy", "build:css", "build:js-dev"]);

gulp.task("watch", ["build-dev"], function () {
  gulp.watch(path.join(config.srcFullPath, "**/*"), ["build-dev"]);
});

gulp.task("reload", ["build-dev", "server"], function () {
  gulp.watch(path.join(config.srcFullPath, "**/*"), ["build-dev", "reload:go"]);
});

gulp.task("test", ["build:test", "server:test"], function () {
  gulp.watch(path.join(config.srcFullPath, "**/*"), function () {
    gulp.run("build:test");
  });
});

gulp.task("test-phantom", ["build:test"], function () {
  return gulp
    .src("dist/spec/test-runner.html")
    .pipe(mochaPhantomJS());
});

gulp.task("test-karma", function () {
  return gulp.src("app/spec/tests/**/*")
    .pipe(karma({
      configFile: "karma.conf.js",
      action: "run"
    }));
});

/**
 * Component Tasks
 */

gulp.task("clean", function () {
  return gulp.src(path.join(config.dest, "*"))
    .pipe(clean());
});

gulp.task("copy", function () {
  return gulp.src(
    path.join(config.srcFullPath, config.assets, "**/*"),
    { base: path.join(config.srcFullPath, config.assets) }
    )
    .pipe(gulp.dest(config.destFullPath));
});

gulp.task("lint", function () {
  return gulp.src([
    path.join(config.srcFullPath, "js", "**/*.js"),
    path.join(config.srcFullPath, "spec/tests/**/*.js"),
    path.join(config.root, "*.js"),
  ])
    .pipe(jshint(path.join(config.root, ".jshintrc")))
    .pipe(jshint.reporter(stylish))
    .pipe(jshint.reporter("fail"));
});

gulp.task("server", function () {
  return connect.server({
    root: [config.destFullPath],
    open: {},
    livereload: true,
    port: config.port
  }).apply(this, arguments);
});

gulp.task("server:test", function () {
  return connect.server({
    root: [config.testFullPath],
    open: {
      file: "test-runner.html"
    },
    livereload: true,
    port: config.testPort
  }).apply(this.arguments);
});

gulp.task("reload:go", function () {
  return gulp.src(path.join(config.srcFullPath, "**/*"))
    .pipe(connect.reload());
});

/**
 * CSS
 */

gulp.task("build:css", function () {
  return gulp.src(path.join(config.srcFullPath, config.styles, "*"))
    .pipe(stylus({
      use: ["axis-css"],
      set: ["compress"],
      define: { "ie8": true }
    }))
    .pipe(prefix("last 1 version", "> 1%", "ie 8"))
    .pipe(gulp.dest(path.join(config.destFullPath, "styles")));
});

/**
 * JS
 */

gulp.task("build:js", function (callback) {
  var webpackConf = _.extend({}, config.webpack);

  webpackConf.plugins = webpackConf.plugins.concat([
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify("production")
      }
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin()
  ]);

  webpack(webpackConf, function (err, stats) {
    if (err) {
      throw new gutil.PluginError("build:js", err);
    }
    gutil.log("[build:js]", stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task("build:js-dev", function (callback) {

  var webpackConf = _.extend({}, config.webpack, {
    devtool: "sourcemap",
    debug: true
  });

  webpack(webpackConf, function (err, stats) {
    if (err) {
      throw new gutil.PluginError("build:js-dev", err);
    }
    gutil.log("[build:js-dev]", stats.toString({
      colors: true
    }));
    callback();
  });
});

/**
 * Tests
 */

gulp.task("build:test", function (callback) {
  gulp.src(path.join(config.srcFullPath, "spec/test-runner.html"))
    .pipe(gulp.dest(config.testFullPath));

  var webpackConf = _.extend({}, config.webpack, {
    entry: {
      test: "./spec/test-runner.js"
    },
    output: {
      path: config.testFullPath,
      publicPath: "/",
      filename: "[name].bundle.js"
    },
    devtool: "sourcemap",
    debug: true
  });

  webpack(webpackConf, function (err) {
    if (err) {
      throw new gutil.PluginError("build:test", err);
    }
    callback();
  });
});
<commit_msg>add _ as alias for lodash; improve imports through hardcoded app path<commit_after>/**
 * Dependencies
 */

var _ = require("lodash");
var path = require("path");

var gulp = require("gulp");
var gutil = require("gulp-util");

var clean = require("gulp-clean");
var stylus = require("gulp-stylus");
var prefix = require("gulp-autoprefixer");
var connect = require("gulp-connect");
var gutil = require("gulp-util");
var jshint = require("gulp-jshint");
var stylish = require("jshint-stylish");

var mochaPhantomJS = require("gulp-mocha-phantomjs");
var karma = require("gulp-karma");

var webpack = require("webpack");

/**
 * App Configuration
 */

var config = {
  src: "app",
  dest: "dist",
  test: "dist-test",
  srcFullPath: path.join(__dirname, "app"),
  destFullPath: path.join(__dirname, "dist"),
  testFullPath: path.join(__dirname, "dist-test"),
  root: __dirname,

  js: "js",
  assets: "assets",
  styles: "styles",

  port: 3000,
  testPort: 3001
};

config.webpack = {
  context: config.srcFullPath,
  cache: true,
  entry: {
    main: "./js/main.js"
  },
  output: {
    path: path.join(config.destFullPath, config.js),
    publicPath: config.js + "/",
    filename: "[name].bundle.js",
    chunkFilename: "[id].bundle.js",
    sourceMapFilename: "[file].map"
  },
  module: {
    loaders: [
      { test: /\.css$/, loader: "style-loader!css-loader" },
    ]
  },
  resolve: {
    alias: {
      "_": "lodash",
      "underscore": "lodash",
      "app": config.srcFullPath
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      jQuery: "jquery",
      $: "jquery",
      _: "lodash"
    })
  ]
};

/**
 * Composite Tasks
 */

gulp.task("default", ["watch"], function () {});

gulp.task("build", ["lint", "test-phantom"], function () {
  gulp.run("clean");
  gulp.run("copy");
  gulp.run("build:css");
  gulp.run("build:js");
});

gulp.task("build-dev", ["clean", "copy", "build:css", "build:js-dev"]);

gulp.task("watch", ["build-dev"], function () {
  gulp.watch(path.join(config.srcFullPath, "**/*"), ["build-dev"]);
});

gulp.task("reload", ["build-dev", "server"], function () {
  gulp.watch(path.join(config.srcFullPath, "**/*"), ["build-dev", "reload:go"]);
});

gulp.task("test", ["build:test", "server:test"], function () {
  gulp.watch(path.join(config.srcFullPath, "**/*"), function () {
    gulp.run("build:test");
  });
});

gulp.task("test-phantom", ["build:test"], function () {
  return gulp
    .src("dist/spec/test-runner.html")
    .pipe(mochaPhantomJS());
});

gulp.task("test-karma", function () {
  return gulp.src("app/spec/tests/**/*")
    .pipe(karma({
      configFile: "karma.conf.js",
      action: "run"
    }));
});

/**
 * Component Tasks
 */

gulp.task("clean", function () {
  return gulp.src(path.join(config.dest, "*"))
    .pipe(clean());
});

gulp.task("copy", function () {
  return gulp.src(
    path.join(config.srcFullPath, config.assets, "**/*"),
    { base: path.join(config.srcFullPath, config.assets) }
    )
    .pipe(gulp.dest(config.destFullPath));
});

gulp.task("lint", function () {
  return gulp.src([
    path.join(config.srcFullPath, "js", "**/*.js"),
    path.join(config.srcFullPath, "spec/tests/**/*.js"),
    path.join(config.root, "*.js"),
  ])
    .pipe(jshint(path.join(config.root, ".jshintrc")))
    .pipe(jshint.reporter(stylish))
    .pipe(jshint.reporter("fail"));
});

gulp.task("server", function () {
  return connect.server({
    root: [config.destFullPath],
    open: {},
    livereload: true,
    port: config.port
  }).apply(this, arguments);
});

gulp.task("server:test", function () {
  return connect.server({
    root: [config.testFullPath],
    open: {
      file: "test-runner.html"
    },
    livereload: true,
    port: config.testPort
  }).apply(this.arguments);
});

gulp.task("reload:go", function () {
  return gulp.src(path.join(config.srcFullPath, "**/*"))
    .pipe(connect.reload());
});

/**
 * CSS
 */

gulp.task("build:css", function () {
  return gulp.src(path.join(config.srcFullPath, config.styles, "*"))
    .pipe(stylus({
      use: ["axis-css"],
      set: ["compress"],
      define: { "ie8": true }
    }))
    .pipe(prefix("last 1 version", "> 1%", "ie 8"))
    .pipe(gulp.dest(path.join(config.destFullPath, "styles")));
});

/**
 * JS
 */

gulp.task("build:js", function (callback) {
  var webpackConf = _.extend({}, config.webpack);

  webpackConf.plugins = webpackConf.plugins.concat([
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify("production")
      }
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin()
  ]);

  webpack(webpackConf, function (err, stats) {
    if (err) {
      throw new gutil.PluginError("build:js", err);
    }
    gutil.log("[build:js]", stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task("build:js-dev", function (callback) {

  var webpackConf = _.extend({}, config.webpack, {
    devtool: "sourcemap",
    debug: true
  });

  webpack(webpackConf, function (err, stats) {
    if (err) {
      throw new gutil.PluginError("build:js-dev", err);
    }
    gutil.log("[build:js-dev]", stats.toString({
      colors: true
    }));
    callback();
  });
});

/**
 * Tests
 */

gulp.task("build:test", function (callback) {
  gulp.src(path.join(config.srcFullPath, "spec/test-runner.html"))
    .pipe(gulp.dest(config.testFullPath));

  var webpackConf = _.extend({}, config.webpack, {
    entry: {
      test: "./spec/test-runner.js"
    },
    output: {
      path: config.testFullPath,
      publicPath: "/",
      filename: "[name].bundle.js"
    },
    devtool: "sourcemap",
    debug: true
  });

  webpack(webpackConf, function (err) {
    if (err) {
      throw new gutil.PluginError("build:test", err);
    }
    callback();
  });
});
<|endoftext|>


<commit_before>angular.module("noteApp")
    .factory("localService", ["$q", "lodash", function($q, lodash) {
        "use strict";
        /* category's data structure

            1. category: {
                id: uuid,
                title: string,
                collection: {
                    count: number,
                    entries: [{
                        id: uuid, // @note except content
                        title: string,
                        created: time,
                        modified: time
                    }]
                },
                created: time,
                modified: time
            }
            ====== In LocalStorge ======
            id => {
                id: uuid,
                title: string,
                collection: {
                    count: number,
                    entries: [noteIDs]
                },
                created: string,
                modified: string
            }

            2. allCategoris: {
                count: number,
                entries: [{
                    id: uuid, // @category except collection
                    title: string,
                    created: time,
                    modified: time
                }]
            }
            ====== In LocalStorge ======
            ID => {count: number, entries: [categoryIDs]}

        */

        /* note's data structure

            1. note: {
                id: uuid,
                title: string,
                content: string,
                created: time,
                modified: time
            }
            ====== In LocalStorge ======
            id => {
                id: uuid,
                title: string,
                content: string,
                created: time,
                modified: time
            }

        */
        var ID = "poplark-angular-note-storage";
        var storage = {
            __load: function(key) {
                var result = {
                    status: 200,
                    data: null
                }
                var item = localStorage.getItem(key);
                if(!item) {
                    result.status = 404;
                } else {
                    try {
                        result.data = JSON.parse(item);
                    } catch(err) {
                        localStorage.removeItem(key);
                        result.status = 404;
                    }
                }
                return result;
            },
            __save: function(item, key) {
                var result = {
                    status: 200,
                    data: null
                }
                if(key) {
                    localStorage.setItem(key, JSON.stringify(item));
                    result.data = item;
                } else if(item.id) {
                    item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                } else {
                    item.id = UUID.generate();
                    item.created = item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                }
                return result;
            },
            __remove: function(key) {
                var result = {
                    status: 200,
                    data: null
                }
                var item = localStorage.getItem(key);
                if(!item) {
                    result.status = 404;
                } else {
                    try {
                        var p = JSON.parse(item);
                        result.data = p;
                    } catch(err) {
                        result.status = 500;
                    } finally {
                        localStorage.removeItem(key);
                    }
                }
                return result;
            },
            __addOneToAllCategories: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(ID);
                // todo if else status
                loadedResult.data.entries.push(id);
                loadedResult.data.count += 1;
                that.__save(loadedResult.data, ID);
            },
            __removeOneFromAllCategories: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(ID);
                // todo if else status
                lodash.remove(loadedResult.data.entries, id);
                loadedResult.data.count -= 1;
                that.__save(loadedResult.data, ID);
            },
            __addOneToCategoryCollection: function(categoryID, noteID) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(categoryID);
                // todo if else status
                loadedResult.data.collection.entries.push(noteID);
                loadedResult.data.collection.count += 1;
                that.__save(loadedResult.data, categoryID);
            },
            __removeOneFromCategoryCollection: function(categoryID, noteID) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(categoryID);
                // todo if else status
                lodash.remove(loadedResult.data.collection.entries, noteID);
                loadedResult.data.collection.count -= 1;
                that.__save(loadedResult.data, categoryID);
            },
            queryAllCategories: function() {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();

                var loadedResult = that.__load(ID);
                if(200 === loadedResult.status) {
                    // loadedResult.data: {count: number, entries: [categoryIDs]}
                    var data = {count: 0, entries: []};
                    loadedResult.data.entries.forEach(function(categoryID, index) {
                        var p = that.__load(categoryID);
                        if(200 === p.status) {
                            var x = lodash.pick(p.data, ["id", "title", "created", "modified"]);
                            data.count += 1;
                            data.entries.push(x);
                        } else {
                            that.__removeOneFromAllCategories(categoryID);
                            // todo if else status
                        }
                    });
                    result.data = data;
                    deferred.resolve(result);
                } else if(404 === loadedResult.status) {
                    var p = {
                        count: 0,
                        entries: []
                    }
                    localStorage.setItem(ID, JSON.stringify(p));
                    result.data = p;
                    deferred.reject(result);
                } else {
                    result.status = 400;
                    deferred.reject(result);
                }
                return deferred.promise;
            },
            addCategory: function(category) {
                // category: {title, contains}
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                // validate - title is a none-empty string and contains is an empty Array
                // todo more validation
                if(("string" !== typeof category.title) || !category.title || !(category.contains instanceof Array) || 0 !== category.contains.length) {
                    result.status = 400;
                    deferred.reject(result);
                } else {
                    var savedResult = that.__save(category);
                    if(200 === savedResult.status) {
                        result.data = savedResult.data;
                        deferred.resolve(result);
                    } else {
                        result.status = 500;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            deleteCategory: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                if("string" !== typeof id || !id) {
                    result.status = 404;
                    deferred.reject(result);
                } else {
                    var removedResult = that.__remove(id);
                    if(200 === removedResult.status) {
                        result.data = removedResult.data;
                        deferred.resolve(result);
                    } else {
                        result.status = removedResult.status;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            queryCategory: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                if("string" !== typeof id || !id) {
                    result.status = 404;
                    deferred.reject(result);
                } else {
                    var loadedResult = that.__load(id);
                    if(200 === loadedResult.status) {
                        // loadedResult.data: {id, title, collection: {count, entries: [noteIDs]}, created, modified}
                        var data = lodash.pick(loadedResult.data, ["id", "title", "created", "modified"]);
                        data.collection = {count: 0, entries: []};
                        loadedResult.data.collection.entries.forEach(function(noteID, index) {
                            var p = that.__load(noteID);
                            if(200 === p.status) {
                                var x = lodash.pick(p.data, ["id", "title", "created", "modified"]);
                                data.collection.count += 1;
                                data.collection.entries.push(x);
                            } else {
                                that.__removeOneFromCategoryCollection(id, noteID);
                            }
                        });
                        result.data = data;
                        deferred.resolve(result);
                    } else {
                        result.status = loadedResult.status;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            updateCategory: function() {
            },
            queryAllNotes: function(category) {
                var deferred = $q.defer();
                var result = {
                    status: 200,
                    data: [{
                            'title': '1. Nexus S',
                            'content': 'Fast just got faster with Nexus S.'
                        }, {
                            'title': '2. Motorola XOOM™ with Wi-Fi',
                            'content': 'The Next, Next Generation tablet.'
                        }, {
                            'title': '3. MOTOROLA XOOM™',
                            'content': 'The Next, Next Generation tablet.'
                        }]
                }
                deferred.resolve(result);
                return deferred.promise;
            },
            addNote: function() {
            },
            deleteNote: function(){
            },
            queryNote: function() {
            },
            updateNote: function() {
            }
        }
        return storage;
    }]).factory("remoteService", ["$http", function($http) {
        // todo
    }]);
<commit_msg>addCategory updateCategory<commit_after>angular.module("noteApp")
    .factory("localService", ["$q", "lodash", function($q, lodash) {
        "use strict";
        /* category's data structure

            1. category: {
                id: uuid,
                title: string,
                collection: {
                    count: number,
                    entries: [{
                        id: uuid, // @note except content
                        title: string,
                        created: time,
                        modified: time
                    }]
                },
                created: time,
                modified: time
            }
            ====== In LocalStorge ======
            id => {
                id: uuid,
                title: string,
                collection: {
                    count: number,
                    entries: [noteIDs]
                },
                created: string,
                modified: string
            }

            2. allCategoris: {
                count: number,
                entries: [{
                    id: uuid, // @category except collection
                    title: string,
                    created: time,
                    modified: time
                }]
            }
            ====== In LocalStorge ======
            ID => {count: number, entries: [categoryIDs]}

        */

        /* note's data structure

            1. note: {
                id: uuid,
                title: string,
                content: string,
                created: time,
                modified: time
            }
            ====== In LocalStorge ======
            id => {
                id: uuid,
                title: string,
                content: string,
                created: time,
                modified: time
            }

        */
        var ID = "poplark-angular-note-storage";
        var storage = {
            __load: function(key) {
                var result = {
                    status: 200,
                    data: null
                }
                var item = localStorage.getItem(key);
                if(!item) {
                    result.status = 404;
                } else {
                    try {
                        result.data = JSON.parse(item);
                    } catch(err) {
                        localStorage.removeItem(key);
                        result.status = 404;
                    }
                }
                return result;
            },
            __save: function(item, key) {
                var result = {
                    status: 200,
                    data: null
                }
                if(key) {
                    localStorage.setItem(key, JSON.stringify(item));
                    result.data = item;
                } else if(item.id) {
                    item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                } else {
                    item.id = UUID.generate();
                    item.created = item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                }
                return result;
            },
            __remove: function(key) {
                var result = {
                    status: 200,
                    data: null
                }
                var item = localStorage.getItem(key);
                if(!item) {
                    result.status = 404;
                } else {
                    try {
                        var p = JSON.parse(item);
                        result.data = p;
                    } catch(err) {
                        result.status = 500;
                    } finally {
                        localStorage.removeItem(key);
                    }
                }
                return result;
            },
            __addOneToAllCategories: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(ID);
                // todo if else status
                loadedResult.data.entries.push(id);
                loadedResult.data.count += 1;
                that.__save(loadedResult.data, ID);
            },
            __removeOneFromAllCategories: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(ID);
                // todo if else status
                lodash.remove(loadedResult.data.entries, id);
                loadedResult.data.count -= 1;
                that.__save(loadedResult.data, ID);
            },
            __addOneToCategoryCollection: function(categoryID, noteID) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(categoryID);
                // todo if else status
                loadedResult.data.collection.entries.push(noteID);
                loadedResult.data.collection.count += 1;
                that.__save(loadedResult.data, categoryID);
            },
            __removeOneFromCategoryCollection: function(categoryID, noteID) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var loadedResult = that.__load(categoryID);
                // todo if else status
                lodash.remove(loadedResult.data.collection.entries, noteID);
                loadedResult.data.collection.count -= 1;
                that.__save(loadedResult.data, categoryID);
            },
            queryAllCategories: function() {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();

                var loadedResult = that.__load(ID);
                if(200 === loadedResult.status) {
                    // loadedResult.data: {count: number, entries: [categoryIDs]}
                    var data = {count: 0, entries: []};
                    loadedResult.data.entries.forEach(function(categoryID, index) {
                        var p = that.__load(categoryID);
                        if(200 === p.status) {
                            var x = lodash.pick(p.data, ["id", "title", "created", "modified"]);
                            data.count += 1;
                            data.entries.push(x);
                        } else {
                            that.__removeOneFromAllCategories(categoryID);
                            // todo if else status
                        }
                    });
                    result.data = data;
                    deferred.resolve(result);
                } else if(404 === loadedResult.status) {
                    var p = {
                        count: 0,
                        entries: []
                    }
                    localStorage.setItem(ID, JSON.stringify(p));
                    result.data = p;
                    deferred.reject(result);
                } else {
                    result.status = 400;
                    deferred.reject(result);
                }
                return deferred.promise;
            },
            addCategory: function(category) {
                // category: {title, collection}
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                // validate title - title is a none-empty string
                // validate collection - collection's entries is an empty Array and collection's count is 0
                // todo more validation
                if(("string" !== typeof category.title) || !category.title
                    || !category.collection
                    || !(category.collection.entries instanceof Array)
                    || 0 !== category.collection.entries.length
                    || 0 !== category.collection.count)
                {
                    result.status = 400;
                    deferred.reject(result);
                } else {
                    var savedResult = that.__save(category);
                    if(200 === savedResult.status) {
                        that.__addOneToAllCategories(savedResult.data.id);
                        // ToDo __addOne... status
                        result.data = savedResult.data;
                        deferred.resolve(result);
                    } else {
                        result.status = 500;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            deleteCategory: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                if("string" !== typeof id || !id) {
                    result.status = 404;
                    deferred.reject(result);
                } else {
                    var removedResult = that.__remove(id);
                    if(200 === removedResult.status) {
                        result.data = removedResult.data;
                        deferred.resolve(result);
                    } else {
                        result.status = removedResult.status;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            queryCategory: function(id) {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                if("string" !== typeof id || !id) {
                    result.status = 404;
                    deferred.reject(result);
                } else {
                    var loadedResult = that.__load(id);
                    if(200 === loadedResult.status) {
                        // loadedResult.data: {id, title, collection: {count, entries: [noteIDs]}, created, modified}
                        var data = lodash.pick(loadedResult.data, ["id", "title", "created", "modified"]);
                        data.collection = {count: 0, entries: []};
                        loadedResult.data.collection.entries.forEach(function(noteID, index) {
                            var p = that.__load(noteID);
                            if(200 === p.status) {
                                var x = lodash.pick(p.data, ["id", "title", "created", "modified"]);
                                data.collection.count += 1;
                                data.collection.entries.push(x);
                            } else {
                                that.__removeOneFromCategoryCollection(id, noteID);
                            }
                        });
                        result.data = data;
                        deferred.resolve(result);
                    } else {
                        result.status = loadedResult.status;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            updateCategory: function(category) {
                // category: {id, title, collection}
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                // validate id - id is a none-empty string
                // validate title - title is a none-empty string
                // validate collection - entries is an Array and its length equal to count
                // todo more validation
                if(("string" !== typeof category.id) || !category.id
                    || ("string" !== typeof category.title) || !category.title
                    || !category.collection
                    || !(category.collection.entries instanceof Array)
                    || category.collection.count !== category.collection.entries.length)
                {
                    result.status = 400;
                    deferred.reject(result);
                } else {
                    var data = lodash.pick(category, ["id", "title", "created", "modified"]);
                    data.collection = {
                        count: category.collection.count,
                        entries: lodash.map(category.collection.entries, function(entry) {return entry.id})
                    }
                    var savedResult = that.__save(data);
                    if(200 === savedResult.status) {
                        // update category with saved data
                        category.modified = savedResult.data.modified;
                        result.data = category;
                        deferred.resolve(result);
                    } else {
                        result.status = 500;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            queryAllNotes: function(category) {
                var deferred = $q.defer();
                var result = {
                    status: 200,
                    data: [{
                            'title': '1. Nexus S',
                            'content': 'Fast just got faster with Nexus S.'
                        }, {
                            'title': '2. Motorola XOOM™ with Wi-Fi',
                            'content': 'The Next, Next Generation tablet.'
                        }, {
                            'title': '3. MOTOROLA XOOM™',
                            'content': 'The Next, Next Generation tablet.'
                        }]
                }
                deferred.resolve(result);
                return deferred.promise;
            },
            addNote: function() {
            },
            deleteNote: function(){
            },
            queryNote: function() {
            },
            updateNote: function() {
            }
        }
        return storage;
    }]).factory("remoteService", ["$http", function($http) {
        // todo
    }]);
<|endoftext|>


<commit_before>import BasicWall from 'objects/BasicWall';
import BasicTurret from 'objects/BasicTurret';

class InventoryManager {

    static get BLOCKER_TYPES() {
        return {
            BASIC_WALL: 'basicWall',
            BASIC_TURRET: 'basicTurret'
        };
    }

    static get BASIC_WALL() {
        return {
            cost: 1
        };
    }

    static get BASIC_TURRET() {
        return {
            cost: 5
        };
    }

    constructor(game) {
       this.game = game;
    }

    setup(initialCoins) {
        this.coins = initialCoins;

        this.inventory = {};

        this.inventory[InventoryManager.BLOCKER_TYPES.BASIC_WALL] = InventoryManager.BASIC_WALL;
        this.inventory[InventoryManager.BLOCKER_TYPES.BASIC_TURRET] = InventoryManager.BASIC_TURRET;

        this.selectBlocker(InventoryManager.BLOCKER_TYPES.BASIC_WALL);

        this.game.input.addMoveCallback((pointer, x, y) => {
            if (!this.cursorView) {
                return;
            }

            let cell = this.game.gridManager.grid.xyToGridCell(x, y);
            if (!cell) {
                this.cursorView.visible = false;
                return;
            }
            this.cursorView.visible = true;
            let location = cell.getCentroid();
            this.cursorView.move(location.x, location.y);
        });

        this.game.input.onUp.add(this.placeBlocker, this);
    }

    update() {

    }

    selectBlocker(item_type) {
        this.selectedBlocker = item_type;
        this.cursorView = this.getSelectedBlockerView({x: 0, y: 0})
    }

    placeBlocker() {

        let item = this.inventory[this.selectedBlocker];
        if (item.cost <= this.coins) {
            this.coins -= item.cost;
            this.getSelectedBlockerView(location);
            return true;
        }
        return false;
    }

    getSelectedBlockerView(position) {
        switch (this.selectedBlocker) {
            case InventoryManager.BLOCKER_TYPES.BASIC_WALL:
                return new BasicWall(this.game, position);
            case InventoryManager.BLOCKER_TYPES.BASIC_TURRET:
                return new BasicTurret(this.game, position);
            default:
                console.log(`unexpected item_type: ${this.selectedBlocker}`);
        }
    }
}

export default InventoryManager;<commit_msg>fix up place blocker and clean up cursor sprite<commit_after>import BasicWall from 'objects/BasicWall';
import BasicTurret from 'objects/BasicTurret';

class InventoryManager {

    static get BLOCKER_TYPES() {
        return {
            BASIC_WALL: 'basicWall',
            BASIC_TURRET: 'basicTurret'
        };
    }

    static get BASIC_WALL() {
        return {
            cost: 1
        };
    }

    static get BASIC_TURRET() {
        return {
            cost: 5
        };
    }

    constructor(game) {
        this.game = game;
    }

    setup(initialCoins) {
        this.coins = initialCoins;

        this.inventory = {};

        this.inventory[InventoryManager.BLOCKER_TYPES.BASIC_WALL] = InventoryManager.BASIC_WALL;
        this.inventory[InventoryManager.BLOCKER_TYPES.BASIC_TURRET] = InventoryManager.BASIC_TURRET;

        this.selectBlocker(InventoryManager.BLOCKER_TYPES.BASIC_WALL);

        this.game.input.addMoveCallback((pointer, x, y) => {
            if (!this.cursorView) {
                return;
            }

            let location = this.getGridCenterFromPosition(this.game.input.activePointer);
            if (!location) {
                this.cursorView.visible = false;
                return;
            }
            this.cursorView.visible = true;
            this.cursorView.move(location.x, location.y);
        });

        this.game.input.onUp.add(this.placeBlocker, this);
    }

    update() {

    }

    selectBlocker(item_type) {
        this.selectedBlocker = item_type;
        if (this.cursorView) {
            this.cursorView.destroy();
        }
        this.cursorView = this.getSelectedBlockerView({x: 0, y: 0})
    }

    placeBlocker() {
        let location = this.getGridCenterFromPosition(this.game.input.activePointer);
        if (!location) {
            return;
        }
        let item = this.inventory[this.selectedBlocker];
        if (item.cost <= this.coins) {
            this.coins -= item.cost;
            this.getSelectedBlockerView(location);
            return true;
        }
        return false;
    }

    getGridCenterFromPosition(position) {
        let cell = this.game.gridManager.grid.xyToGridCell(position.x, position.y);
        if (!cell) {
            return;
        }
        return cell.getCentroid();
    }

    getSelectedBlockerView(position) {
        switch (this.selectedBlocker) {
            case InventoryManager.BLOCKER_TYPES.BASIC_WALL:
                return new BasicWall(this.game, position);
            case InventoryManager.BLOCKER_TYPES.BASIC_TURRET:
                return new BasicTurret(this.game, position);
            default:
                console.log(`unexpected item_type: ${this.selectedBlocker}`);
        }
    }
}

export default InventoryManager;<|endoftext|>


<commit_before>$( document ).ready(function() {

var thumbApiUrl="http://jsonplaceholder.typicode.com/photos";

AjaxThumbNails()

  // ajaxcall(loopappened(append(scoreGenerate)))

  function AjaxThumbNails(){
    $.ajax({
      url:thumbApiUrl,
      dataType:"JSON",
      type: "Get",
      success: function(resp){loopAddThumbnail(resp)},
      error: function(err){alert('Error: '+ err)}
    });
  }

  function loopAddThumbnail(resp){
    resp = resp;
    for (var i = 0; i < 6; i++) {
      thumbnailUrl = resp[i].thumbnailUrl
      addThumbnail(thumbnailUrl)
    };
  };

  function addThumbnail(thumbUrl){
    $(".thumbnails-container").append(
      $("<div/>")
      .addClass("thumb-well")
      .append($("<img/>").attr('src',thumbUrl))
      )
  };
  function scoreGenerate(){};

});<commit_msg>add img + p with filler score<commit_after>$( document ).ready(function() {

var thumbApiUrl="http://jsonplaceholder.typicode.com/photos";

AjaxThumbNails()

  // ajaxcall(loopappened(append(scoreGenerate)))

  function AjaxThumbNails(){
    $.ajax({
      url:thumbApiUrl,
      dataType:"JSON",
      type: "Get",
      success: function(resp){loopAddThumbnail(resp)},
      error: function(err){alert('Error: '+ err)}
    });
  }

  function loopAddThumbnail(resp){
    resp = resp;
    for (var i = 0; i < 6; i++) {
      thumbnailUrl = resp[i].thumbnailUrl
      addThumbnail(thumbnailUrl)
    };
  };

  function addThumbnail(thumbUrl){
    $(".thumbnails-container").append(
      $("<div/>")
      .addClass("thumb-well")
      .append($("<img/>").attr('src',thumbUrl))
      .append($("<p/>").text("32"))
      )
  };
  function scoreGenerate(){};

});<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var randu = require( '@stdlib/math/base/random/randu' );
var abs = require( '@stdlib/math/base/special/abs' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var acoversin = require( './../lib' );

// FIXTURES //

var data = require( './fixtures/julia/data.json' );
var smallPositive = require( './fixtures/julia/small_positive.json' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof acoversin, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function computes the inverse coversed sine', function test( t ) {
	var expected;
	var delta;
	var tol;
	var x;
	var y;
	var i;

	x = data.x;
	expected = data.expected;

	for ( i = 0; i < x.length; i++ ) {
		y = acoversin( x[i] );
		if ( y === expected[ i ] ) {
			t.strictEqual( y, expected[ i ], 'x: '+x[i]+'. Expected: '+expected[i] );
		} else {
			delta = abs( y - expected[i] );
			tol = 350.0 * EPS * abs( expected[i] );
			t.ok( delta <= tol, 'within tolerance. x: '+x[i]+'. Value: '+y+'. Expected: '+expected[i]+'. tol: '+tol+'. delta: '+delta+'.' );
		}
	}
	t.end();
});

tape( 'the function computes the inverse coversed sine (small positive numbers)', function test( t ) {
	var expected;
	var delta;
	var tol;
	var x;
	var y;
	var i;

	x = smallPositive.x;
	expected = smallPositive.expected;

	for ( i = 0; i < x.length; i++ ) {
		y = acoversin( x[i] );
		if ( y === expected[ i ] ) {
			t.strictEqual( y, expected[ i ], 'x: '+x[i]+'. Expected: '+expected[i] );
		} else {
			delta = abs( y - expected[i] );
			tol = EPS * abs( expected[i] );
			t.ok( delta <= tol, 'within tolerance. x: '+x[i]+'. Value: '+y+'. Expected: '+expected[i]+'. tol: '+tol+'. delta: '+delta+'.' );
		}
	}
	t.end();
});

tape( 'the function returns `NaN` if provided a `NaN`', function test( t ) {
	var v = acoversin( NaN );
	t.strictEqual( isnan( v ), true, 'returns NaN' );
	t.end();
});

tape( 'the function returns `NaN` if provided a value less than `0`', function test( t ) {
	var v;
	var i;
	for ( i = 0; i < 1e4; i++ ) {
		v = -(randu()*1.0e6) - (0.0+EPS);
		t.strictEqual( isnan( acoversin( v ) ), true, 'returns NaN when provided '+v );
	}
	t.end();
});

tape( 'the function returns `NaN` if provided a value greater than `2`', function test( t ) {
	var v;
	var i;
	for ( i = 0; i < 1e4; i++ ) {
		v = (randu()*1.0e6) + 2.0 + EPS;
		t.strictEqual( isnan( acoversin( v ) ), true, 'returns NaN when provided '+v );
	}
	t.end();
});
<commit_msg>Update test descriptions<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var randu = require( '@stdlib/math/base/random/randu' );
var abs = require( '@stdlib/math/base/special/abs' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var acoversin = require( './../lib' );

// FIXTURES //

var data = require( './fixtures/julia/data.json' );
var smallPositive = require( './fixtures/julia/small_positive.json' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof acoversin, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function computes the inverse coversed sine', function test( t ) {
	var expected;
	var delta;
	var tol;
	var x;
	var y;
	var i;

	x = data.x;
	expected = data.expected;

	for ( i = 0; i < x.length; i++ ) {
		y = acoversin( x[i] );
		if ( y === expected[ i ] ) {
			t.strictEqual( y, expected[ i ], 'x: '+x[i]+'. E: '+expected[i] );
		} else {
			delta = abs( y - expected[i] );
			tol = 350.0 * EPS * abs( expected[i] );
			t.ok( delta <= tol, 'within tolerance. x: '+x[i]+'. y: '+y+'. E: '+expected[i]+'. tol: '+tol+'. Δ: '+delta+'.' );
		}
	}
	t.end();
});

tape( 'the function computes the inverse coversed sine (small positive numbers)', function test( t ) {
	var expected;
	var delta;
	var tol;
	var x;
	var y;
	var i;

	x = smallPositive.x;
	expected = smallPositive.expected;

	for ( i = 0; i < x.length; i++ ) {
		y = acoversin( x[i] );
		if ( y === expected[ i ] ) {
			t.strictEqual( y, expected[ i ], 'x: '+x[i]+'. E: '+expected[i] );
		} else {
			delta = abs( y - expected[i] );
			tol = EPS * abs( expected[i] );
			t.ok( delta <= tol, 'within tolerance. x: '+x[i]+'. y: '+y+'. E: '+expected[i]+'. tol: '+tol+'. Δ: '+delta+'.' );
		}
	}
	t.end();
});

tape( 'the function returns `NaN` if provided `NaN`', function test( t ) {
	var v = acoversin( NaN );
	t.strictEqual( isnan( v ), true, 'returns NaN' );
	t.end();
});

tape( 'the function returns `NaN` if provided a value less than `0`', function test( t ) {
	var v;
	var i;
	for ( i = 0; i < 1e4; i++ ) {
		v = -(randu()*1.0e6) - (0.0+EPS);
		t.strictEqual( isnan( acoversin( v ) ), true, 'returns NaN when provided '+v );
	}
	t.end();
});

tape( 'the function returns `NaN` if provided a value greater than `2`', function test( t ) {
	var v;
	var i;
	for ( i = 0; i < 1e4; i++ ) {
		v = (randu()*1.0e6) + 2.0 + EPS;
		t.strictEqual( isnan( acoversin( v ) ), true, 'returns NaN when provided '+v );
	}
	t.end();
});
<|endoftext|>