<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 scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    console.log("Move element ", element);
    console.log("to position ", to);

    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());

      // console.log("increment", increment);
      // console.log("limit", limit);
      // console.log("offset", offset);

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;
      // console.log(nextOffset);
      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;

        console.log("ELEMENT scroll top", element);
        if (inValidRange(newOffset, limit)) {
          // element.animate({
          //     scrollTop: document.getElementById(newOffset).offsetTop
          // }, 400);
          scrollTo(element, 0, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });

      // $this.on('click', function() {
      //   offset = element.dataset.scrollOffset;
      //
      //   newOffset = offset + increment;
      //
      //   console.log("newOffset", newOffset);
      //   if (inValidRange(newOffset, limit)) {
      //     element.animate({
      //         scrollTop: $('#' + newOffset).position().top
      //     }, 400);
      //     element.data('scroll-offset', newOffset);
      //
      //     setVisibilityAll(scrollElements, newOffset);
      //   }
      // });
    })
    // scrollElements.each();

    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

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

      $this = $(this);

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

  var setContainerHeight = function(containerEl) {
    // TODO: Refactor this to make simpler
    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      panelEl,
      referralsEl,
      referralsTitleEl,
      panelHeight,
      css,
      stylesheet;

    bodyEl           = $('.squatch-body');
    titleEl          = bodyEl.find('.squatch-title');
    panelEl          = $('#squatch-panel');
    referralsEl      = $('.squatch-referrals');
    referralsTitleEl = $('.squatch-referrals-title');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    panelHeight = panelEl.outerHeight();

    if (referralsEl.is(':visible')) {
      panelHeight -= referralsEl.outerHeight();
    }

    if (referralsTitleEl.is(':visible')) {
      panelHeight -= referralsTitleEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + panelHeight);

    stylesheet = document.createElement('style');
    stylesheet.type = 'text/css';

    css = '#squatch-panel.open {' +
      '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '}' +
      'html.lt-ie9 #squatch-panel.open {' +
      'top: -' + bodyHeightWithoutTitle + 'px;' +
      '}';

    if (stylesheet.styleSheet){
      // IE
      stylesheet.styleSheet.cssText = css;
    } else {
      // W3C Standard
      stylesheet.appendChild(document.createTextNode(css));
    }

    document.querySelector('head').appendChild(stylesheet);
  };

  var containerEl = $('.squatch-container-popup');
  if (containerEl.length) {
    var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
    var windowEl = $(window);

    // Workaround for popup height being incorrectly set during iframe resizing.
    // This is due to the popup being displayed inconsistently - with responsive styles activated, sometimes the mobile view will be displayed, even on a desktop monitor with more than 500 pixels width. The solution may be to set the iframe width to the full browser width, rather than the width of the widget theme.
    // There is another hack in _popup.less as well
    // TODO: Find a solution for this and enable responsive styles again.
    windowEl.on('load', function (i) {
      var setContainerHeightIfWideEnough = function () {
        var width = windowEl.width();

        if (width === 500) {
          setContainerHeightForPopup();
        } else {
          setTimeout(function() {
            setContainerHeightIfWideEnough();
          }, 50);
        }
      };

      setContainerHeightIfWideEnough();
    });

    // The content has a different height in mobile
    // TODO: Find a a solution for responsive in popups and re-enable this
    // var mql = window.matchMedia('(max-width: 500px)');
    // mql.addListener(setContainerHeightForPopup);
  }
})();
<commit_msg>new scroll top<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 scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    console.log("Move element ", element);
    console.log("to position ", to);

    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());

      // console.log("increment", increment);
      // console.log("limit", limit);
      // console.log("offset", offset);

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;
      // console.log(nextOffset);
      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;

        console.log("ELEMENT scroll top", element);
        if (inValidRange(newOffset, limit)) {
          // element.animate({
          //     scrollTop: document.getElementById(newOffset).offsetTop
          // }, 400);
          scrollTo(document.getElementById(newOffset), 0, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });

      // $this.on('click', function() {
      //   offset = element.dataset.scrollOffset;
      //
      //   newOffset = offset + increment;
      //
      //   console.log("newOffset", newOffset);
      //   if (inValidRange(newOffset, limit)) {
      //     element.animate({
      //         scrollTop: $('#' + newOffset).position().top
      //     }, 400);
      //     element.data('scroll-offset', newOffset);
      //
      //     setVisibilityAll(scrollElements, newOffset);
      //   }
      // });
    })
    // scrollElements.each();

    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

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

      $this = $(this);

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

  var setContainerHeight = function(containerEl) {
    // TODO: Refactor this to make simpler
    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      panelEl,
      referralsEl,
      referralsTitleEl,
      panelHeight,
      css,
      stylesheet;

    bodyEl           = $('.squatch-body');
    titleEl          = bodyEl.find('.squatch-title');
    panelEl          = $('#squatch-panel');
    referralsEl      = $('.squatch-referrals');
    referralsTitleEl = $('.squatch-referrals-title');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    panelHeight = panelEl.outerHeight();

    if (referralsEl.is(':visible')) {
      panelHeight -= referralsEl.outerHeight();
    }

    if (referralsTitleEl.is(':visible')) {
      panelHeight -= referralsTitleEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + panelHeight);

    stylesheet = document.createElement('style');
    stylesheet.type = 'text/css';

    css = '#squatch-panel.open {' +
      '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '}' +
      'html.lt-ie9 #squatch-panel.open {' +
      'top: -' + bodyHeightWithoutTitle + 'px;' +
      '}';

    if (stylesheet.styleSheet){
      // IE
      stylesheet.styleSheet.cssText = css;
    } else {
      // W3C Standard
      stylesheet.appendChild(document.createTextNode(css));
    }

    document.querySelector('head').appendChild(stylesheet);
  };

  var containerEl = $('.squatch-container-popup');
  if (containerEl.length) {
    var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
    var windowEl = $(window);

    // Workaround for popup height being incorrectly set during iframe resizing.
    // This is due to the popup being displayed inconsistently - with responsive styles activated, sometimes the mobile view will be displayed, even on a desktop monitor with more than 500 pixels width. The solution may be to set the iframe width to the full browser width, rather than the width of the widget theme.
    // There is another hack in _popup.less as well
    // TODO: Find a solution for this and enable responsive styles again.
    windowEl.on('load', function (i) {
      var setContainerHeightIfWideEnough = function () {
        var width = windowEl.width();

        if (width === 500) {
          setContainerHeightForPopup();
        } else {
          setTimeout(function() {
            setContainerHeightIfWideEnough();
          }, 50);
        }
      };

      setContainerHeightIfWideEnough();
    });

    // The content has a different height in mobile
    // TODO: Find a a solution for responsive in popups and re-enable this
    // var mql = window.matchMedia('(max-width: 500px)');
    // mql.addListener(setContainerHeightForPopup);
  }
})();
<|endoftext|>


<commit_before>(function () {
    angular
        .module('app')
        .config(configure)
        .run(run);

    configure.$inject = ['RestangularProvider', '$routeProvider', 'localStorageServiceProvider', 'apiPrefix'];

    function configure(RestangularProvider, $routeProvider, localStorageServiceProvider, apiPrefix) {
        $routeProvider
            .when("/", {
                template: "<profile-summary></profile-summary>"
            })
            .otherwise({
                redirectTo: "/"
            });

        RestangularProvider.setBaseUrl('/api/v1');

        //sTODO: set request error interceptor

        localStorageServiceProvider
            .setPrefix('scientilla');
    }

    // unused services are injected for initialization purpose
    const servicesToInit = ['context'];
    const services = [
        '$rootScope',
        'AuthService',
        'Restangular',
        'Prototyper',
        'path',
        'Notification',
        'ModalService'
    ];
    run.$inject = _.union(services, servicesToInit);

    function run($rootScope, AuthService, Restangular, Prototyper, path, Notification, ModalService) {

        $rootScope.$on("$routeChangeStart", (event, next, current) => {
            const goingToUnavailablePage = next.$$route && next.$$route.originalPath === '/unavailable';
            if (!goingToUnavailablePage && !AuthService.isAvailable && !AuthService.isAdmin) {
                Notification.warning('Sorry but scientilla is temporary unavailable. Try again later.');
                ModalService.dismiss(null);
                path.goTo('/unavailable');
                return;
            }
            if (!AuthService.isLogged) {
                if (next.access && next.access.noLogin) {

                } else {
                    path.goTo("/login");
                }
            }
        });

        $rootScope.$on('$locationChangeSuccess', (event, current) =>
            path.current = path.getUrlPath(current)
        );

        $rootScope.$on('$viewContentLoaded', () => {
            if (!AuthService.isLogged && AuthService.isAvailable)
                AuthService.loadAuthenticationData();
        });

        Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
            const isLogged = response.headers('scientilla-logged') === 'true';
            if (response.status === 403 && isLogged) {
                Notification.warning('Your session is expired. Please login again.');
                ModalService.dismiss(null);
                AuthService.logout();
                return false;
            }

            return true;
        });

        Restangular.addResponseInterceptor((data, operation, what, url, response) => {
            const status = response.headers('scientilla-status');
            const isAdmin = response.headers('scientilla-admin') === 'true';
            AuthService.isAdmin = isAdmin;
            if (status === 'DISABLED') {
                AuthService.isAvailable = false;
                if (!isAdmin) {
                    Notification.warning('Sorry but scientilla is temporary unavailable. Try again later.');
                    ModalService.dismiss(null);
                    path.goTo('/unavailable');
                }
            } else {
                AuthService.isAvailable = true;
            }

            if (operation === 'getList') {
                var newResponse = data.items;
                newResponse.count = data.count;
                return newResponse;
            }
            return data;
        });

        Restangular.extendModel('users', Prototyper.toUserModel);
        Restangular.extendModel('groups', Prototyper.toGroupModel);
        Restangular.extendModel('drafts', Prototyper.toDocumentModel);
        Restangular.extendModel('externals', Prototyper.toDocumentModel);
        Restangular.extendCollection('documents', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('externalDocuments', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('suggestedDocuments', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('discardedDocuments', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('drafts', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('authorships', Prototyper.toAuthorshipsCollection);
        Restangular.extendCollection('institutes', Prototyper.toInstitutesCollection);
        Restangular.extendCollection('users', Prototyper.toUsersCollection);
        Restangular.extendCollection('groups', Prototyper.toGroupsCollection);
        Restangular.extendCollection('taglabels', Prototyper.toTagLabelsCollection);
    }
})();
<commit_msg>Fixed small issue.<commit_after>(function () {
    angular
        .module('app')
        .config(configure)
        .run(run);

    configure.$inject = ['RestangularProvider', '$routeProvider', 'localStorageServiceProvider', 'apiPrefix'];

    function configure(RestangularProvider, $routeProvider, localStorageServiceProvider, apiPrefix) {
        $routeProvider
            .when("/", {
                template: "<profile-summary></profile-summary>"
            })
            .otherwise({
                redirectTo: "/"
            });

        RestangularProvider.setBaseUrl('/api/v1');

        //sTODO: set request error interceptor

        localStorageServiceProvider
            .setPrefix('scientilla');
    }

    // unused services are injected for initialization purpose
    const servicesToInit = ['context'];
    const services = [
        '$rootScope',
        'AuthService',
        'Restangular',
        'Prototyper',
        'path',
        'Notification',
        'ModalService'
    ];
    run.$inject = _.union(services, servicesToInit);

    function run($rootScope, AuthService, Restangular, Prototyper, path, Notification, ModalService) {

        $rootScope.$on("$routeChangeStart", (event, next, current) => {
            const noRedirectUrls = ['/unavailable', '/login'];
            const goingToNoRedirectUrl = next.$$route && noRedirectUrls.includes(next.$$route.originalPath);
            if (!goingToNoRedirectUrl && !AuthService.isAvailable && !AuthService.isAdmin) {
                Notification.warning('Sorry but scientilla is temporary unavailable. Try again later.');
                ModalService.dismiss(null);
                path.goTo('/unavailable');
                return;
            }
            if (!AuthService.isLogged) {
                if (next.access && next.access.noLogin) {

                } else {
                    path.goTo("/login");
                }
            }
        });

        $rootScope.$on('$locationChangeSuccess', (event, current) =>
            path.current = path.getUrlPath(current)
        );

        $rootScope.$on('$viewContentLoaded', () => {
            if (!AuthService.isLogged && AuthService.isAvailable)
                AuthService.loadAuthenticationData();
        });

        Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
            const isLogged = response.headers('scientilla-logged') === 'true';
            if (response.status === 403 && isLogged) {
                Notification.warning('Your session is expired. Please login again.');
                ModalService.dismiss(null);
                AuthService.logout();
                return false;
            }

            return true;
        });

        Restangular.addResponseInterceptor((data, operation, what, url, response) => {
            const status = response.headers('scientilla-status');
            const isAdmin = response.headers('scientilla-admin') === 'true';
            AuthService.isAdmin = isAdmin;
            if (status === 'DISABLED') {
                AuthService.isAvailable = false;
                if (!isAdmin) {
                    Notification.warning('Sorry but scientilla is temporary unavailable. Try again later.');
                    ModalService.dismiss(null);
                    path.goTo('/unavailable');
                }
            } else {
                AuthService.isAvailable = true;
            }

            if (operation === 'getList') {
                var newResponse = data.items;
                newResponse.count = data.count;
                return newResponse;
            }
            return data;
        });

        Restangular.extendModel('users', Prototyper.toUserModel);
        Restangular.extendModel('groups', Prototyper.toGroupModel);
        Restangular.extendModel('drafts', Prototyper.toDocumentModel);
        Restangular.extendModel('externals', Prototyper.toDocumentModel);
        Restangular.extendCollection('documents', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('externalDocuments', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('suggestedDocuments', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('discardedDocuments', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('drafts', Prototyper.toDocumentsCollection);
        Restangular.extendCollection('authorships', Prototyper.toAuthorshipsCollection);
        Restangular.extendCollection('institutes', Prototyper.toInstitutesCollection);
        Restangular.extendCollection('users', Prototyper.toUsersCollection);
        Restangular.extendCollection('groups', Prototyper.toGroupsCollection);
        Restangular.extendCollection('taglabels', Prototyper.toTagLabelsCollection);
    }
})();
<|endoftext|>


<commit_before>// customize-home.js

// logo spin
$('#logo').hover(function(){
    $(this).addClass('fa-spin text-yellow-inverted');
}, function(){
    $(this).removeClass('fa-spin text-yellow-inverted');
});

// progress bar
$('#page-loading-progress').progress({
    total: 2,
    onSuccess: function() {
        $('#page-loading-progress').fadeOut(1000, function() {
            $('#page-loading-progress').remove();
        });
    }
});

// version
moment.locale('zh-cn');
var pushedAt = 'loading';
var lastMoment = '';
var thisMoment = '';
$.getJSON('https://api.github.com/repos/iROCKBUNNY/BYR-Navi', function(data) {
    pushedAt = data.pushed_at;
    lastMoment = encodeURIComponent(moment(pushedAt).fromNow());
    $('#page-loading-progress').progress('increment');
});
function updateVersion(pushedAt) {
    if (pushedAt !== 'loading') {
        thisMoment = encodeURIComponent(moment(pushedAt).fromNow());
        $('#version img').attr('src', 'https://img.shields.io/badge/' + encodeURIComponent('更新') + '-' + thisMoment + '-brightgreen.svg');
        if (thisMoment !== lastMoment) {
            $('#version img').transition('pulse');
            lastMoment = thisMoment;
        };
    };
};
updateVersion(pushedAt);
setInterval(function() {
    updateVersion(pushedAt);
}, 5000);

// visit
function updateVisit(updateProgressBar) {
    $.getJSON(urlPrefix + '/json/analytics_data.json', function(data) {
        $.getJSON(data.analytics.api_url, {
            'module': 'API',
            'method': 'VisitsSummary.getUniqueVisitors',
            'idSite': '1',
            'period': 'day',
            'date': 'today',
            'format': 'JSON',
            'token_auth': data.analytics.token
        }, function(data) {
            $('#visit img').attr('src', 'https://img.shields.io/badge/' + encodeURIComponent('今日访客') +'-' + encodeURIComponent(data.value) + '-brightgreen.svg');
            if (updateProgressBar) {
                $('#page-loading-progress').progress('increment');
            };
        });
    });
};
updateVisit(true);
setInterval(function() {
    updateVisit(false);
}, 15000);

// search
$('#search-services').dropdown();
if (Cookies.get('byr_navi_previous_search_service_option') == undefined || $('#' + Cookies.get('byr_navi_previous_search_service_option')).length === 0) {
    Cookies.set('byr_navi_previous_search_service_option', $('#search-services').val(), { expires: 365 });
} else {
    $('#search-services').dropdown('set selected', Cookies.get('byr_navi_previous_search_service_option'));
};

$('#search-button').click(function() {
    var service = $('#' + $('#search-services').val());
    var query = $('#search-query').val();
    query = encodeURIComponent(query);
    if (query) {
        Cookies.set('byr_navi_previous_search_service_option', $('#search-services').val(), { expires: 365 });
        window.open(service.attr('data-url') + query + service.attr('data-suffix'), '_blank');
    } else {
        $('#search-div').addClass('error');
        $('#search-query').attr('placeholder', '请输入搜索内容');
    };
});

$('#search-query').click(function() {
    $(this).select();
});

$(document).ready(function() {
    $('#search-query').focus();
});

$(window).keyup(function(event) {
    var windowTop = $(window).scrollTop();
    var windowHeight = $(window).innerHeight();
    var windowBottom = windowTop + windowHeight;
    var searchBoxTop = $('#search-div').offset().top;
    var searchBoxHeight = $('#search-div').innerHeight();
    var searchBoxBottom = searchBoxTop + searchBoxHeight;
    if (event.key == 'Enter' && searchBoxBottom > windowTop && searchBoxTop < windowBottom) {
        var service = $('#' + $('#search-services').val());
        var query = $('#search-query').val();
        query = encodeURIComponent(query);
        if (query) {
            Cookies.set('byr_navi_previous_search_service_option', $('#search-services').val(), { expires: 365 });
            window.open(service.attr('data-url') + query + service.attr('data-suffix'), '_blank');
        } else {
            $('#search-div').addClass('error');
            $('#search-query').attr('placeholder', '请输入搜索内容').focus();
        };
    };
});

$('#search-query').keyup(function(event) {
    if (event.key) {
        if ($('#search-query').val()) {
            $('#search-div').removeClass('error');
            $('#search-query').attr('placeholder', '立即搜索');
        };
    };
});

// query suggestions
var sugParams = {
    "XOffset": -3, //提示框位置横向偏移量,单位px
    "YOffset": -2, //提示框位置纵向偏移量,单位px
    // "width": $('#search-query').innerWidth(), //提示框宽度，单位px
    "fontColor": "rgba(0, 0, 0, 0.87)", //提示框文字颜色
    "fontColorHI": "rgba(0, 0, 0, 0.87)", //提示框高亮选择时文字颜色
    "fontSize": "14px", //文字大小
    "fontFamily": "Lato, 'Helvetica Neue', Arial, Helvetica, sans-serif", //文字字体
    "borderColor": "rgba(34, 36, 38, 0.14902)", //提示框的边框颜色
    "bgcolorHI": "rgba(0, 0, 0, 0.05)", //提示框高亮选择的颜色
    "sugSubmit": false //选中提示框中词条时是否提交表单
};
BaiduSuggestion.bind('search-query', sugParams);<commit_msg>Update<commit_after>// customize-home.js

// logo spin
$('#logo').hover(function(){
    $(this).addClass('fa-spin text-yellow-inverted');
}, function(){
    $(this).removeClass('fa-spin text-yellow-inverted');
});

// progress bar
$('#page-loading-progress').progress({
    total: 2,
    onSuccess: function() {
        $('#page-loading-progress').fadeOut(1000, function() {
            $('#page-loading-progress').remove();
        });
    }
});

// version
moment.locale('zh-cn');
var pushedAt = 'loading';
var lastMoment = '';
var thisMoment = '';
$.getJSON('https://api.github.com/repos/iROCKBUNNY/BYR-Navi', function(data) {
    pushedAt = data.pushed_at;
    lastMoment = encodeURIComponent(moment(pushedAt).fromNow());
    $('#page-loading-progress').progress('increment');
});
function updateVersion(pushedAt) {
    if (pushedAt !== 'loading') {
        thisMoment = encodeURIComponent(moment(pushedAt).fromNow());
        if (thisMoment === lastMoment) {
            $('#version img').attr('src', 'https://img.shields.io/badge/' + encodeURIComponent('更新') + '-' + thisMoment + '-brightgreen.svg');
            lastMoment = thisMoment;
        } else {
            $('#version img').attr('src', 'https://img.shields.io/badge/' + encodeURIComponent('更新') + '-' + thisMoment + '-brightgreen.svg').transition('pulse');
        };
    };
};
updateVersion(pushedAt);
setInterval(function() {
    updateVersion(pushedAt);
}, 5000);

// visit
function updateVisit(updateProgressBar) {
    $.getJSON(urlPrefix + '/json/analytics_data.json', function(data) {
        $.getJSON(data.analytics.api_url, {
            'module': 'API',
            'method': 'VisitsSummary.getUniqueVisitors',
            'idSite': '1',
            'period': 'day',
            'date': 'today',
            'format': 'JSON',
            'token_auth': data.analytics.token
        }, function(data) {
            $('#visit img').attr('src', 'https://img.shields.io/badge/' + encodeURIComponent('今日访客') +'-' + encodeURIComponent(data.value) + '-brightgreen.svg');
            if (updateProgressBar) {
                $('#page-loading-progress').progress('increment');
            };
        });
    });
};
updateVisit(true);
setInterval(function() {
    updateVisit(false);
}, 15000);

// search
$('#search-services').dropdown();
if (Cookies.get('byr_navi_previous_search_service_option') == undefined || $('#' + Cookies.get('byr_navi_previous_search_service_option')).length === 0) {
    Cookies.set('byr_navi_previous_search_service_option', $('#search-services').val(), { expires: 365 });
} else {
    $('#search-services').dropdown('set selected', Cookies.get('byr_navi_previous_search_service_option'));
};

$('#search-button').click(function() {
    var service = $('#' + $('#search-services').val());
    var query = $('#search-query').val();
    query = encodeURIComponent(query);
    if (query) {
        Cookies.set('byr_navi_previous_search_service_option', $('#search-services').val(), { expires: 365 });
        window.open(service.attr('data-url') + query + service.attr('data-suffix'), '_blank');
    } else {
        $('#search-div').addClass('error');
        $('#search-query').attr('placeholder', '请输入搜索内容');
    };
});

$('#search-query').click(function() {
    $(this).select();
});

$(document).ready(function() {
    $('#search-query').focus();
});

$(window).keyup(function(event) {
    var windowTop = $(window).scrollTop();
    var windowHeight = $(window).innerHeight();
    var windowBottom = windowTop + windowHeight;
    var searchBoxTop = $('#search-div').offset().top;
    var searchBoxHeight = $('#search-div').innerHeight();
    var searchBoxBottom = searchBoxTop + searchBoxHeight;
    if (event.key == 'Enter' && searchBoxBottom > windowTop && searchBoxTop < windowBottom) {
        var service = $('#' + $('#search-services').val());
        var query = $('#search-query').val();
        query = encodeURIComponent(query);
        if (query) {
            Cookies.set('byr_navi_previous_search_service_option', $('#search-services').val(), { expires: 365 });
            window.open(service.attr('data-url') + query + service.attr('data-suffix'), '_blank');
        } else {
            $('#search-div').addClass('error');
            $('#search-query').attr('placeholder', '请输入搜索内容').focus();
        };
    };
});

$('#search-query').keyup(function(event) {
    if (event.key) {
        if ($('#search-query').val()) {
            $('#search-div').removeClass('error');
            $('#search-query').attr('placeholder', '立即搜索');
        };
    };
});

// query suggestions
var sugParams = {
    "XOffset": -3, //提示框位置横向偏移量,单位px
    "YOffset": -2, //提示框位置纵向偏移量,单位px
    // "width": $('#search-query').innerWidth(), //提示框宽度，单位px
    "fontColor": "rgba(0, 0, 0, 0.87)", //提示框文字颜色
    "fontColorHI": "rgba(0, 0, 0, 0.87)", //提示框高亮选择时文字颜色
    "fontSize": "14px", //文字大小
    "fontFamily": "Lato, 'Helvetica Neue', Arial, Helvetica, sans-serif", //文字字体
    "borderColor": "rgba(34, 36, 38, 0.14902)", //提示框的边框颜色
    "bgcolorHI": "rgba(0, 0, 0, 0.05)", //提示框高亮选择的颜色
    "sugSubmit": false //选中提示框中词条时是否提交表单
};
BaiduSuggestion.bind('search-query', sugParams);<|endoftext|>


<commit_before>import localforage from 'localforage';
import { setupCache } from 'axios-cache-adapter';

export default {
  api: null,
  settings: {
    baseURL: '/wp-json/wp/v2',
    params: {
      orderby: 'modified',
    },
  },
  setupCacheAdapter() {
    const cache = setupCache({
      store: localforage.createInstance({
        driver: [localforage.INDEXEDDB, localforage.LOCALSTORAGE],
        name: 'kiku-cache',
      }),
      maxAge: 15 * 60 * 1000, // 15 minutes
      key: request => {
        return request.url + JSON.stringify(request.params);
      },
      exclude: {
        query: false,
      },
    });

    this.settings.adapter = cache.adapter;
  },
  preparedParams() {
    this.settings.params = Object.assign(
      this.settings.params,
      WP.per_page && { per_page: WP.per_page },
      WP.paged && { page: WP.paged },
      WP.search && { search: WP.search },
      WP.tag && { tags: WP.tag },
      WP.category && { categories: WP.category },
      WP.categories_exclude && { categories_exclude: WP.categories_exclude },
    );
  },
  getInstance() {
    if (!this.api) {
      this.preparedParams();
      this.setupCacheAdapter();
      this.api = axios.create(this.settings);
    }

    return this.api;
  },
  getNavigation() {
    var client = this.getInstance();

    return client.get('/wp-json/kiku/v1/navigation', { baseURL: '/' });
  },
  getPostList() {
    var client = this.getInstance();

    return client.get('/posts/?list');
  },
  getPosts(post_id) {
    var client = this.getInstance();

    return client.get(`/posts/${post_id}`);
  },
  getPages(post_id) {
    var client = this.getInstance();

    return client.get(`/pages/${post_id}`);
  },
  getAttachData(post_id) {
    var client = this.getInstance();

    return client.get(`/wp-json/kiku/v1/post/${post_id}`, { baseURL: '/' });
  },
};
<commit_msg>fix: Paramを対象を絞って指定<commit_after>import localforage from 'localforage';
import { setupCache } from 'axios-cache-adapter';

export default {
  api: null,
  settings: {
    baseURL: '/wp-json/wp/v2',
    params: {},
  },
  setupCacheAdapter() {
    const cache = setupCache({
      store: localforage.createInstance({
        driver: [localforage.INDEXEDDB, localforage.LOCALSTORAGE],
        name: 'kiku-cache',
      }),
      maxAge: 15 * 60 * 1000, // 15 minutes
      key: request => {
        return request.url + JSON.stringify(request.params);
      },
      exclude: {
        query: false,
      },
    });

    this.settings.adapter = cache.adapter;
  },
  preparedParams() {
    this.settings.params = Object.assign(
      this.settings.params,
      WP.per_page && { per_page: WP.per_page },
      WP.paged && { page: WP.paged },
      WP.search && { search: WP.search },
      WP.tag && { tags: WP.tag },
      WP.category && { categories: WP.category },
      WP.categories_exclude && { categories_exclude: WP.categories_exclude },
    );
  },
  getInstance() {
    if (!this.api) {
      this.preparedParams();
      this.setupCacheAdapter();
      this.api = axios.create(this.settings);
    }

    return this.api;
  },
  getNavigation() {
    var client = this.getInstance();

    return client.get('/wp-json/kiku/v1/navigation', {
      baseURL: '/',
      params: '',
    });
  },
  getPostList() {
    var client = this.getInstance();

    return client.get('/posts/?list', {
      params: Object.assign(this.settings.params, { orderby: 'modified' }),
    });
  },
  getPosts(post_id) {
    var client = this.getInstance();

    return client.get(`/posts/${post_id}`);
  },
  getPages(post_id) {
    var client = this.getInstance();

    return client.get(`/pages/${post_id}`);
  },
  getAttachData(post_id) {
    var client = this.getInstance();

    return client.get(`/wp-json/kiku/v1/post/${post_id}`, {
      baseURL: '/',
      params: '',
    });
  },
};
<|endoftext|>


<commit_before>(function(window) {

  var WEST = 'west',
      EAST = 'east',
      COLORS = {};

  function addColorPalette(id, base, core, west, east) {
    COLORS[id] = {base:base, core:core, west:west, east:east};
  }

  addColorPalette('main',
    '#1E1A31', // Base
    '#FFFFFF', // Core
  [
    '#FFE193',
    '#FFB46B',
    '#F98A75',
    '#E2687C',
    '#B14B77',
    '#6B2A64'
  ],[
    '#B9F7F5',
    '#72D4E2',
    '#5BAFCD',
    '#518CBE',
    '#4D64B0',
    '#4C4690'
  ]);

  Sketch.create({

    interval: 1,
    container: document.getElementById('container'),

    setup: function() {

      // Behaviours
      this.speed = 2.5;
      this.frequency = 30;
      this.jitter = 0.2;

      // Controls
      this.gui = new dat.GUI();
      this.gui.add(this, 'speed', 0.5, 10);
      this.gui.add(this, 'frequency', 1, 120);
      this.gui.add(this, 'jitter', 0, 1);

      // Setup
      this.setColorPalette(COLORS.main);
      this.reset();
    },

    setColorPalette: function(palette) {
      if (this.palette !== palette) {
        this.palette = palette;
        this.container.style.backgroundColor = palette.base;
      }
    },

    reset: function() {
      this.wave = [{a:0, v:0, t:0}];
      this.counter = 0;
      this.time = 0;
    },

    resize: function() {
      this.center = Math.round(this.width * 0.5);
    },

    update: function() {
      if (++this.counter >= this.frequency) {
        var sign = Math.random() > 0.5 ? 1 : -1;
        var oldPoint = this.wave[this.wave.length-1];
        var newPoint = {a:oldPoint.a, v:0, t:this.time};
        newPoint.a += Math.random() * sign * this.jitter;
        newPoint.a = Math.max(newPoint.a, 0);
        newPoint.a = Math.min(newPoint.a, 1);
        this.wave.push(newPoint);
        if (this.wave.length > 100) {
          this.wave.shift();
        }
        this.counter = 0;
      }
      this.time++;
    },

    draw: function() {
      var i, l,
          MIN = 0.1,
          MAX = 0.8,
          RANGE = MAX - MIN;

      for (i = l = this.palette.east.length; i > 0; i--) {
        this.drawWave(WEST, MIN + RANGE * i / l, this.palette.west[i-1]);
      }
      for (i = l = this.palette.east.length; i > 0; i--) {
        this.drawWave(EAST, MIN + RANGE * i / l, this.palette.east[i-1]);
      }
      this.drawWave(WEST, MIN, this.palette.core);
      this.drawWave(EAST, MIN, this.palette.core);
    },

    drawWave: function(mode, scale, color) {
      var p, c1x, c1y, c2x, c2y,
          i = this.wave.length - 1,
          o = mode === WEST ? -this.center : this.center,
          x = this.center,
          y = this.height;

      this.beginPath();
      this.moveTo(x, y);
      for (i; i >= 0; i--) {
        p = this.wave[i];
        x = this.center + o * p.a * scale;
        y = this.height - (this.time - p.t) * this.speed;
        this.lineTo(x, y);
      }
      this.lineTo(this.center, y);
      this.closePath();
      this.fillStyle = color;
      this.fill();
    },

    catmullRom: function(points) {

      if (points.length < 3) return;

      var p0, p1, p2, p3,
          i6 = 1.0 / 6.0,
          ox = points[0].x,
          oy = points[0].y;

      for (var i = 3, n = points.length; i < n; i++) {

        p0 = points[i-3];
        p1 = points[i-2];
        p2 = points[i-1];
        p3 = points[i];

        this.beginPath();
        this.moveTo(ox, oy);
        this.bezierCurveTo(
          p2.x *  i6 + p1.x - p0.x * i6,
          p2.y *  i6 + p1.y - p0.y * i6,
          p3.x * -i6 + p2.x + p1.x * i6,
          p3.y * -i6 + p2.y + p1.y * i6,
          ox = p2.x,
          oy = p2.y
        );
      }
    }

  });

})(window);
<commit_msg>:gb: Refined defaults<commit_after>(function(window) {

  var WEST = 'west',
      EAST = 'east',
      COLORS = {};

  function addColorPalette(id, base, core, west, east) {
    COLORS[id] = {base:base, core:core, west:west, east:east};
  }

  addColorPalette('main',
    '#1E1A31', // Base
    '#FFFFFF', // Core
  [
    '#FFE193',
    '#FFB46B',
    '#F98A75',
    '#E2687C',
    '#B14B77',
    '#6B2A64'
  ],[
    '#B9F7F5',
    '#72D4E2',
    '#5BAFCD',
    '#518CBE',
    '#4D64B0',
    '#4C4690'
  ]);

  Sketch.create({

    interval: 1,
    container: document.getElementById('container'),

    setup: function() {

      // Behaviours
      this.speed = 2;
      this.frequency = 10;
      this.jitter = 0.1;

      // Controls
      this.gui = new dat.GUI();
      this.gui.add(this, 'speed', 0.5, 10);
      this.gui.add(this, 'frequency', 1, 120);
      this.gui.add(this, 'jitter', 0, 1);

      // Setup
      this.setColorPalette(COLORS.main);
      this.reset();
    },

    setColorPalette: function(palette) {
      if (this.palette !== palette) {
        this.palette = palette;
        this.container.style.backgroundColor = palette.base;
      }
    },

    reset: function() {
      this.wave = [{a:0, v:0, t:0}];
      this.counter = 0;
      this.time = 0;
    },

    resize: function() {
      this.center = Math.round(this.width * 0.5);
    },

    update: function() {
      if (++this.counter >= this.frequency) {
        var sign = Math.random() > 0.5 ? 1 : -1;
        var oldPoint = this.wave[this.wave.length-1];
        var newPoint = {a:oldPoint.a, v:0, t:this.time};
        newPoint.a += Math.random() * sign * this.jitter;
        newPoint.a = Math.max(newPoint.a, 0);
        newPoint.a = Math.min(newPoint.a, 1);
        this.wave.push(newPoint);
        if (this.wave.length > 100) {
          this.wave.shift();
        }
        this.counter = 0;
      }
      this.time++;
    },

    draw: function() {
      var i, l,
          MIN = 0.1,
          MAX = 0.8,
          RANGE = MAX - MIN;

      for (i = l = this.palette.east.length; i > 0; i--) {
        this.drawWave(WEST, MIN + RANGE * i / l, this.palette.west[i-1]);
      }
      for (i = l = this.palette.east.length; i > 0; i--) {
        this.drawWave(EAST, MIN + RANGE * i / l, this.palette.east[i-1]);
      }
      this.drawWave(WEST, MIN, this.palette.core);
      this.drawWave(EAST, MIN, this.palette.core);
    },

    drawWave: function(mode, scale, color) {
      var p, c1x, c1y, c2x, c2y,
          i = this.wave.length - 1,
          o = mode === WEST ? -this.center : this.center,
          x = this.center,
          y = this.height;

      this.beginPath();
      this.moveTo(x, y);
      for (i; i >= 0; i--) {
        p = this.wave[i];
        x = this.center + o * p.a * scale;
        y = this.height - (this.time - p.t) * this.speed;
        this.lineTo(x, y);
      }
      this.lineTo(this.center, y);
      this.closePath();
      this.fillStyle = color;
      this.fill();
    },

    catmullRom: function(points) {

      if (points.length < 3) return;

      var p0, p1, p2, p3,
          i6 = 1.0 / 6.0,
          ox = points[0].x,
          oy = points[0].y;

      for (var i = 3, n = points.length; i < n; i++) {

        p0 = points[i-3];
        p1 = points[i-2];
        p2 = points[i-1];
        p3 = points[i];

        this.beginPath();
        this.moveTo(ox, oy);
        this.bezierCurveTo(
          p2.x *  i6 + p1.x - p0.x * i6,
          p2.y *  i6 + p1.y - p0.y * i6,
          p3.x * -i6 + p2.x + p1.x * i6,
          p3.y * -i6 + p2.y + p1.y * i6,
          ox = p2.x,
          oy = p2.y
        );
      }
    }

  });

})(window);
<|endoftext|>


<commit_before>(function(window) {

  var WEST = 'west',
      EAST = 'east',
      CORE = 'core',
      COLORS = {};

  function addColorPalette(id, base, core, west, east) {
    COLORS[id] = {base:base, core:core, west:west, east:east};
  }

  addColorPalette('main',
    '#1E1A31', // Base
    '#FFFFFF', // Core
  [
    '#FFE193',
    '#FFB46B',
    '#F98A75',
    '#E2687C',
    '#B14B77',
    '#6B2A64'
  ],[
    '#B9F7F5',
    '#72D4E2',
    '#5BAFCD',
    '#518CBE',
    '#4D64B0',
    '#4C4690'
  ]);

  Sketch.create({

    interval: 1,
    container: document.getElementById('container'),

    setup: function() {
      this.setColorPalette(COLORS.main);
      this.reset();
    },

    setColorPalette: function(palette) {
      if (this.palette !== palette) {
        this.palette = palette;
        this.container.style.backgroundColor = palette.base;
      }
    },

    reset: function() {
      this.wave = [0];
    },

    resize: function() {
      this.center = Math.round(this.width * 0.5);
    },

    update: function() {
      var sign = Math.random() > 0.5 ? 1 : -1;
      var value = this.wave[this.wave.length-1];
      value += Math.random() * sign * 0.05;
      value = Math.max(value, 0);
      value = Math.min(value, 1);
      this.wave.push(value);
      if (this.wave.length > this.height / 2) {
        this.wave.shift();
      }
    },

    draw: function() {
      var i, l,
          MIN = 0.1,
          MAX = 0.8,
          STEP = 2,
          RANGE = MAX - MIN;

      for (i = l = this.palette.east.length; i > 0; i--) {
        this.drawWave(WEST, MIN + RANGE * i / l, STEP, this.palette.west[i-1]);
      }
      for (i = l = this.palette.east.length; i > 0; i--) {
        // this.drawWave(EAST, MIN + RANGE * i / l, STEP, this.palette.east[i-1]);
      }
      this.drawWave(CORE, MIN, STEP, this.palette.core);
    },

    drawWave: function(mode, scale, step, color) {
      var c1x, c1y, c2x, c2y;
      var i = this.wave.length - 1;
      var x = Math.round(this.center + this.center * this.wave[i] * scale);
      var y = this.height;
      this.beginPath();
      this.moveTo(this.center, y);
      this.lineTo(x, y);
      for (i; i >= 0; i--) {
        c1x = x;
        c1y = y - step * 0.5;
        c2x = Math.round(this.center + this.center * this.wave[i] * scale);
        c2y = y - step * 0.5;
        y = y - step;
        x = c2x;
        this.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
        if (y < 0) break;
      }
      this.lineTo(this.center, y);
      this.closePath();
      this.fillStyle = color;
      this.fill();
    }
  });

})(window);
<commit_msg>:gb: Tweaked step values<commit_after>(function(window) {

  var WEST = 'west',
      EAST = 'east',
      CORE = 'core',
      COLORS = {};

  function addColorPalette(id, base, core, west, east) {
    COLORS[id] = {base:base, core:core, west:west, east:east};
  }

  addColorPalette('main',
    '#1E1A31', // Base
    '#FFFFFF', // Core
  [
    '#FFE193',
    '#FFB46B',
    '#F98A75',
    '#E2687C',
    '#B14B77',
    '#6B2A64'
  ],[
    '#B9F7F5',
    '#72D4E2',
    '#5BAFCD',
    '#518CBE',
    '#4D64B0',
    '#4C4690'
  ]);

  Sketch.create({

    interval: 1,
    container: document.getElementById('container'),

    setup: function() {
      this.setColorPalette(COLORS.main);
      this.reset();
    },

    setColorPalette: function(palette) {
      if (this.palette !== palette) {
        this.palette = palette;
        this.container.style.backgroundColor = palette.base;
      }
    },

    reset: function() {
      this.wave = [0];
    },

    resize: function() {
      this.center = Math.round(this.width * 0.5);
    },

    update: function() {
      var sign = Math.random() > 0.5 ? 1 : -1;
      var value = this.wave[this.wave.length-1];
      value += Math.random() * sign * 0.08;
      value = Math.max(value, 0);
      value = Math.min(value, 1);
      this.wave.push(value);
      if (this.wave.length > this.height / 2) {
        this.wave.shift();
      }
    },

    draw: function() {
      var i, l,
          MIN = 0.1,
          MAX = 0.8,
          STEP = 2,
          RANGE = MAX - MIN;

      for (i = l = this.palette.east.length; i > 0; i--) {
        this.drawWave(WEST, MIN + RANGE * i / l, STEP, this.palette.west[i-1]);
      }
      for (i = l = this.palette.east.length; i > 0; i--) {
        // this.drawWave(EAST, MIN + RANGE * i / l, STEP, this.palette.east[i-1]);
      }
      this.drawWave(CORE, MIN, STEP, this.palette.core);
    },

    drawWave: function(mode, scale, step, color) {
      var c1x, c1y, c2x, c2y;
      var i = this.wave.length - 1;
      var x = Math.round(this.center + this.center * this.wave[i] * scale);
      var y = this.height;
      this.beginPath();
      this.moveTo(this.center, y);
      this.lineTo(x, y);
      for (i; i >= 0; i--) {
        c1x = x;
        c1y = y - step * 0.5;
        c2x = Math.round(this.center + this.center * this.wave[i] * scale);
        c2y = y - step * 0.5;
        y = y - step;
        x = c2x;
        this.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
        if (y < 0) break;
      }
      this.lineTo(this.center, y);
      this.closePath();
      this.fillStyle = color;
      this.fill();
    }
  });

})(window);
<|endoftext|>


<commit_before>'use strict';

var Component = require('substance/ui/Component');
var TextPropertyEditor = require('substance/ui/TextPropertyEditor');

function XRefComponent() {
  XRefComponent.super.apply(this, arguments);
}

XRefComponent.Prototype = function() {

  this.render = function($$) { // eslint-disable-line
    var node = this.props.node;
    var el = $$('span').addClass('sc-xref');

    var labelEditor = $$(TextPropertyEditor, {
      disabled: this.props.disabled,
      tagName: 'span',
      path: [node.id, 'label'],
      withoutBreak: true
    });
    el.append(labelEditor);

    el.addClass('sm-'+node.referenceType);
    return el;
  };
};

Component.extend(XRefComponent);

module.exports = XRefComponent;<commit_msg>Add ref for labelEditor.<commit_after>'use strict';

var Component = require('substance/ui/Component');
var TextPropertyEditor = require('substance/ui/TextPropertyEditor');

function XRefComponent() {
  XRefComponent.super.apply(this, arguments);
}

XRefComponent.Prototype = function() {

  this.render = function($$) { // eslint-disable-line
    var node = this.props.node;
    var el = $$('span').addClass('sc-xref');

    var labelEditor = $$(TextPropertyEditor, {
      disabled: this.props.disabled,
      tagName: 'span',
      path: [node.id, 'label'],
      withoutBreak: true
    }).ref('labelEditor');
    el.append(labelEditor);

    el.addClass('sm-'+node.referenceType);
    return el;
  };
};

Component.extend(XRefComponent);

module.exports = XRefComponent;<|endoftext|>


<commit_before>const { defaults } = require('jest-config');

module.exports = {
  moduleNameMapper: {
    '^.+\\.(png|gif|jpe?g|webp|html|svg|((o|t)tf)|woff2?|ico)$':
      'jest-preset-hops/mocks/file.js',
    '^.+\\.tpl$': 'jest-preset-hops/mocks/tpl.js',
    '^.+\\.css$': 'identity-obj-proxy',
  },
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  transform: {
    '^.+\\.(js|jsx|mjs)$': 'jest-preset-hops/transforms/babel.js',
    '^.+\\.(ts|tsx)$': 'ts-jest',
    '^.+\\.(gql|graphql)$': 'jest-preset-hops/transforms/graphql.js',
  },
  transformIgnorePatterns: [],
  setupFiles: ['regenerator-runtime/runtime'],
};
<commit_msg>fix(jest-preset): explicitly set testURL to fix jsdom localstorage issue<commit_after>const { defaults } = require('jest-config');

module.exports = {
  moduleNameMapper: {
    '^.+\\.(png|gif|jpe?g|webp|html|svg|((o|t)tf)|woff2?|ico)$':
      'jest-preset-hops/mocks/file.js',
    '^.+\\.tpl$': 'jest-preset-hops/mocks/tpl.js',
    '^.+\\.css$': 'identity-obj-proxy',
  },
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  transform: {
    '^.+\\.(js|jsx|mjs)$': 'jest-preset-hops/transforms/babel.js',
    '^.+\\.(ts|tsx)$': 'ts-jest',
    '^.+\\.(gql|graphql)$': 'jest-preset-hops/transforms/graphql.js',
  },
  transformIgnorePatterns: [],
  setupFiles: ['regenerator-runtime/runtime'],
  // fixes: https://github.com/facebook/jest/issues/6766
  testURL: 'http://localhost',
};
<|endoftext|>


<commit_before>var s = require('shared');
const moveOpts = {visualizePathStyle: {stroke: '#0095ff', opacity:0.6}};

var getTarget = function(creep, source) {
    var targets = [];

    if (source && source.structureType == STRUCTURE_LINK) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_STORAGE && creep.pos.getRangeTo(structure) < 3 && structure.store[RESOURCE_ENERGY] < structure.storeCapacity;
            }
        });
    }

    if (_.sum(creep.carry) > creep.carry.RESOURCE_ENERGY) {
        targets = [creep.room.storage];
    }

    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] < creep.carryCapacity && s.isNear(structure.room.controller, structure);
            }
        });
    }

    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                structure.energy < structure.energyCapacity;
            }
        });
    }

    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  (structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
            }
        });
    }
    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] < structure.storeCapacity && s.isNear(structure.room.controller, structure);
            }
        });
    }
    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_STORAGE && structure.store[RESOURCE_ENERGY] < structure.storeCapacity;
            }
        });
    }
    if (targets.length === 0) {
        targets = creep.room.find(FIND_CONSTRUCTION_SITES, {
            filter: (structure) => s.isEnergyEnough(structure)
        });
    }
    return creep.pos.findClosestByRange(targets);
};

var getSource = function(creep, target) {
    var sources = creep.room.find(FIND_DROPPED_ENERGY, {filter: (resource) => {
        return resource.type != RESOURCE_ENERGY && !PathFinder.search(resource, creep, {ignoreCreeps: true, ignoreRoads:true, maxRooms:1, maxOps: 500}).incomplete;
        }
    });
    if (sources.length === 0) {
        sources = creep.room.find(FIND_DROPPED_ENERGY, {
            filter: (resource) => !PathFinder.search(resource, creep, {ignoreCreeps: true, ignoreRoads:true, maxRooms:1, maxOps: 500}).incomplete
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  structure.structureType == STRUCTURE_LINK && structure.energy > 0 && s.isNear(structure, creep.room.storage);
            }
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                var stored = _.sum(structure.store);
                return  structure.structureType == STRUCTURE_CONTAINER && stored > structure.store[RESOURCE_ENERGY];
            }
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] > creep.carryCapacity && !s.isNear(structure.room.controller, structure);
            }
        });
    }

    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  structure.structureType == STRUCTURE_STORAGE && structure.store[RESOURCE_ENERGY] > 0;
            }
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_DROPPED_ENERGY);
    }
    return creep.pos.findClosestByRange(sources);
};

var extract = function(creep, source) {
    var err;
    if (source instanceof Resource) {
        err = creep.pickup(source);
    } else if (source instanceof StructureContainer) {
        err = creep.withdraw(source, firstResource(source, false));
    } else {
        err = creep.withdraw(source, RESOURCE_ENERGY);
        if (err === OK && source.store && source.store[RESOURCE_ENERGY] === 0) {
            err = ERR_NOT_FOUND;
        }
    }
    return err;
};
var deposit = function(creep, target) {
    var err;
    // todo: distinguish store types and energy-only types - for "finished" analysis
    if (target instanceof StructureSpawn || target instanceof StructureExtension || target instanceof StructureContainer || target instanceof StructureTower) {
        err = creep.transfer(target, RESOURCE_ENERGY);
        if (err == OK && target.energy == target.energyCapacity) {
            err = ERR_NOT_FOUND;
        }
    } else if (target instanceof ConstructionSite) {
        if (creep.pos == target.pos) {
            err = ERR_NOT_IN_RANGE;
        } else {
            err = creep.drop(RESOURCE_ENERGY);
        }
    } else if(target instanceof StructureStorage) {
        err = creep.transfer(target, firstResource(creep, true));
    } else {
        err = ERR_NOT_FOUND;
    }
    return err;
};
var errResponse = function errResponse(err, creep, goal) {
    var mem = goal.id;
    switch (err) {
        case ERR_NOT_IN_RANGE:
        err = creep.moveTo(goal, moveOpts);
        break;
        case OK:
        case ERR_FULL:
        case ERR_NOT_ENOUGH_ENERGY:
        case ERR_TIRED:
        case ERR_BUSY:
        case ERR_NOT_FOUND:
            mem = undefined;
            break;
        default:
            creep.say('?');
            break;
    }
    return mem;
};
var roleSherpa = {
    run: function(creep) {
        var err = OK;
        const m = creep.memory;
        const energy = creep.carry.energy;
        const carried = _.sum(creep.carry);
        var target;
        var source;
        var extracting = !m.depositing;

        if (extracting) {
            if (carried == creep.carryCapacity) {
                extracting = false;
            }
        } else {
            if (carried === 0) {
                extracting = true;
            }
        }

        m.depositing = !extracting;

        if (extracting) {
            target = Game.getObjectById(m.target);
            if (m.source) {
                source = Game.getObjectById(m.source);
            }
            if (!source) {
                source = getSource(creep, target);
                m.source = undefined;
            }
            if (source) {
                err = extract(creep, source);
                m.source = errResponse(err, creep, source);
            }
        } else {
            source = Game.getObjectById(m.source);
            if (m.target) {
                target = Game.getObjectById(m.target);
            }
            if (!target) {
                target = getTarget(creep, source);
                m.target = undefined;
            }
            if (target) {
                err = deposit(creep, target);
                m.target = errResponse(err, creep, target);
            }
        }
        return OK;
    }
};

module.exports = roleSherpa;   <commit_msg>start of tasking overhaul -> collect tasks once per role instead of per creep.<commit_after>var s = require('shared');
const moveOpts = {visualizePathStyle: {stroke: '#0095ff', opacity:0.6}};

function onlyThings(item) {
    const notInterested = [LOOK_FLAGS, LOOK_TERRAIN, LOOK_CREEPS, LOOK_MINERALS];
    return notInterested.indexOf(item.type) == -1;
}
function firstResource(container, isCreep) {
    const store = container[isCreep? 'carry' : 'store'];
    for (var key in store) {
        if (store.hasOwnProperty(key) && key != RESOURCE_ENERGY) {
            return key;
        }
    }
    return RESOURCE_ENERGY;
}

var getRoomsTargets = function(room) {
    var targets = [];
    var potentials = _.filter(room.lookAtArea(0, 0, 49, 49, true), onlyThings);
    var i = 0;
    const bucketNames = [
    'almostEmptyControllerContainer',
    'emptyExtensions',
    'emptyTowers',
    'emptyControllerContainer',
    'constructionSites',
    'roomStorage'
    ];
    const buckets = {};

    for (i = 0; i < bucketNames.length; i++) {
        const bucket = [];
        buckets[bucketNames[i]] = bucket;
        targets.push(bucket);
    }

    for (i = 0; i < potentials.length; i++) {
        let item = potentials[i];
        switch (item.type) {
            default:
            break;
        }
    }

    return targets;
};

var getTarget = function(creep, source) {
    var targets = [];

    if (source && source.structureType == STRUCTURE_LINK) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_STORAGE && creep.pos.getRangeTo(structure) < 3 && structure.store[RESOURCE_ENERGY] < structure.storeCapacity;
            }
        });
    }

    if (_.sum(creep.carry) > creep.carry.RESOURCE_ENERGY) {
        targets = [creep.room.storage];
    }

    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] < creep.carryCapacity && s.isNear(structure.room.controller, structure);
            }
        });
    }

    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                structure.energy < structure.energyCapacity;
            }
        });
    }

    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  (structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
            }
        });
    }
    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] < structure.storeCapacity && s.isNear(structure.room.controller, structure);
            }
        });
    }
    if (targets.length === 0) {
        targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_STORAGE && structure.store[RESOURCE_ENERGY] < structure.storeCapacity;
            }
        });
    }
    if (targets.length === 0) {
        targets = creep.room.find(FIND_CONSTRUCTION_SITES, {
            filter: (structure) => s.isEnergyEnough(structure)
        });
    }
    return creep.pos.findClosestByRange(targets);
};

var getSource = function(creep, target) {
    var sources = creep.room.find(FIND_DROPPED_ENERGY, {filter: (resource) => {
        return resource.type != RESOURCE_ENERGY && !PathFinder.search(resource, creep, {ignoreCreeps: true, ignoreRoads:true, maxRooms:1, maxOps: 500}).incomplete;
        }
    });
    if (sources.length === 0) {
        sources = creep.room.find(FIND_DROPPED_ENERGY, {
            filter: (resource) => !PathFinder.search(resource, creep, {ignoreCreeps: true, ignoreRoads:true, maxRooms:1, maxOps: 500}).incomplete
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  structure.structureType == STRUCTURE_LINK && structure.energy > 0 && s.isNear(structure, creep.room.storage);
            }
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                var stored = _.sum(structure.store);
                return  structure.structureType == STRUCTURE_CONTAINER && stored > structure.store[RESOURCE_ENERGY];
            }
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  structure.structureType == STRUCTURE_CONTAINER && structure.store[RESOURCE_ENERGY] > creep.carryCapacity && !s.isNear(structure.room.controller, structure);
            }
        });
    }

    if (sources.length === 0) {
        sources = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return  structure.structureType == STRUCTURE_STORAGE && structure.store[RESOURCE_ENERGY] > 0;
            }
        });
    }
    if (sources.length === 0) {
        sources = creep.room.find(FIND_DROPPED_ENERGY);
    }
    return creep.pos.findClosestByRange(sources);
};

var extract = function(creep, source) {
    var err;
    if (source instanceof Resource) {
        err = creep.pickup(source);
    } else if (source instanceof StructureContainer) {
        err = creep.withdraw(source, firstResource(source, false));
    } else {
        err = creep.withdraw(source, RESOURCE_ENERGY);
        if (err === OK && source.store && source.store[RESOURCE_ENERGY] === 0) {
            err = ERR_NOT_FOUND;
        }
    }
    return err;
};
var deposit = function(creep, target) {
    var err;
    // todo: distinguish store types and energy-only types - for "finished" analysis
    if (target instanceof StructureSpawn || target instanceof StructureExtension || target instanceof StructureContainer || target instanceof StructureTower) {
        err = creep.transfer(target, RESOURCE_ENERGY);
        if (err == OK && target.energy == target.energyCapacity) {
            err = ERR_NOT_FOUND;
        }
    } else if (target instanceof ConstructionSite) {
        if (creep.pos == target.pos) {
            err = ERR_NOT_IN_RANGE;
        } else {
            err = creep.drop(RESOURCE_ENERGY);
        }
    } else if(target instanceof StructureStorage) {
        err = creep.transfer(target, firstResource(creep, true));
    } else {
        err = ERR_NOT_FOUND;
    }
    return err;
};
var errResponse = function errResponse(err, creep, goal) {
    var mem = goal.id;
    switch (err) {
        case ERR_NOT_IN_RANGE:
        err = creep.moveTo(goal, moveOpts);
        break;
        case OK:
        case ERR_FULL:
        case ERR_NOT_ENOUGH_ENERGY:
        case ERR_TIRED:
        case ERR_BUSY:
        case ERR_NOT_FOUND:
            mem = undefined;
            break;
        default:
            creep.say('?');
            break;
    }
    return mem;
};
var roleSherpa = {
    run: function(creep) {
        var err = OK;
        const m = creep.memory;
        const energy = creep.carry.energy;
        const carried = _.sum(creep.carry);
        var target;
        var source;
        var extracting = !m.depositing;

        if (extracting) {
            if (carried == creep.carryCapacity) {
                extracting = false;
            }
        } else {
            if (carried === 0) {
                extracting = true;
            }
        }

        m.depositing = !extracting;

        if (extracting) {
            target = Game.getObjectById(m.target);
            if (m.source) {
                source = Game.getObjectById(m.source);
            }
            if (!source) {
                source = getSource(creep, target);
                m.source = undefined;
            }
            if (source) {
                err = extract(creep, source);
                m.source = errResponse(err, creep, source);
            }
        } else {
            source = Game.getObjectById(m.source);
            if (m.target) {
                target = Game.getObjectById(m.target);
            }
            if (!target) {
                target = getTarget(creep, source);
                m.target = undefined;
            }
            if (target) {
                err = deposit(creep, target);
                m.target = errResponse(err, creep, target);
            }
        }
        return OK;
    }
};

module.exports = roleSherpa;   <|endoftext|>


<commit_before>var path = require('path');
var OFF = 0;
var ERROR = 2;

module.exports = {
  env: {
    es6: true,
    browser: true,
    node: true,
  },
  overrides: [
    {
      files: ['*.spec.js'],
      env: {
        es6: true,
        browser: true,
        node: true,
        jest: true,
      },
    },
    {
      files: ['*.int.js'],
      env: {
        jest: true,
      },
      globals: {
        page: true,
        browser: true,
        context: true,
        jestPuppeteer: true,
      },
    },
  ],
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 2018,
    ecmaFeatures: {
      impliedStrict: true,
    },
  },
  globals: {
    __version: true,
    __filename: true,
    __copyrightYear: true,
    __kolibriModuleName: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/recommended',
    'plugin:import/errors',
    'plugin:import/warnings',
    'prettier',
  ],
  plugins: ['import', 'vue', 'kolibri'],
  settings: {
    'import/resolver': {
      [path.resolve(path.join(path.dirname(__filename), './lib/alias_import_resolver.js'))]: {
        extensions: ['.js', '.vue'],
      },
    },
  },
  rules: {
    'comma-style': ERROR,
    'max-len': [
      ERROR,
      100,
      {
        ignoreStrings: true,
        ignoreTemplateLiterals: true,
        ignoreUrls: true,
        ignoreTrailingComments: true,
      },
    ],
    'vue/max-len': [
      ERROR,
      {
        code: 100,
        template: 100,
        comments: 100,
        ignoreUrls: true,
        ignoreStrings: true,
        ignoreTemplateLiterals: true,
        ignoreHTMLTextContents: true,
        ignoreTrailingComments: true,
      },
    ],
    'vue/attribute-hyphenation': [ERROR, 'never'],
    'vue/require-default-prop': OFF,
    'vue/html-self-closing': [
      ERROR,
      {
        html: {
          void: 'never',
          normal: 'never',
          component: 'always',
        },
        svg: 'always',
        math: 'always',
      },
    ],
    'vue/max-attributes-per-line': [
      ERROR,
      {
        singleline: 5,
        multiline: {
          max: 1,
          allowFirstLine: false,
        },
      },
    ],
    'vue/html-closing-bracket-newline': [
      ERROR,
      {
        singleline: 'never',
        multiline: 'always',
      },
    ],
    'vue/component-name-in-template-casing': [
      ERROR,
      'PascalCase',
      {
        ignores: [
          'mat-svg',
          'file-svg',
          'component',
          'transition',
          'transition-group',
          'router-link',
          'router-view',
        ],
      },
    ],
    'vue/no-spaces-around-equal-signs-in-attribute': ERROR,
    'vue/multiline-html-element-content-newline': [
      ERROR,
      {
        // because of compatibility with our custom HTMLHint rule
        // enforcing top-level content surrounded by one empty line
        allowEmptyLines: true,
      },
    ],
    'vue/order-in-components': [
      ERROR,
      {
        order: [
          'el',
          'name',
          'metaInfo',
          'parent',
          'functional',
          ['delimiters', 'comments'],
          ['components', 'directives', 'filters'],
          'extends',
          'mixins',
          'inheritAttrs',
          'model',
          ['props', 'propsData'],
          'data',
          'computed',
          'watch',
          'beforeRouteEnter',
          'beforeRouteUpdate',
          'beforeRouteLeave',
          'LIFECYCLE_HOOKS',
          'methods',
          ['template', 'render'],
          'renderError',
          '$trs',
        ],
      },
    ],
    'vue/html-indent': [
      ERROR,
      2, // Base indent spaces
      {
        attribute: 1,
        baseIndent: 1,
        closeBracket: 0,
        alignAttributesVertically: true,
      },
    ],
    'vue/static-class-names-order': ERROR,
    'vue/no-deprecated-scope-attribute': ERROR,
    'vue/valid-v-bind-sync': ERROR,
    // TODO Enforcing these rules requires bigger refactor
    // 'vue/no-deprecated-slot-attribute': ERROR,
    // 'vue/no-deprecated-slot-scope-attribute': ERROR,
    'vue/valid-v-slot': ERROR,
    'vue/v-slot-style': ERROR,
    // ESLint rules for interpolated JS
    'vue/object-curly-spacing': [ERROR, 'always'],
    'vue/eqeqeq': [ERROR, 'always'],
    'vue/key-spacing': [ERROR, { afterColon: true }],
    'vue/space-infix-ops': ERROR,
    'vue/space-unary-ops': ERROR,
    'vue/no-lone-template': OFF,

    'import/first': ERROR,
    'import/no-duplicates': ERROR,
    'import/newline-after-import': ERROR,
    'import/order': ERROR,

    // Custom vue rules
    'kolibri/vue-filename-and-component-name-match': ERROR,
    'kolibri/vue-component-registration-casing': ERROR,
    'kolibri/vue-no-unused-properties': ERROR,
    'kolibri/vue-no-unused-vuex-properties': ERROR,
    'kolibri/vue-no-unused-methods': ERROR,
    'kolibri/vue-no-unused-vuex-methods': ERROR,
    'kolibri/vue-watch-no-string': ERROR,
    'kolibri/vue-no-unused-translations': ERROR,
    'kolibri/vue-no-undefined-string-uses': ERROR,
  },
};
<commit_msg>Enable vue/no-deprecated-slot-attribute rule<commit_after>var path = require('path');
var OFF = 0;
var ERROR = 2;

module.exports = {
  env: {
    es6: true,
    browser: true,
    node: true,
  },
  overrides: [
    {
      files: ['*.spec.js'],
      env: {
        es6: true,
        browser: true,
        node: true,
        jest: true,
      },
    },
    {
      files: ['*.int.js'],
      env: {
        jest: true,
      },
      globals: {
        page: true,
        browser: true,
        context: true,
        jestPuppeteer: true,
      },
    },
  ],
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 2018,
    ecmaFeatures: {
      impliedStrict: true,
    },
  },
  globals: {
    __version: true,
    __filename: true,
    __copyrightYear: true,
    __kolibriModuleName: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/recommended',
    'plugin:import/errors',
    'plugin:import/warnings',
    'prettier',
  ],
  plugins: ['import', 'vue', 'kolibri'],
  settings: {
    'import/resolver': {
      [path.resolve(path.join(path.dirname(__filename), './lib/alias_import_resolver.js'))]: {
        extensions: ['.js', '.vue'],
      },
    },
  },
  rules: {
    'comma-style': ERROR,
    'max-len': [
      ERROR,
      100,
      {
        ignoreStrings: true,
        ignoreTemplateLiterals: true,
        ignoreUrls: true,
        ignoreTrailingComments: true,
      },
    ],
    'vue/max-len': [
      ERROR,
      {
        code: 100,
        template: 100,
        comments: 100,
        ignoreUrls: true,
        ignoreStrings: true,
        ignoreTemplateLiterals: true,
        ignoreHTMLTextContents: true,
        ignoreTrailingComments: true,
      },
    ],
    'vue/attribute-hyphenation': [ERROR, 'never'],
    'vue/require-default-prop': OFF,
    'vue/html-self-closing': [
      ERROR,
      {
        html: {
          void: 'never',
          normal: 'never',
          component: 'always',
        },
        svg: 'always',
        math: 'always',
      },
    ],
    'vue/max-attributes-per-line': [
      ERROR,
      {
        singleline: 5,
        multiline: {
          max: 1,
          allowFirstLine: false,
        },
      },
    ],
    'vue/html-closing-bracket-newline': [
      ERROR,
      {
        singleline: 'never',
        multiline: 'always',
      },
    ],
    'vue/component-name-in-template-casing': [
      ERROR,
      'PascalCase',
      {
        ignores: [
          'mat-svg',
          'file-svg',
          'component',
          'transition',
          'transition-group',
          'router-link',
          'router-view',
        ],
      },
    ],
    'vue/no-spaces-around-equal-signs-in-attribute': ERROR,
    'vue/multiline-html-element-content-newline': [
      ERROR,
      {
        // because of compatibility with our custom HTMLHint rule
        // enforcing top-level content surrounded by one empty line
        allowEmptyLines: true,
      },
    ],
    'vue/order-in-components': [
      ERROR,
      {
        order: [
          'el',
          'name',
          'metaInfo',
          'parent',
          'functional',
          ['delimiters', 'comments'],
          ['components', 'directives', 'filters'],
          'extends',
          'mixins',
          'inheritAttrs',
          'model',
          ['props', 'propsData'],
          'data',
          'computed',
          'watch',
          'beforeRouteEnter',
          'beforeRouteUpdate',
          'beforeRouteLeave',
          'LIFECYCLE_HOOKS',
          'methods',
          ['template', 'render'],
          'renderError',
          '$trs',
        ],
      },
    ],
    'vue/html-indent': [
      ERROR,
      2, // Base indent spaces
      {
        attribute: 1,
        baseIndent: 1,
        closeBracket: 0,
        alignAttributesVertically: true,
      },
    ],
    'vue/static-class-names-order': ERROR,
    'vue/no-deprecated-scope-attribute': ERROR,
    'vue/valid-v-bind-sync': ERROR,
    // TODO Enforcing these rules requires bigger refactor
    // 'vue/no-deprecated-slot-scope-attribute': ERROR,
    'vue/no-deprecated-slot-scope-attribute': ERROR,
    'vue/valid-v-slot': ERROR,
    'vue/v-slot-style': ERROR,
    // ESLint rules for interpolated JS
    'vue/object-curly-spacing': [ERROR, 'always'],
    'vue/eqeqeq': [ERROR, 'always'],
    'vue/key-spacing': [ERROR, { afterColon: true }],
    'vue/space-infix-ops': ERROR,
    'vue/space-unary-ops': ERROR,
    'vue/no-lone-template': OFF,

    'import/first': ERROR,
    'import/no-duplicates': ERROR,
    'import/newline-after-import': ERROR,
    'import/order': ERROR,

    // Custom vue rules
    'kolibri/vue-filename-and-component-name-match': ERROR,
    'kolibri/vue-component-registration-casing': ERROR,
    'kolibri/vue-no-unused-properties': ERROR,
    'kolibri/vue-no-unused-vuex-properties': ERROR,
    'kolibri/vue-no-unused-methods': ERROR,
    'kolibri/vue-no-unused-vuex-methods': ERROR,
    'kolibri/vue-watch-no-string': ERROR,
    'kolibri/vue-no-unused-translations': ERROR,
    'kolibri/vue-no-undefined-string-uses': ERROR,
  },
};
<|endoftext|>


<commit_before>Package.describe({
  name: "mdg:geolocation",
  summary: "Provides reactive geolocation on desktop and mobile.",
  version: "1.0.2",
  git: "https://github.com/meteor/mobile-packages"
});

Cordova.depends({
  "org.apache.cordova.geolocation": "0.3.10"
});

Package.on_use(function (api) {
  api.use(["reactive-var"]);
  api.versionsFrom("METEOR@0.9.2");
  api.add_files(["geolocation.js"], "client");
  api.export("Geolocation", "client");
});<commit_msg>Bump version for PR<commit_after>Package.describe({
  name: "mdg:geolocation",
  summary: "Provides reactive geolocation on desktop and mobile.",
  version: "1.0.3",
  git: "https://github.com/meteor/mobile-packages"
});

Cordova.depends({
  "org.apache.cordova.geolocation": "0.3.10"
});

Package.on_use(function (api) {
  api.use(["reactive-var"]);
  api.versionsFrom("METEOR@0.9.2");
  api.add_files(["geolocation.js"], "client");
  api.export("Geolocation", "client");
});<|endoftext|>


<commit_before>
var express = require('express');
var StreamCache = require('stream-cache');
var browserify = require('browserify');
var Swatch = require('./swatch');
var watchify = require('watchify');
var path = require('path');
var Stream = require('stream');
var xtend = require('xtend');

var parseConfig = require('./lib/config');
var validVariations = require('./lib/variations');
var treenherit = require('mendel-treenherit');

module.exports = MendelMiddleware;

function MendelMiddleware(opts) {
    var router = express.Router();
    var config = parseConfig(opts);
    var existingVariations = validVariations(config);
    var base = config.base || 'base';
    var routePath = '/mendel/:variations/:bundle\.js' || opts.path;

    existingVariations = existingVariations.concat({
        id: base,
        chain: [config.basetree || 'base'],
    });

    // server side watch
    var swatch = new Swatch({
        basedir: opts.basedir,
        outdir: opts.mountdir,
        variations: existingVariations,
        verbose: opts.verbose
    });

    swatch.on('error', function (err) {
        console.error(err.stack);
    });

    return router.get(routePath, function(req, res, next) {
        var variations = (req.params.variations||'').split(',').concat(base);
        var bundle = req.params.bundle;

        var bundleConfig = config.bundles[bundle];
        var dirs = resolveVariations(existingVariations, variations);

        if (!dirs.length || !bundleConfig) {
            return next();
        }

        // return res.end(JSON.stringify({
        //     bundle:bundle,
        //     variations:variations,
        //     bundleConfig:bundleConfig,
        //     dirs:dirs,
        //     existingVariations:existingVariations,
        //     config:config
        // }, null, '  '));

        res.header('content-type', 'application/javascript');

        bundleConfig = xtend(bundleConfig, {
            base: base,
            basedir: config.basedir,
            cache: {},
            packageCache: {}
        });

        var bundleStream = cachedStreamBundle(bundleConfig, dirs);
        bundleStream.on('error', function(e) {
            console.error(e.stack);
            res.send('console.error( "Error compiling client bundle", ' +
                JSON.stringify({ stack: e.stack }) + ')').end();
        });
        bundleStream.pipe(res);
    });
}

function resolveVariations(existingVariations, variations) {
    var i, j, evar, dir, resolved = [];
    // walk in reverse and fill in reverse achieves desired order
    for (i = existingVariations.length-1; i >= 0; i--) {
        evar = existingVariations[i];
        if (-1 !== variations.indexOf(evar.id)) {
            for (j = evar.chain.length-1; j >= 0; j--) {
                dir = evar.chain[j];
                if (-1 === resolved.indexOf(dir)) {
                    resolved.unshift(dir);
                }
            }
        }
    }
    return resolved;
}

var streamCache = {};
function cachedStreamBundle(bundleConfig, dirs) {
    var id = [bundleConfig.id].concat(dirs).join('/');
    if (!streamCache[id]) {
        streamCache[id] = new StreamCache();
        streamCache[id].outlets = [];
        getCachedWatchfy(id, bundleConfig, dirs, function(err, bundler) {
            function bundleError(e) {
                streamCache[id].outlets.forEach(function(stream) {
                    stream.emit('error', e);
                });
                delete streamCache[id];
            }
            if (err) return bundleError(err);
            var bundle = bundler.bundle();
            bundle.on('error', bundleError);
            bundle.on('transform', function(tr) {
                tr.on('error', bundleError);
            });
            bundle.pipe(streamCache[id]);
        });
    }

    var outStream = new Stream.PassThrough();
    streamCache[id].outlets.push(outStream);
    outStream.on('end', function() {
        streamCache[id].outlets.splice(streamCache[id].outlets.indexOf(outStream), 1);
    });
    streamCache[id].pipe(outStream);
    return outStream;
}

var watchfyCache = {};
function getCachedWatchfy(id, bundleConfig, dirs, cb) {
    if (watchfyCache[id]) {
        return cb(null, watchfyCache[id]);
    }

    // TODO: async lookup of entries
    bundleConfig.entries = bundleConfig.entries.map(function(entry) {
        return path.join(bundleConfig.base, entry);
    });

    var bundler = browserify(bundleConfig);
    bundler.transform(treenherit, { dirs: dirs });
    bundler.plugin(watchify);

    bundler.on('update', function() {
        streamCache[id] = null;
    });

    watchfyCache[id] = bundler;
    cb(null, watchfyCache[id]);
}
<commit_msg>Small refactor, not functionality change<commit_after>
var express = require('express');
var StreamCache = require('stream-cache');
var browserify = require('browserify');
var Swatch = require('./swatch');
var watchify = require('watchify');
var path = require('path');
var Stream = require('stream');
var xtend = require('xtend');

var parseConfig = require('./lib/config');
var validVariations = require('./lib/variations');
var treenherit = require('mendel-treenherit');

module.exports = MendelMiddleware;

function MendelMiddleware(opts) {
    var router = express.Router();
    var config = parseConfig(opts);
    var existingVariations = validVariations(config);
    var base = config.base || 'base';
    var routePath = '/mendel/:variations/:bundle\.js' || opts.path;

    existingVariations = existingVariations.concat({
        id: base,
        chain: [config.basetree || 'base'],
    });

    // server side watch
    var swatch = new Swatch({
        basedir: opts.basedir,
        outdir: opts.mountdir,
        variations: existingVariations,
        verbose: opts.verbose
    });

    swatch.on('error', function (err) {
        console.error(err.stack);
    });

    return router.get(routePath, function(req, res, next) {
        var variations = (req.params.variations||'').split(',').concat(base);
        var bundle = req.params.bundle;

        var bundleConfig = config.bundles[bundle];
        var dirs = resolveVariations(existingVariations, variations);

        if (!dirs.length || !bundleConfig) {
            return next();
        }

        // return res.end(JSON.stringify({
        //     bundle:bundle,
        //     variations:variations,
        //     bundleConfig:bundleConfig,
        //     dirs:dirs,
        //     existingVariations:existingVariations,
        //     config:config
        // }, null, '  '));

        res.header('content-type', 'application/javascript');

        bundleConfig = xtend(bundleConfig, {
            base: base,
            basedir: config.basedir,
            cache: {},
            packageCache: {}
        });

        var bundleStream = cachedStreamBundle(bundleConfig, dirs);
        bundleStream.on('error', function(e) {
            console.error(e.stack);
            res.send('console.error( "Error compiling client bundle", ' +
                JSON.stringify({ stack: e.stack }) + ')').end();
        });
        bundleStream.pipe(res);
    });
}

function resolveVariations(existingVariations, variations) {
    var i, j, evar, dir, resolved = [];
    // walk in reverse and fill in reverse achieves desired order
    for (i = existingVariations.length-1; i >= 0; i--) {
        evar = existingVariations[i];
        if (-1 !== variations.indexOf(evar.id)) {
            for (j = evar.chain.length-1; j >= 0; j--) {
                dir = evar.chain[j];
                if (-1 === resolved.indexOf(dir)) {
                    resolved.unshift(dir);
                }
            }
        }
    }
    return resolved;
}

var streamCache = {};
function cachedStreamBundle(bundleConfig, dirs) {
    var id = [bundleConfig.id].concat(dirs).join('/');
    var curStream = streamCache[id];
    if (!curStream) {
        curStream = (streamCache[id] = new StreamCache());
        curStream.outlets = [];

        getCachedWatchfy(id, bundleConfig, dirs, function(err, watchBundle) {

            // multiple kinds of error handling start
            if (err) return bundleError(err);

            var bundle = watchBundle.bundle();
            bundle.on('error', bundleError);
            bundle.on('transform', function(tr) {
                tr.on('error', bundleError);
            });

            function bundleError(e) {
                curStream.outlets.forEach(function(stream) {
                    stream.emit('error', e);
                });
                delete streamCache[id];
            }
            // multiple kinds of error handling end

            watchBundle.on('update', function() {
                delete streamCache[id];
            });
            bundle.pipe(curStream);
        });
    }

    var outStream = new Stream.PassThrough();
    curStream.outlets.push(outStream);
    outStream.on('end', function() {
        curStream.outlets.splice(curStream.outlets.indexOf(outStream), 1);
    });
    curStream.pipe(outStream);
    return outStream;
}

var watchfyCache = {};
function getCachedWatchfy(id, bundleConfig, dirs, cb) {
    if (watchfyCache[id]) {
        return cb(null, watchfyCache[id]);
    }

    // TODO: async lookup of entries
    bundleConfig.entries = bundleConfig.entries.map(function(entry) {
        return path.join(bundleConfig.base, entry);
    });

    var bundler = browserify(bundleConfig);
    bundler.transform(treenherit, { dirs: dirs });
    bundler.plugin(watchify);

    watchfyCache[id] = bundler;
    cb(null, watchfyCache[id]);
}
<|endoftext|>


<commit_before>Ext.define('devilry.statistics.sidebarplugin.qualifiesforexam.Choices', {
});
<commit_msg>apps.statistics: Removed unused file.<commit_after><|endoftext|>


<commit_before>console.log('in test file');

Tinytest.add("Postgres - basics", function (test) {

  if (Meteor.isServer) {
    console.log('in test');

    //first delete table
    //Drop table work, but, it seems like the notify does not be dropped.
    Postgres.dropTable('tasks');

    // way to detect the existence of specific table?

    // Version 1
    // var taskTable = {
    //   text: [Postgres._DataTypes['$string'], Postgres._TableConstraints['$notnull']]
    // };

    // Varsion 2
    // var taskTable = {
    //   text: [Postgres._DataTypes['$string'], 'not null']
    // };

    // Postgres.createTable('tasks', taskTable);
  }

  test.equal(true, true);

})

<commit_msg>create table waiting for the syntax finished<commit_after>console.log('in test file');

Tinytest.add("Postgres - basics", function (test) {

  if (Meteor.isServer) {
    console.log('in test');

    //first delete table
    //Drop table work, but, it seems like the notify does not be dropped.
    Postgres.dropTable('tasks');

    // way to detect the existence of specific table?

    // Version 1
    // var taskTable = {
    //   text: ['$string', '$notnull']
    // };

    // Varsion 2
    // var taskTable = {
    //   text: ['$string', 'not null']
    // };

    // Postgres.createTable('tasks', taskTable);
  }

  test.equal(true, true);

})

<|endoftext|>