<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React from 'react';
// import cx from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { blue300 } from 'material-ui/styles/colors';
import s from './Navigation.css';
import Link from '../Link';
import LogInModal from './LogInModal';
import SignUpModal from './SignUpModal';

const muiTheme = getMuiTheme({
  borderRadius: 5,
  palette: {
    primary1Color: blue300,
  },
}, { userAgent: 'all' });

class Navigation extends React.Component {
  constructor(props) {
    super(props);
    this.logIn = this.logIn.bind(this);
    this.signUp = this.signUp.bind(this);
    this.state = { logInPopUp: false, signUpPopUp: false };
  }

  logIn() {
    this.setState({ logInPopUp: true });
  }

  signUp() {
    this.setState({ signUpPopUp: true });
  }

  render() {
    return (
      <MuiThemeProvider muiTheme={muiTheme}>

          <Link className={s.link} to="/about">About</Link>
          <Link className={s.link} to="/contact">Contact</Link>
           |
          {(this.state.logInPopUp) ? <RaisedButton label="Log in" labelColor="#AFAFAF" />
            : <RaisedButton label="Log in" onClick={this.logIn} labelColor="#AFAFAF" />}
          or
          {(this.state.signUpPopUp) ? <RaisedButton label="Sign up" primary />
            : <RaisedButton label="Sign up" onClick={this.signUp} primary />}

          {(this.state.logInPopUp) ?
            <LogInModal className={s.logInPage} /> : null }
          {(this.state.signUpPopUp) ?
            <SignUpModal className={s.signUpPage} /> : null }

      </MuiThemeProvider>
    );
  }
}

export default withStyles(s)(Navigation);
<commit_msg>log in and sign up<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React from 'react';
// import cx from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { blue300 } from 'material-ui/styles/colors';
import s from './Navigation.css';
import Link from '../Link';
import LogInModal from './LogInModal';
import SignUpModal from './SignUpModal';

const muiTheme = getMuiTheme({
  borderRadius: 5,
  palette: {
    primary1Color: blue300,
  },
}, { userAgent: 'all' });

class Navigation extends React.Component {
  constructor(props) {
    super(props);
    this.logIn = this.logIn.bind(this);
    this.signUp = this.signUp.bind(this);
    this.state = { logInPopUp: false, signUpPopUp: false };
  }

  logIn() {
    this.setState({ logInPopUp: !this.state.logInPopUp });
  }

  signUp() {
    this.setState({ signUpPopUp: !this.state.signUpPopUp });
  }

  render() {
    return (
      <MuiThemeProvider muiTheme={muiTheme}>

          <Link className={s.link} to="/about">About</Link>
          <Link className={s.link} to="/contact">Contact</Link>
           |
          <RaisedButton label="Log in" onClick={this.logIn} labelColor="#AFAFAF" />
          or
          <RaisedButton label="Sign up" onClick={this.signUp} primary />

          {(this.state.logInPopUp) ?
            <LogInModal
              className={s.logInPage}
            /> : null }
          {(this.state.signUpPopUp) ?
            <SignUpModal
              className={s.signUpPage}
            /> : null}

      </MuiThemeProvider>
    );
  }
}

export default withStyles(s)(Navigation);
<|endoftext|>


<commit_before>var _ = require('lodash');

var React = require('react');

var MessagesSection = require('./dialog/MessagesSection.react');
var ComposeSection = require('./dialog/ComposeSection.react');

var DialogStore = require('../stores/DialogStore');
var MessageStore = require('../stores/MessageStore');

var initialMessagesCount = 100;

var getStateFromStores = function() {
  var messages = MessageStore.getAll();

  var messagesToRender;

  if (messages.length > initialMessagesCount) {
    messagesToRender = messages.slice(messages.length - initialMessagesCount);
  } else {
    messagesToRender = messages;
  }

  return({
    dialog: DialogStore.getSelectedDialog(),
    messages: messages,
    messagesToRender: messagesToRender
  });
};

var DialogSection = React.createClass({
  getInitialState: function() {
    return(getStateFromStores());
  },

  componentDidMount: function() {
    DialogStore.addSelectListener(this._onChange);
    MessageStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    MessageStore.removeChangeListener(this._onChange);
    DialogStore.removeSelectListener(this._onChange);
  },

  render: function() {
    return(

        <MessagesSection messages={this.state.messagesToRender} ref="MessagesSection"/>
        <ComposeSection dialog={this.state.dialog}/>

    )
  },

  _scrollToBottom: function() {
    var ul = this.refs.MessagesSection.getDOMNode();
    ul.scrollTop = ul.scrollHeight;
  },

  _scrollToBottomDebounced: _.debounce(function() {
    this._scrollToBottom();
  }, 50),

  _scrolledToBottom: function() {
    var self = this.getDOMNode();

    return(self.scrollHeight - self.scrollTop - self.clientHeight == 0);
  },

  _onChange: function() {
    this.setState(getStateFromStores());

    if (this._scrolledToBottom()) {
      this._scrollToBottomDebounced()
    }
  }
});

module.exports = DialogSection;
<commit_msg>perf(web): fasten messages rendering<commit_after>var _ = require('lodash');

var React = require('react');

var MessagesSection = require('./dialog/MessagesSection.react');
var ComposeSection = require('./dialog/ComposeSection.react');

var DialogStore = require('../stores/DialogStore');
var MessageStore = require('../stores/MessageStore');

var initialMessagesCount = 100;

var getStateFromStores = function() {
  var messages = MessageStore.getAll();

  var messagesToRender;

  if (messages.length > initialMessagesCount) {
    messagesToRender = messages.slice(messages.length - initialMessagesCount);
  } else {
    messagesToRender = messages;
  }

  return({
    dialog: DialogStore.getSelectedDialog(),
    messages: messages,
    messagesToRender: messagesToRender
  });
};

var DialogSection = React.createClass({
  getInitialState: function() {
    return(getStateFromStores());
  },

  componentDidMount: function() {
    DialogStore.addSelectListener(this._onChange);
    MessageStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    MessageStore.removeChangeListener(this._onChange);
    DialogStore.removeSelectListener(this._onChange);
  },

  render: function() {
    return(

        <MessagesSection messages={this.state.messagesToRender} ref="MessagesSection"/>
        <ComposeSection dialog={this.state.dialog}/>

    )
  },

  _scrollToBottom: function() {
    var ul = this.refs.MessagesSection.getDOMNode();
    ul.scrollTop = ul.scrollHeight;
  },

  _scrollToBottomDebounced: _.debounce(function() {
    this._scrollToBottom();
  }, 50),

  _scrolledToBottom: function() {
    var self = this.getDOMNode();

    return(self.scrollHeight - self.scrollTop - self.clientHeight == 0);
  },

  _onChange: _.debounce(function() {
    this.setState(getStateFromStores());

    if (this._scrolledToBottom()) {
      this._scrollToBottomDebounced()
    }
  }, 30, 300)
});

module.exports = DialogSection;
<|endoftext|>


<commit_before>(function($) {

    function ButterList(options) {
      this.$el = $(options.el);
      this.$topPadding = null;
      this.$bottomPadding = null;

      this.items = options.items || [];
      this.itemRenderer = options.renderer || null;
      this.ignoreScroll = false;

      this.rendered = false;

      this.$el.on('scroll', this.onScroll.bind(this));
      // If items were passed in, render
      if (this.items && this.items.length) {
        this.render();
      }
    };

    ButterList.prototype.appendItem = function(item) {
      if (isArray(item)) {
        this.items.push.apply(this.items, item);
      } else {
        this.items.append(item);
      }
      if (this.rendered) {
        this.fullUpdate();
      }
      this.render();
    };

    ButterList.prototype.prependItem = function(item) {
      if (isArray(item)) {
        this.items.unshift.apply(this.items, item);
      } else {
        this.items.unshift(item);
      }
      if (this.rendered) {
        this.fullUpdate();
      }
      this.render();
    };

    ButterList.prototype.bindItemRenderer = function(renderer) {
      this.itemRenderer = renderer;
    };

    ButterList.prototype.getAverageItemHeight = function() {
      if (this.averageHeight) {
        return this.averageHeight;
      }
      var heights = [];
      var iterator = 0;
      for (var key in this.itemHeights) {
        heights.push(this.itemHeights[key]);
        // Stop after 100. If this turns out terrible, make it better.
        if (++iterator === 100) {
          this.averageHeight = average(heights);
          break;
        }
      }
      return heights.length ? average(heights) : 1;
    };

    ButterList.prototype.getBottomPadHeight = function() {
      var itemsBelowCount = this.items.length - this.bottomItemIndex;
      return itemsBelowCount * this.getAverageItemHeight();
    };

    ButterList.prototype.getTopPadHeight = function() {
      return this.topItemIndex * this.getAverageItemHeight();
    };

    ButterList.prototype.getPaddingFromType = function(type) {
      return type === 'top' ? this.$topPadding : this.$bottomPadding;
    };

    ButterList.prototype.onScroll = function() {
      var delta = this.prevScrollTop - this.$el.scrollTop();
      this.prevScrollTop = this.$el.scrollTop();
      this.update(delta);
    };

    ButterList.prototype.removeItems = function() {
      this.$topPadding.nextUntil('.butterlist-padding-bottom').remove();
    };

    ButterList.prototype.removeItemsAbove = function() {
      var itemsToRemove = [];
      for (var i = this.topItemIndex; i < this.bottomItemIndex && i < this.items.length; i++) {
        var $nextItem = this.$topItem.next();
        if ($nextItem === this.$bottomPadding || this.$topItem.position().top >= -5) {
          break;
        }
        else {
          itemsToRemove.push(this.$topItem);
        }
        this.topItemIndex = i + 1;
        this.$topItem = $nextItem;
      }
      itemsToRemove.forEach(function(item) { item.remove(); });
    };

    ButterList.prototype.render = function() {
      if (this.rendered) {
        return;
      }

      this.itemHeights = {};

      this.averageHeight = null;

      this.$topItem = null;
      this.$bottomItem = null;
      this.topItemIndex = 0;
      this.bottomItemIndex = -1;

      this.prevScrollTop = 0;

      this.rendered = true;
      this.$topPadding = $('

').appendTo(this.$el);
      this.$bottomPadding = $('

').appendTo(this.$el);

      this.renderItemsBelow();
      this.updatePaddingBottom();
    };

    ButterList.prototype.renderItems = function() {
      var $rendered = null;
      for (var i = this.topItemIndex; i <= this.bottomItemIndex && i < this.items.length; i++) {
        $rendered = $(this.itemRenderer(this.items[i])).insertBefore(this.$bottomPadding).data('index', i);
        if (i === this.topItemIndex) {
          this.$topItem = $rendered;
        }
      }
      this.$bottomItem = $rendered;
    };

    ButterList.prototype.renderItemsAbove = function() {
      if (this.topItemIndex <= 0 || this.$topItem.position().top < 0) {
        return;
      }

      var $renderedItem = null;
      for (var i = this.topItemIndex - 1; i >= 0; i--) {
        $renderedItem = $(this.itemRenderer(this.items[i])).insertAfter(this.$topPadding).data('index', i);
        this.resizePadding('top', -$renderedItem.outerHeight());
        this.itemHeights[i] = $renderedItem.outerHeight();
        this.$topItem = $renderedItem;
        if ($renderedItem.position().top < 0) {
          break;
        }
      }

      this.topItemIndex = i;
    };

    ButterList.prototype.removeItemsBelow = function() {
      var itemsToRemove = [];
      var averageHeight = this.getAverageItemHeight();
      for (var i = this.bottomItemIndex; i > this.topItemIndex && i >= 0; i--) {
        var $prevItem = this.$bottomItem.prev();
        if ($prevItem === this.$topPadding || (this.$bottomItem.position().top - (averageHeight * 3)) < this.$el.outerHeight()) {
          break;
        } else {
          itemsToRemove.push(this.$bottomItem);
        }
        this.bottomItemIndex = i - 1;
        this.$bottomItem = $prevItem;
      }
      itemsToRemove.forEach(function(item) { item.remove(); });
    };

    ButterList.prototype.renderItemsBelow = function() {
      var averageHeight = this.getAverageItemHeight();
      var outerHeight = this.$el.outerHeight() + averageHeight * 3;
      if (this.bottomItemIndex + 1 === this.items.length
        || (this.$bottomItem && this.$bottomItem.position().top > outerHeight)) {
        return;
      }
      var $renderedItem = null;
      for (var i = this.bottomItemIndex + 1; i < this.items.length; i++) {
        $renderedItem = $(this.itemRenderer(this.items[i])).insertBefore(this.$bottomPadding).data('index', i);
        if (i === 0 || !this.$topItem) {
          this.$topItem = $renderedItem;
        }
        if (averageHeight === 1) {
          averageHeight = $renderedItem.height();
          outerHeight = this.$el.outerHeight() + averageHeight * 3;
        }
        this.resizePadding('bottom', -$renderedItem.outerHeight());
        this.itemHeights[i] = $renderedItem.outerHeight();
        this.$bottomItem = $renderedItem;
        if ($renderedItem.position().top > outerHeight) {
          break;
        }
      }
      this.bottomItemIndex = i;
    };

    ButterList.prototype.resizePadding = function(type, pixels) {
      var $padding = this.getPaddingFromType(type);
      $padding.height($padding.outerHeight() + pixels);
    };

    ButterList.prototype.scrollToTopOfItems = function() {
      this.ignoreScroll = true;
      this.$el.scrollTop(this.getTopPadHeight());
    };

    ButterList.prototype.fullUpdate = function() {
      this.removeItems();
      this.topItemIndex = Math.round(this.$el.percentScrolledTop() * this.items.length);
      this.bottomItemIndex = Math.round(this.$el.percentScrolledBottom() * this.items.length);
      this.renderItems();
      this.updatePaddingTop();
      this.updatePaddingBottom();
      this.scrollToTopOfItems();
    };

    ButterList.prototype.setItems = function(items) {
      this.rendered = false;
      this.items = items;
      this.$el.empty();
      this.render();
    };

    ButterList.prototype.update = function(delta) {
      if (this.ignoreScroll) {
        this.ignoreScroll = false;
        return;
      }
      // Scrolling with scrollbar
      if (Math.abs(delta) > 500) {
        this.fullUpdate();
      }
      // Scrolling down
      else if (delta < 0) {
        this.renderItemsBelow();
        this.removeItemsAbove();
        this.updatePaddingTop();
      }
      // Scrolling up
      else {
        this.renderItemsAbove();
        this.removeItemsBelow();
        this.updatePaddingBottom();
      }
    };

    ButterList.prototype.updatePaddingBottom = function() {
      this.$bottomPadding.height(this.getBottomPadHeight());
    };

    ButterList.prototype.updatePaddingTop = function() {
      this.$topPadding.height(this.getTopPadHeight());
    };

    /*** jQuery methods ***/

    $.fn.butterlist = function(options) {
      var butterlists = [];
      options = options || {};
      this.each(function() {
        var $this = $(this);
        var data = $this.data('list');
        if (!data) {
          $this.data('list', (data = new ButterList({
            el: this,
            items: options.items,
            renderer: options.renderer
          })));
        }
        butterlists.push(data);
      });
      return butterlists.length === 1 ? butterlists[0] : butterlists;
    };

    $.fn.percentScrolledTop = function() {
      var vals = [];
      this.each(function() {
        vals.push(+($(this).scrollTop() / this.scrollHeight));
      });
      return vals.length === 1 ? vals[0] : vals;
    };

    $.fn.percentScrolledBottom = function() {
      var vals = [];
      this.each(function() {
        var $this = $(this);
        vals.push(($this.scrollTop() + $this.outerHeight())  / this.scrollHeight);
      });
      return vals.length === 1 ? vals[0] : vals;
    };

    function average(array) {
      var sum = 0;
      for (var i = 0; i < array.length; i++) {
        sum += array[i];
      }
      return sum / array.length;
    }

    function isArray(obj) {
      return obj instanceof Array;
    }

}).call(this, window.jQuery);<commit_msg>JSDoc the place up.<commit_after>/**
 * @preserve
 *
 * ButterList version 0.1.0
 * http://github.com/AvocadoCorp/butterlist
 *
 * (c) 2013 Avocado Software, Inc.
 * ButterList is freely distributable under the MIT license.
 */

(function($) {

    /**
     *  @param {Object}       options
     *  @param {HTMLElement}  options.el
     *  @param {Array=}       options.items
     *  @param {Function=}    options.renderer
     */
    function ButterList(options) {
      this.$el = $(options.el);
      this.$topPadding = null;
      this.$bottomPadding = null;

      this.items = options.items || [];
      this.itemRenderer = options.renderer || null;
      this.ignoreScroll = false;

      this.rendered = false;

      this.$el.on('scroll', this.onScroll.bind(this));
      // If items were passed in, render
      if (this.items && this.items.length) {
        this.render();
      }
    };

    /**
     *  @description Add items to the end of the list
     *  @param {} item
     */
    ButterList.prototype.appendItem = function(item) {
      if (isArray(item)) {
        this.items.push.apply(this.items, item);
      } else {
        this.items.append(item);
      }
      if (this.rendered) {
        this.fullUpdate();
      }
      this.render();
    };

    /**
     *  @description Add items to the beginning of the list
     *  @param {} item
     */
    ButterList.prototype.prependItem = function(item) {
      if (isArray(item)) {
        this.items.unshift.apply(this.items, item);
      } else {
        this.items.unshift(item);
      }
      if (this.rendered) {
        this.fullUpdate();
      }
      this.render();
    };

    /**
     *  @description Bind the rendering callback to the list
     *  @param {function(): HTMLElement} renderer
     */
    ButterList.prototype.bindItemRenderer = function(renderer) {
      this.itemRenderer = renderer;
    };

    /** @return {number} **/
    ButterList.prototype.getAverageItemHeight = function() {
      if (this.averageHeight) {
        return this.averageHeight;
      }
      var heights = [];
      var iterator = 0;
      for (var key in this.itemHeights) {
        heights.push(this.itemHeights[key]);
        // Stop after 100. If this turns out terrible, make it better.
        if (++iterator === 100) {
          this.averageHeight = average(heights);
          break;
        }
      }
      return heights.length ? average(heights) : 1;
    };

    /** @return {number} **/
    ButterList.prototype.getBottomPadHeight = function() {
      var itemsBelowCount = this.items.length - this.bottomItemIndex;
      return itemsBelowCount * this.getAverageItemHeight();
    };

    /** @return {number} **/
    ButterList.prototype.getTopPadHeight = function() {
      return this.topItemIndex * this.getAverageItemHeight();
    };

    /**
     *  @param {string} type
     *  @return {number}
     */
    ButterList.prototype.getPaddingFromType = function(type) {
      return type === 'top' ? this.$topPadding : this.$bottomPadding;
    };

    /** @description Called when a 'scroll' event is triggered **/
    ButterList.prototype.onScroll = function() {
      var delta = this.prevScrollTop - this.$el.scrollTop();
      this.prevScrollTop = this.$el.scrollTop();
      this.update(delta);
    };

    /** @description Removes all visible list items **/
    ButterList.prototype.removeItems = function() {
      this.$topPadding.nextUntil('.butterlist-padding-bottom').remove();
    };

    /** @description Remove top-most items that are no longer visible **/
    ButterList.prototype.removeItemsAbove = function() {
      var itemsToRemove = [];
      for (var i = this.topItemIndex; i < this.bottomItemIndex && i < this.items.length; i++) {
        var $nextItem = this.$topItem.next();
        if ($nextItem === this.$bottomPadding || this.$topItem.position().top >= -5) {
          break;
        }
        else {
          itemsToRemove.push(this.$topItem);
        }
        this.topItemIndex = i + 1;
        this.$topItem = $nextItem;
      }
      itemsToRemove.forEach(function(item) { item.remove(); });
    };

    /** @description Initial render called to setup the list **/
    ButterList.prototype.render = function() {
      if (this.rendered) {
        return;
      }

      this.itemHeights = {};

      this.averageHeight = null;

      this.$topItem = null;
      this.$bottomItem = null;
      this.topItemIndex = 0;
      this.bottomItemIndex = -1;

      this.prevScrollTop = 0;

      this.rendered = true;
      this.$topPadding = $('

').appendTo(this.$el);
      this.$bottomPadding = $('

').appendTo(this.$el);

      this.renderItemsBelow();
      this.updatePaddingBottom();
    };

    /** @description Render all items that should be visible given the current scroll state **/
    ButterList.prototype.renderItems = function() {
      var $rendered = null;
      for (var i = this.topItemIndex; i <= this.bottomItemIndex && i < this.items.length; i++) {
        $rendered = $(this.itemRenderer(this.items[i])).insertBefore(this.$bottomPadding).data('index', i);
        if (i === this.topItemIndex) {
          this.$topItem = $rendered;
        }
      }
      this.$bottomItem = $rendered;
    };

    /**
     * @description Render visible items above the current top-most rendered item
     * TODO(Mike): This should be cleaned up
     */
    ButterList.prototype.renderItemsAbove = function() {
      if (this.topItemIndex <= 0 || this.$topItem.position().top < 0) {
        return;
      }

      var $renderedItem = null;
      for (var i = this.topItemIndex - 1; i >= 0; i--) {
        $renderedItem = $(this.itemRenderer(this.items[i])).insertAfter(this.$topPadding).data('index', i);
        this.resizePadding('top', -$renderedItem.outerHeight());
        this.itemHeights[i] = $renderedItem.outerHeight();
        this.$topItem = $renderedItem;
        if ($renderedItem.position().top < 0) {
          break;
        }
      }

      this.topItemIndex = i;
    };

    /** @description Remove bottom-most items that are no longer visible **/
    ButterList.prototype.removeItemsBelow = function() {
      var itemsToRemove = [];
      var averageHeight = this.getAverageItemHeight();
      for (var i = this.bottomItemIndex; i > this.topItemIndex && i >= 0; i--) {
        var $prevItem = this.$bottomItem.prev();
        if ($prevItem === this.$topPadding || (this.$bottomItem.position().top - (averageHeight * 3)) < this.$el.outerHeight()) {
          break;
        } else {
          itemsToRemove.push(this.$bottomItem);
        }
        this.bottomItemIndex = i - 1;
        this.$bottomItem = $prevItem;
      }
      itemsToRemove.forEach(function(item) { item.remove(); });
    };

    /**
     * @description Render visible items below the current bottom-most rendered item
     * TODO(Mike): This should be cleaned up
     */
    ButterList.prototype.renderItemsBelow = function() {
      var averageHeight = this.getAverageItemHeight();
      var outerHeight = this.$el.outerHeight() + averageHeight * 3;
      if (this.bottomItemIndex + 1 === this.items.length
        || (this.$bottomItem && this.$bottomItem.position().top > outerHeight)) {
        return;
      }
      var $renderedItem = null;
      for (var i = this.bottomItemIndex + 1; i < this.items.length; i++) {
        $renderedItem = $(this.itemRenderer(this.items[i])).insertBefore(this.$bottomPadding).data('index', i);
        if (i === 0 || !this.$topItem) {
          this.$topItem = $renderedItem;
        }
        if (averageHeight === 1) {
          averageHeight = $renderedItem.height();
          outerHeight = this.$el.outerHeight() + averageHeight * 3;
        }
        this.resizePadding('bottom', -$renderedItem.outerHeight());
        this.itemHeights[i] = $renderedItem.outerHeight();
        this.$bottomItem = $renderedItem;
        if ($renderedItem.position().top > outerHeight) {
          break;
        }
      }
      this.bottomItemIndex = i;
    };

    /**
     *  @description Set the size of the top/bottom padding of the list
     *    Padding in this context is a div sized so that the scroll bar is
     *    rendered in the proper location.
     *  @param {string} type
     *  @param {number} pixels
     */
    ButterList.prototype.resizePadding = function(type, pixels) {
      var $padding = this.getPaddingFromType(type);
      $padding.height($padding.outerHeight() + pixels);
    };

    /** @description Scroll to top of the list **/
    ButterList.prototype.scrollToTopOfItems = function() {
      this.ignoreScroll = true;
      this.$el.scrollTop(this.getTopPadHeight());
    };

    /** @description Clear the rendered items, calculate our location, and rerender items.
     *    Useful when we want to do quick jumps on the list.
     */
    ButterList.prototype.fullUpdate = function() {
      this.removeItems();
      this.topItemIndex = Math.round(this.$el.percentScrolledTop() * this.items.length);
      this.bottomItemIndex = Math.round(this.$el.percentScrolledBottom() * this.items.length);
      this.renderItems();
      this.updatePaddingTop();
      this.updatePaddingBottom();
      this.scrollToTopOfItems();
    };

    /**
     *  @description Set the items for the list and renders everything.
     *  @param {Array} items
     */
    ButterList.prototype.setItems = function(items) {
      this.rendered = false;
      this.items = items;
      this.$el.empty();
      this.render();
    };

    /**
     *  @description Take a scroll delta and call the proper rendering function
     *  @param {number} delta
     */
    ButterList.prototype.update = function(delta) {
      if (this.ignoreScroll) {
        this.ignoreScroll = false;
        return;
      }
      // Scrolling with scrollbar
      if (Math.abs(delta) > 500) {
        this.fullUpdate();
      }
      // Scrolling down
      else if (delta < 0) {
        this.renderItemsBelow();
        this.removeItemsAbove();
        this.updatePaddingTop();
      }
      // Scrolling up
      else {
        this.renderItemsAbove();
        this.removeItemsBelow();
        this.updatePaddingBottom();
      }
    };

    ButterList.prototype.updatePaddingBottom = function() {
      this.$bottomPadding.height(this.getBottomPadHeight());
    };

    ButterList.prototype.updatePaddingTop = function() {
      this.$topPadding.height(this.getTopPadHeight());
    };

    /*** jQuery methods ***/

    /**
     *  @param {Object} options
     */
    $.fn.butterlist = function(options) {
      var butterlists = [];
      options = options || {};
      this.each(function() {
        var $this = $(this);
        var data = $this.data('list');
        if (!data) {
          $this.data('list', (data = new ButterList({
            el: this,
            items: options.items,
            renderer: options.renderer
          })));
        }
        butterlists.push(data);
      });
      return butterlists.length === 1 ? butterlists[0] : butterlists;
    };

    /** @return {Array.<number>|number} **/
    $.fn.percentScrolledTop = function() {
      var vals = [];
      this.each(function() {
        vals.push(+($(this).scrollTop() / this.scrollHeight));
      });
      return vals.length === 1 ? vals[0] : vals;
    };

    /** @return {Array.<number>|number} **/
    $.fn.percentScrolledBottom = function() {
      var vals = [];
      this.each(function() {
        var $this = $(this);
        vals.push(($this.scrollTop() + $this.outerHeight())  / this.scrollHeight);
      });
      return vals.length === 1 ? vals[0] : vals;
    };

    /**
     *  @param {Array.<number>} array
     *  @return {number}
     */
    function average(array) {
      var sum = 0;
      for (var i = 0; i < array.length; i++) {
        sum += array[i];
      }
      return sum / array.length;
    }

    /**
     *  @param {Object} obj
     *  @return {bool}
     */
    function isArray(obj) {
      return obj instanceof Array;
    }

}).call(this, window.jQuery);<|endoftext|>


<commit_before>class Colours {
  /**
   * Converts the second to a hex value, from 0x000000 to 0xFFFFFF.
   * 00:00:00 corresponds to #000000 and 23:59:59 corresponds to #ffffff.
   *
   * @param {Number} seconds  The current second in the day.
   *
   * @return {String}  The hex colour value (e.g. #1fd531).
   */
  static secondToHexColour (seconds) {
    return `#${('00000' + (seconds / (24 * 60 * 60 - 1) * 0xFFFFFF | 0).toString(16)).slice(-6)}`;
  }

  /**
   * Converts the second to a hex value, as a point along the hue spectrum.
   * 00:00:00 corresponds to #FF0000, 12:00:00 corresponds to #00FEFF.
   */
  static secondToHueColour (seconds) {
    var hue = seconds / (24 * 60 * 60);

    return Colours.rgbToHex(...Colours.hslToRgb(hue, 1, 0.5));
  }

  /**
   * Converts an HSL color value to RGB. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes h, s, and l are contained in the set [0, 1] and
   * returns r, g, and b in the set [0, 255].
   *
   * @param {Number} h  The hue.
   * @param {Number} s  The saturation.
   * @param {Number} l  The lightness.
   *
   * @return {Array}  The RGB representation.
   */
  static hslToRgb (h, s, l) {
    var r, g, b;

    if (s === 0){
      r = g = b = l;  // Achromatic
    } else {
      var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      var p = 2 * l - q;
      r = Colours.hueToRgb(p, q, h + 1/3);
      g = Colours.hueToRgb(p, q, h);
      b = Colours.hueToRgb(p, q, h - 1/3);
    }

    return [r * 255, g * 255, b * 255];
  }

  /**
   * Converts a hue color value to RGB.
   */
  static hueToRgb (p, q, t) {
    if (t < 0) t++;
    if (t > 1) t--;
    if (t < 1/6) return p + (q - p) * 6 * t;
    if (t < 1/2) return q;
    if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;

    return p;
  }

  /**
   * Converts RGB values to a hex colour string.
   */
  static rgbToHex (r, g, b) {
    return `#${(((1 << 24) + (r << 16) + (g << 8) + b) | 0).toString(16).slice(1)}`;
  }

  /**
   * Converts a hex colour string to an array of RGB values.
   */
  static hexToRgb (hex) {
    var r = parseInt(hex, 16) >> 16,
      g = parseInt(hex, 16) >> 8 & 0xFF,
      b = parseInt(hex, 16) & 0xFF;

    return [r, g, b];
  }

  /**
   * Converts a hex colour to an RGBA string with the provided alpha value.
   */
  static rgba (hex, a) {
    var colour = Colours.hexToRgb(hex.substring(1, 7));

    return `rgba(${colour[0]}, ${colour[1]}, ${colour[2]}, ${a})`;
  }

  /**
   * Returns a random hex colour string.
   */
  static random () {
    return `#${('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6)}`;
  }
}

export default Colours;
<commit_msg>Refactor common colour logic<commit_after>class Colours {
  /**
   * Converts the second to a hex value, from 0x000000 to 0xFFFFFF.
   * 00:00:00 corresponds to #000000 and 23:59:59 corresponds to #ffffff.
   *
   * @param {Number} seconds  The current second in the day.
   *
   * @return {String}  The hex colour value (e.g. #1fd531).
   */
  static secondToHexColour (seconds) {
    return Colours._valueToHex(seconds / (24 * 60 * 60 - 1));
  }

  /**
   * Converts the second to a hex value, as a point along the hue spectrum.
   * 00:00:00 corresponds to #FF0000, 12:00:00 corresponds to #00FEFF.
   */
  static secondToHueColour (seconds) {
    var hue = seconds / (24 * 60 * 60);

    return Colours.rgbToHex(...Colours.hslToRgb(hue, 1, 0.5));
  }

  /**
   * Converts an HSL color value to RGB. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes h, s, and l are contained in the set [0, 1] and
   * returns r, g, and b in the set [0, 255].
   *
   * @param {Number} h  The hue.
   * @param {Number} s  The saturation.
   * @param {Number} l  The lightness.
   *
   * @return {Array}  The RGB representation.
   */
  static hslToRgb (h, s, l) {
    var r, g, b;

    if (s === 0){
      r = g = b = l;  // Achromatic
    } else {
      var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      var p = 2 * l - q;
      r = Colours.hueToRgb(p, q, h + 1/3);
      g = Colours.hueToRgb(p, q, h);
      b = Colours.hueToRgb(p, q, h - 1/3);
    }

    return [r * 255, g * 255, b * 255];
  }

  /**
   * Converts a hue color value to RGB.
   */
  static hueToRgb (p, q, t) {
    if (t < 0) t++;
    if (t > 1) t--;
    if (t < 1/6) return p + (q - p) * 6 * t;
    if (t < 1/2) return q;
    if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;

    return p;
  }

  /**
   * Converts RGB values to a hex colour string.
   */
  static rgbToHex (r, g, b) {
    return `#${(((1 << 24) + (r << 16) + (g << 8) + b) | 0).toString(16).slice(1)}`;
  }

  /**
   * Converts a hex colour string to an array of RGB values.
   */
  static hexToRgb (hex) {
    var r = parseInt(hex, 16) >> 16,
      g = parseInt(hex, 16) >> 8 & 0xFF,
      b = parseInt(hex, 16) & 0xFF;

    return [r, g, b];
  }

  /**
   * Converts a hex colour to an RGBA string with the provided alpha value.
   */
  static rgba (hex, alpha) {
    var colour = Colours.hexToRgb(hex.substring(1, 7));

    return `rgba(${colour[0]}, ${colour[1]}, ${colour[2]}, ${alpha})`;
  }

  /**
   * Returns a random hex colour string.
   */
  static random () {
    return Colours._valueToHex(Math.random());
  }

  /**
   * PRIVATE: returns a hex colour string using the given number.
   */
  static _valueToHex (value) {
    return `#${('000000' + (value * 0xFFFFFF | 0).toString(16)).slice(-6)}`;
  }
}

export default Colours;
<|endoftext|>


<commit_before>'use strict';
/*jshint -W069 */
var oauthToken;
chrome.storage.sync.get({
    oauthToken: ''
}, function(items) {
    oauthToken = items.oauthToken;
    check();
});

document.addEventListener('DOMNodeInserted', nodeInsertedCallback);

const log = (message) => console.log(`[Follow for GitHub] ${message}`);

var timeout;
function nodeInsertedCallback(event) {
	var id = $(event.relatedNode).attr('id');
	if (id === 'js-repo-pjax-container') {
		if (timeout){
			clearTimeout(timeout);
		}
    	timeout = setTimeout(check, 200);
	}
}

function check() {
	var split = $('title').text().split(' - ');
	var ownerRepo = split[1];
	var fileName = split[0].replace('History for ', '');
	var sha = $('clipboard-copy').last().attr('value');
	findMove(sha, fileName, ownerRepo);
}

function findMove(sha, fileName, ownerRepo) {
	var url = 'https://api.github.com/repos/:owner/:repo/commits/:sha'.replace(':sha', sha).replace(':owner/:repo', ownerRepo);
	get(url).done(function(data) {
		var file = findFile(data.files, fileName);
		log(`${fileName} was ${file.status}`);
		if (file.status === 'renamed') {
			var previousFileName = file['previous_filename'];
			var parentSha = data.parents[0].sha;
			follow(parentSha, previousFileName, ownerRepo);
		}
	});
}

function follow(sha, fileName, ownerRepo) {
	var url = 'https://api.github.com/repos/:owner/:repo/commits?sha=:sha&path=:path'
		.replace(':owner/:repo', ownerRepo)
		.replace(':sha', sha)
		.replace(':path', fileName);

	get(url).done(function(data) {
		var fileSha = data[0].sha;
		var link = '/:owner/:repo/commits/:sha/:fileName'
			.replace(':owner/:repo', ownerRepo)
			.replace(':sha', fileSha)
			.replace(':fileName', fileName);

		// var iconUrl = chrome.extension.getURL('images/icon-16.png');
		// var style = ''
		// 	.replace(':iconUrl', iconUrl);

		var template = ['
'
				,'Renamed to :fileName Follow
'
			].join('')
			.replace(':fileName', fileName)
			.replace(':link', link);

		$('.commits-listing').append(template);
	});
}

function get(url) {

	var headers = {
	        'Accept':'application/vnd.github.v3+json'
	};

	if (oauthToken) {
		headers['Authorization'] = 'token ' + oauthToken;
	}

    return $.ajax({
	    type: 'GET',
	    url: url,
	    headers: headers
	});
}

function findFile(files, fileName) {
    for (var i = 0, len = files.length; i < len; i++) {
        if (files[i].filename === fileName) {
            return files[i];
        }
    }
    return null;
}<commit_msg>fix follow button<commit_after>'use strict';
/*jshint -W069 */
var oauthToken;
chrome.storage.sync.get({
    oauthToken: ''
}, function(items) {
    oauthToken = items.oauthToken;
    check();
});

document.addEventListener('DOMNodeInserted', nodeInsertedCallback);

const log = (message) => console.log(`[Follow for GitHub] ${message}`);

var timeout;
function nodeInsertedCallback(event) {
	var id = $(event.relatedNode).attr('id');
	if (id === 'js-repo-pjax-container') {
		if (timeout){
			clearTimeout(timeout);
		}
    	timeout = setTimeout(check, 200);
	}
}

function check() {
	var split = $('title').text().split(' - ');
	var ownerRepo = split[1];
	var fileName = split[0].replace('History for ', '');
	var sha = $('clipboard-copy').last().attr('value');
	findMove(sha, fileName, ownerRepo);
}

function findMove(sha, fileName, ownerRepo) {
	var url = 'https://api.github.com/repos/:owner/:repo/commits/:sha'.replace(':sha', sha).replace(':owner/:repo', ownerRepo);
	get(url).done(function(data) {
		var file = findFile(data.files, fileName);
		log(`${fileName} was ${file.status}`);
		if (file.status === 'renamed') {
			var previousFileName = file['previous_filename'];
			var parentSha = data.parents[0].sha;
			follow(parentSha, previousFileName, ownerRepo);
		}
	});
}

function follow(sha, fileName, ownerRepo) {
	var url = 'https://api.github.com/repos/:owner/:repo/commits?sha=:sha&path=:path'
		.replace(':owner/:repo', ownerRepo)
		.replace(':sha', sha)
		.replace(':path', fileName);

	get(url).done(function(data) {
		var fileSha = data[0].sha;
		var link = '/:owner/:repo/commits/:sha/:fileName'
			.replace(':owner/:repo', ownerRepo)
			.replace(':sha', fileSha)
			.replace(':fileName', fileName);

		// var iconUrl = chrome.extension.getURL('images/icon-16.png');
		// var style = ''
		// 	.replace(':iconUrl', iconUrl);

		// Drive File Move from Material Design - https://fonts.google.com/icons?icon.query=move
		const moveIcon = 'M20,6h-8l-2-2H4C2.9,4,2,4.9,2,6v12c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V8C22,6.9,21.1,6,20,6z M20,18H4V6h5.17l1.41,1.41 L11.17,8H20V18z M12.16,12H8v2h4.16l-1.59,1.59L11.99,17L16,13.01L11.99,9l-1.41,1.41L12.16,12z';

		var template = [
			'
',
			'
',
            `<svg class="octicon octicon-git-commit" style="margin-left: -20px;margin-top: -25px;" height="2" viewBox="0 0 2 2" version="1.1" width="2" aria-hidden="true"><path fill-rule="evenodd" d="${moveIcon}"></path></svg>`,
          	'
',
			'
',
			'
',
			'Renamed to :fileName',
			'Follow',
			'
',
			'
',
			'
'
			].join('')
			.replace(':fileName', fileName)
			.replace(':link', link);

		$('.js-navigation-container.mt-3').append(template);
	});
}

function get(url) {

	var headers = {
	        'Accept':'application/vnd.github.v3+json'
	};

	if (oauthToken) {
		headers['Authorization'] = 'token ' + oauthToken;
	}

    return $.ajax({
	    type: 'GET',
	    url: url,
	    headers: headers
	});
}

function findFile(files, fileName) {
    for (var i = 0, len = files.length; i < len; i++) {
        if (files[i].filename === fileName) {
            return files[i];
        }
    }
    return null;
}<|endoftext|>


<commit_before>var ficsClient = angular.module("ficsClient", [
  "ngCookies",
  "ui.bootstrap.buttons",
  "ui.bootstrap.dropdown",
  "ui.bootstrap.pagination",
  "ui.bootstrap.tabs",
  "ui.keypress",
  "ui.scroll",
  "luegg.directives"
]);

ficsClient.run(["$rootScope", "TabManager", "User", function($rootScope, TabManager, User) {
  TabManager.attach();

  $rootScope.$watch(User.getUsername, function(username) {
    $rootScope.isLoggedIn = angular.isDefined(username);

    TabManager.watchLogin();
  }, true);

  $rootScope.$watch(User.isGuest, function(isGuest) {
    $rootScope.isGuest = isGuest;
  });
}]);
<commit_msg>fix call to undefined method<commit_after>var ficsClient = angular.module("ficsClient", [
  "ngCookies",
  "ui.bootstrap.buttons",
  "ui.bootstrap.dropdown",
  "ui.bootstrap.pagination",
  "ui.bootstrap.tabs",
  "ui.keypress",
  "ui.scroll",
  "luegg.directives"
]);

// only include play as a dependency temporarily to make it register its messages
ficsClient.run(["$rootScope", "TabManager", "User", "Play", function($rootScope, TabManager, User) {
  TabManager.attach();

  $rootScope.$watch(User.getUsername, function(username) {
    $rootScope.isLoggedIn = angular.isDefined(username);

    TabManager.watchLogin();
  }, true);

  $rootScope.$watch(User.isGuest, function(isGuest) {
    $rootScope.isGuest = isGuest;
  });
}]);
<|endoftext|>


<commit_before>import moment from 'moment';
import getServerList from './../../utils/getServerList';

function getInitialState() {
  return {
    time: undefined,
    servers: getServerList().map(server => Object.assign(server, {state: 'loading', delay: 0}))
  };
}

export default function serverReducer(state = getInitialState(), action) {
  switch (action.type) {
    case "server.current.time":
      return setCurrentTime(state);
    case "server.online":
      return modifyServerState(state, action, 'online');
    case "server.offline":
      return modifyServerState(state, action, 'offline');
    default:
      return state;
  }
}

function setCurrentTime(state) {
  return {
    ...state,
    time: moment().unix()
  };
}

function modifyServerState(state, {server, responseTime}, newStateValue) {
  return {
    ...state,
    servers: state.servers.map(server => {
      if (server.name === server.name) {
        server.state = newStateValue;
        server.delay = moment().unix() - state.time;
      }
      return server;
    })
  };
}
<commit_msg>Fix a bug in the reducer<commit_after>import moment from 'moment';
import getServerList from './../../utils/getServerList';

function getInitialState() {
  return {
    time: undefined,
    servers: getServerList().map(server => Object.assign(server, {state: 'loading', delay: 0}))
  };
}

export default function serverReducer(state = getInitialState(), action) {
  switch (action.type) {
    case "server.current.time":
      return setCurrentTime(state);
    case "server.online":
      return modifyServerState(state, action, 'online');
    case "server.offline":
      return modifyServerState(state, action, 'offline');
    default:
      return state;
  }
}

function setCurrentTime(state) {
  return {
    ...state,
    time: moment().unix()
  };
}

function modifyServerState(state, {server, responseTime}, newStateValue) {
  return {
    ...state,
    servers: state.servers.map(stateServer => {
      if (server.name === stateServer.name) {
        return {
          ...stateServer,
          state: newStateValue,
          delay: moment().unix() - state.time
        };
      }
      return stateServer;
    })
  };
}
<|endoftext|>


<commit_before>/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global Backbone, angular, jQuery, _, console */

/*
  This is the entity manager class which consists of utility functions
  to simplify the cross-app discussion of certin entities
*/

(function() {
	angular
		.module('indx')
		.factory('entities', function(client, utils) {
			var u = utils;

			var to_obj = function(box, obj) {
				var d = u.deferred();
				if (obj instanceof client.Obj) { return u.dresolve(obj); }
				if (!_.isObject(obj)) { return u.dresolve(obj); }
				var uid = obj['@id'] || obj.id || u.guid();

				box.getObj(uid).then(function(model) {
					var ds = _(obj).map(function(v,k) {
						var dk = u.deferred();
						if (_(v).isObject(v) && !(v instanceof client.Obj)) {
							to_obj(box,v).then(function(vobj) {
								model.set(k,vobj);
								dk.resolve();
							}).fail(function() {
								dk.reject();
							});
						} else {
							model.set(k,v);
							dk.resolve();
						}
						return dk.promise();
					});
					u.when(ds).then(function() { d.resolve(model); }).fail(function() { d.reject('error setting properties'); });
				});
				return d.promise();
			};

			var toQueryTime = function(date) {
				return date.toISOString().slice(0,-5);	// chop off the .000Z or queries don't like it
			};

			var slowQuery = function(box, properties) {
				var d = u.deferred(), results = [];
				box.getObj(box.getObjIDs()).then(function(objs) {
					window._objs = objs;
					var hits = objs.filter(function(obj) {
						var results = _(properties).map(function(v,k) {
							console.info(obj.id, '.peek(',k,') => ', obj.peek(k), obj.attributes && obj.attributes[k], obj.attributes, ' == ', v);
							return obj && (obj.peek(k) == v || (obj.get(k) && (obj.get(k).indexOf(v) >= 0)));
						});
						return results.reduce(function(x,y) { return x && y; }, true);
					});
					d.resolve(hits);
				}).fail(d.reject);
				return d.promise();
			};

			var search = function(box, properties) {
				// query is broken :( so going to manually rig it.
				//return slowQuery(box,properties);
				return box.query(properties);
			};

			var LATLNG_THRESH = 0.05;

			return {
				toObj:to_obj,
				locations: {
					getAll: function(box, extras) {
						return search(box, _(extras || {}).chain().clone().extend({'type':'location'}).value());
					},
					getByLatLng: function(box, lat, lng) {
						var d = u.deferred();
						this.getAll(box).then(function(results) {
							var dist = {}, resD = {};
							results.map(function(result) {
								if (!(result.peek('latitude') && result.peek('longitude') )) { return; }
								dist[result.id] = Math.sqrt(Math.pow(result.peek('latitude') - lat,2) + Math.pow(result.peek('longitude') - lng, 2));
								resD[result.id] = result;
							});
							var kbyD = _(dist).keys();
							kbyD.sort(function(a,b) { return dist[a] - dist[b]; });
							// console.log('kbyD > ', kbyD);
							var hits = kbyD.filter(function(k) { return dist[k] < LATLNG_THRESH; }).map(function(k) { return resD[k]; });
							// console.info('hits >> ', hits);
							d.resolve(hits);
						});
						return d.promise();
					},
					getByMovesID: function(box, movesid) {
						return this.getAll(box, { moves_id: movesid });
					},
					getByName:function(box, name) {
						return this.getAll(box, { name: name });
					},
					make:function(box, name, location_type, latitude, longitude, moves_id, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'location_type', 'latitude', 'longitude', 'moves_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						var id = 'location-'+u.guid(); // ['location', name || '', location_type && location_type !== 'unknown' ? location_type : '' , moves_id ? moves_id : '', latitude.toString(), longitude.toString() ].join('-');
						box.getObj(id).then(function(model) {
							model.set(argset);
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.set({'type':'location'});
							console.log('SAVING LOCATION >>>>>>>>>>>>>>> ', model);
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				activities:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Activity'}));
					},
					getByActivityType:function(box, tstart, tend, activity_types) {
						if (!_.isArray(activity_types)) { activity_types=[activity_types]; };
						var query = ({
							'$and':[ {type:'Activity'},	{'$or': activity_types.map(function(atype) { return {'activity': atype}; })} ]
						});
						if (tstart) { query.$and.push({'tstart': {'$ge': toQueryTime(tstart) }}); }
						if (tend) { query.$and.push({'tend': {'$lt': toQueryTime(tend)}}); }
						console.log('issuing query ... ', JSON.stringify(query));
						return search(box, query);
					},
					getByTimeseriesPointsPerMinute:function(box, ts, tstart, tend) {
						// ts in {'fitbit_steps_ts', 'fitbit_calories_ts', 'fitbit_distance_ts', 'fitbit_floors_ts', 'fitbit_elevation_ts', 'nikeplus_steps_ts', 'nikeplus_calories_ts', 'nikeplus_fuel_ts', 'nikeplus_stars_ts'}
						if (ts && tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':ts},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return u.dreject('must specify all arguments: ts, tstart, tend');
					},
					getFitbitStepsPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'fitbit_steps_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return u.dreject('must specify all arguments: ts, tstart, tend');
					},
					getFitbitCaloriesPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'fitbit_calories_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					getFitbitDistancePerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'fitbit_distance_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					getFitbitFloorsPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'fitbit_floors_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					getFitbitElevationPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'fitbit_elevation_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					getNikeStepsPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'nikeplus_steps_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					getNikeCaloriesPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'nikeplus_calories_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					getNikeFuelPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'nikeplus_fuel_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					getNikeStarsPerMin:function(box, tstart, tend) {
						if (tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':'nikeplus_stars_ts'},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return [];
					},
					make1:function(box, activity_type, whom, from_t, to_t, distance, steps, calories, waypoints, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var id = ['activity', whom && whom.id || '', activity_type || '', from_t.valueOf().toString(), to_t.valueOf().toString()].join('-');
						var argnames = [undefined, 'activity', 'whom', 'tstart', 'tend', 'distance', 'steps', 'calories', 'waypoints'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'activity'});
							model.set(otherprops);
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				people:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Person'}));
					},
					getByName:function(box, name) {
						var d = u.deferred();
						u.when(this.getAll(box, { names: [name] }), this.getAll(box, {name:name})).then(function(x,y) {
							var results = _.uniq( ([] || x).concat(y) );
							d.resolve(results);
						}).fail(d.reject);
						return d.promise();
					},
					getByGivenName:function(box, name) { return this.getAll(box, { given_name:[name] }); },
					getBySurname:function(box, name) { return this.getAll(box, { surname:[name] }); },
					getByTwitter:function(box, name) { return this.getAll(box, { twitter_id:[name] }); },
					getByEmail:function(box, name) { return this.getAll(box, { email:[name] }); },
					make:function(box, id, givenname, surname, other_names, emails, twitter, facebook_url, linkedin_url, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'given_name', 'surname', 'name', 'email', 'twitter_id', 'facebook_id', 'linkedin_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'person'});
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				documents:{
					getWebPage:function(box, url) {
						return search(box, url ? { url: url, type:'web-page' } : { type: 'web-page' });
					},
					makeWebPage:function(box, url, title, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var id = url;
						var argnames = [undefined, 'url', 'title'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'web-page'});
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					},
					getTweet:undefined,
					getInstagram:undefined,
					getFBMessage:undefined,
					getFBWallPost:undefined,
				},
				sensors:{
					getByName:undefined,
					getByActivity:undefined,
					make:undefined
				}
			};
		});
})();<commit_msg>timeseries queries<commit_after>/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global Backbone, angular, jQuery, _, console */

/*
  This is the entity manager class which consists of utility functions
  to simplify the cross-app discussion of certin entities
*/

(function() {
	angular
		.module('indx')
		.factory('entities', function(client, utils) {
			var u = utils;

			var to_obj = function(box, obj) {
				var d = u.deferred();
				if (obj instanceof client.Obj) { return u.dresolve(obj); }
				if (!_.isObject(obj)) { return u.dresolve(obj); }
				var uid = obj['@id'] || obj.id || u.guid();

				box.getObj(uid).then(function(model) {
					var ds = _(obj).map(function(v,k) {
						var dk = u.deferred();
						if (_(v).isObject(v) && !(v instanceof client.Obj)) {
							to_obj(box,v).then(function(vobj) {
								model.set(k,vobj);
								dk.resolve();
							}).fail(function() {
								dk.reject();
							});
						} else {
							model.set(k,v);
							dk.resolve();
						}
						return dk.promise();
					});
					u.when(ds).then(function() { d.resolve(model); }).fail(function() { d.reject('error setting properties'); });
				});
				return d.promise();
			};

			var toQueryTime = function(date) {
				return date.toISOString().slice(0,-5);	// chop off the .000Z or queries don't like it
			};

			var slowQuery = function(box, properties) {
				var d = u.deferred(), results = [];
				box.getObj(box.getObjIDs()).then(function(objs) {
					window._objs = objs;
					var hits = objs.filter(function(obj) {
						var results = _(properties).map(function(v,k) {
							console.info(obj.id, '.peek(',k,') => ', obj.peek(k), obj.attributes && obj.attributes[k], obj.attributes, ' == ', v);
							return obj && (obj.peek(k) == v || (obj.get(k) && (obj.get(k).indexOf(v) >= 0)));
						});
						return results.reduce(function(x,y) { return x && y; }, true);
					});
					d.resolve(hits);
				}).fail(d.reject);
				return d.promise();
			};

			var search = function(box, properties) {
				// query is broken :( so going to manually rig it.
				//return slowQuery(box,properties);
				return box.query(properties);
			};

			var LATLNG_THRESH = 0.05;

			return {
				toObj:to_obj,
				locations: {
					getAll: function(box, extras) {
						return search(box, _(extras || {}).chain().clone().extend({'type':'location'}).value());
					},
					getByLatLng: function(box, lat, lng) {
						var d = u.deferred();
						this.getAll(box).then(function(results) {
							var dist = {}, resD = {};
							results.map(function(result) {
								if (!(result.peek('latitude') && result.peek('longitude') )) { return; }
								dist[result.id] = Math.sqrt(Math.pow(result.peek('latitude') - lat,2) + Math.pow(result.peek('longitude') - lng, 2));
								resD[result.id] = result;
							});
							var kbyD = _(dist).keys();
							kbyD.sort(function(a,b) { return dist[a] - dist[b]; });
							// console.log('kbyD > ', kbyD);
							var hits = kbyD.filter(function(k) { return dist[k] < LATLNG_THRESH; }).map(function(k) { return resD[k]; });
							// console.info('hits >> ', hits);
							d.resolve(hits);
						});
						return d.promise();
					},
					getByMovesID: function(box, movesid) {
						return this.getAll(box, { moves_id: movesid });
					},
					getByName:function(box, name) {
						return this.getAll(box, { name: name });
					},
					make:function(box, name, location_type, latitude, longitude, moves_id, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'location_type', 'latitude', 'longitude', 'moves_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						var id = 'location-'+u.guid(); // ['location', name || '', location_type && location_type !== 'unknown' ? location_type : '' , moves_id ? moves_id : '', latitude.toString(), longitude.toString() ].join('-');
						box.getObj(id).then(function(model) {
							model.set(argset);
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.set({'type':'location'});
							console.log('SAVING LOCATION >>>>>>>>>>>>>>> ', model);
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				activities:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Activity'}));
					},
					getByActivityType:function(box, tstart, tend, activity_types) {
						if (!_.isArray(activity_types)) { activity_types=[activity_types]; };
						var query = ({
							'$and':[ {type:'Activity'},	{'$or': activity_types.map(function(atype) { return {'activity': atype}; })} ]
						});
						if (tstart) { query.$and.push({'tstart': {'$ge': toQueryTime(tstart) }}); }
						if (tend) { query.$and.push({'tend': {'$lt': toQueryTime(tend)}}); }
						console.log('issuing query ... ', JSON.stringify(query));
						return search(box, query);
					},
					getByTimeseriesPointsPerMinute:function(box, ts, tstart, tend) {
						// ts in {'fitbit_steps_ts', 'fitbit_calories_ts', 'fitbit_distance_ts', 'fitbit_floors_ts', 'fitbit_elevation_ts', 'nikeplus_steps_ts', 'nikeplus_calories_ts', 'nikeplus_fuel_ts', 'nikeplus_stars_ts'}
						if (ts && tstart && tend) {
							var query = ( {'$and': [
									{'timeseries':ts},
									{'tstart':{'$ge':toQueryTime(tstart)} },
									{'tend':{'$le':toQueryTime(tend)} }
								] } );
							console.log('issuing query ... ', JSON.stringify(query));
							return search(box, query);
						}
						return u.dreject('must specify all arguments: ts, tstart, tend');
					},
					getFitbitStepsPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'fitbit_steps_ts', tstart, tend);
					},
					getFitbitCaloriesPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'fitbit_calories_ts', tstart, tend);
					},
					getFitbitDistancePerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'fitbit_distance_ts', tstart, tend);
					},
					getFitbitFloorsPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'fitbit_floors_ts', tstart, tend);
					},
					getFitbitElevationPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'fitbit_elevation_ts', tstart, tend);					},
					getNikeStepsPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'nikeplus_steps_ts', tstart, tend);
					},
					getNikeCaloriesPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'nikeplus_calories_ts', tstart, tend);
					},
					getNikeFuelPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'nikeplus_fuel_ts', tstart, tend);
					},
					getNikeStarsPerMin:function(box, tstart, tend) {
						return getByTimeseriesPointsPerMinute(box, 'nikeplus_stars_ts', tstart, tend);
					},
					make1:function(box, activity_type, whom, from_t, to_t, distance, steps, calories, waypoints, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var id = ['activity', whom && whom.id || '', activity_type || '', from_t.valueOf().toString(), to_t.valueOf().toString()].join('-');
						var argnames = [undefined, 'activity', 'whom', 'tstart', 'tend', 'distance', 'steps', 'calories', 'waypoints'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'activity'});
							model.set(otherprops);
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				people:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Person'}));
					},
					getByName:function(box, name) {
						var d = u.deferred();
						u.when(this.getAll(box, { names: [name] }), this.getAll(box, {name:name})).then(function(x,y) {
							var results = _.uniq( ([] || x).concat(y) );
							d.resolve(results);
						}).fail(d.reject);
						return d.promise();
					},
					getByGivenName:function(box, name) { return this.getAll(box, { given_name:[name] }); },
					getBySurname:function(box, name) { return this.getAll(box, { surname:[name] }); },
					getByTwitter:function(box, name) { return this.getAll(box, { twitter_id:[name] }); },
					getByEmail:function(box, name) { return this.getAll(box, { email:[name] }); },
					make:function(box, id, givenname, surname, other_names, emails, twitter, facebook_url, linkedin_url, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'given_name', 'surname', 'name', 'email', 'twitter_id', 'facebook_id', 'linkedin_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'person'});
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				documents:{
					getWebPage:function(box, url) {
						return search(box, url ? { url: url, type:'web-page' } : { type: 'web-page' });
					},
					makeWebPage:function(box, url, title, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var id = url;
						var argnames = [undefined, 'url', 'title'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'web-page'});
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					},
					getTweet:undefined,
					getInstagram:undefined,
					getFBMessage:undefined,
					getFBWallPost:undefined,
				},
				sensors:{
					getByName:undefined,
					getByActivity:undefined,
					make:undefined
				}
			};
		});
})();<|endoftext|>


<commit_before>/****************************************************************************
 Copyright (c) 2008-2010 Ricardo Quesada
 Copyright (c) 2011-2012 cocos2d-x.org
 Copyright (c) 2013-2014 Chukong Technologies Inc.

 http://www.cocos2d-x.org

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

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

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

var LINE_SPACE = 40;
var ITEM_TAG_BASIC = 1000;

var TEST_NOTIFICATIONCENTER = 0;
var TEST_CCCONTROLBUTTON = 1;
var TEST_COCOSBUILDER = 2;
var TEST_HTTPCLIENT = 3;

var extensionsTestItemNames = [
    /*    {
     itemTitle:"NotificationCenterTest",
     testScene:function () {
     //runNotificationCenterTest();
     cc.log("not implement");
     }
     },*/
    {
        itemTitle:"CCControlButtonTest",
        testScene:function () {
            var pManager = ControlSceneManager.getInstance();
            var pScene = pManager.currentControlScene();
	        cc.director.runScene(pScene);
        }
    },
    {
        itemTitle:"CocosBuilderTest",
        testScene:function () {
            var pScene = new CocosBuilderTestScene();
            if (pScene) {
                pScene.runThisTest();
            }
        }
    },
    /*    {
     itemTitle:"HttpClientTest",
     testScene:function () {
     //runHttpClientTest();
     cc.log("not implement");
     }
     },*/
    {
        itemTitle:"TableViewTest",
        testScene:function () {
            runTableViewTest();
        }
    },
    {
        itemTitle:"EditBoxTest",
        testScene:function () {
            runEditBoxTest();
        }
    },
    {
        itemTitle:"WebSocketTest",
        testScene:function () {
            runWebSocketTest();
        }
    },
    {
        itemTitle:"SocketIOTest",
        testScene:function () {
            runSocketIOTest();
        }
    },
    {
        itemTitle:"CCPoolTest",
        testScene:function () {
            runCCPoolTest();
        }
    },
    {
        itemTitle:"PluginTest",
        testScene:function () {
            if(cc.sys.isNative){
                var testScene = pluginXSceneManager.currentPluginXScene();
                cc.director.runScene(testScene);
            }else{
                cc.loader.loadJs('', [
                    "../../frameworks/cocos2d-html5/external/pluginx/platform/facebook.js",
                    "../../frameworks/cocos2d-html5/external/pluginx/platform/facebook_sdk.js"
                ], function(){
                    var testScene = pluginXSceneManager.currentPluginXScene();
                    if (testScene) {
                        cc.director.runScene(testScene);
                    }
                });
            }
        }
    }
];
if (cc.sys.isNative) {
    extensionsTestItemNames.push({
        itemTitle:"AssetsManagerTest",
        testScene:function () {
            var testScene = new AssetsManagerLoaderScene();
            if (testScene) {
                testScene.runThisTest();
            }
        }
    });
}

var ExtensionsMainLayer = cc.Layer.extend({
    onEnter:function () {
        this._super();

        var winSize = cc.director.getWinSize();

        var pMenu = cc.Menu.create();
        pMenu.x = 0;
        pMenu.y = 0;
        cc.MenuItemFont.setFontName("Arial");
        cc.MenuItemFont.setFontSize(24);
        for (var i = 0; i < extensionsTestItemNames.length; ++i) {
            var selItem = extensionsTestItemNames[i];
            var pItem = cc.MenuItemFont.create(selItem.itemTitle, this.menuCallback, this);
            pItem.x = winSize.width / 2;
            pItem.y = winSize.height - (i + 1) * LINE_SPACE;
            pMenu.addChild(pItem, ITEM_TAG_BASIC + i);
        }
        this.addChild(pMenu);
    },

    menuCallback:function (sender) {
        var nIndex = sender.zIndex - ITEM_TAG_BASIC;
        extensionsTestItemNames[nIndex].testScene();
    }
});

var ExtensionsTestScene = TestScene.extend({
    runThisTest:function () {
        var pLayer = new ExtensionsMainLayer();
        this.addChild(pLayer);
	    cc.director.runScene(this);
    }
});
<commit_msg>fix plugin-x test for desktop platforms<commit_after>/****************************************************************************
 Copyright (c) 2008-2010 Ricardo Quesada
 Copyright (c) 2011-2012 cocos2d-x.org
 Copyright (c) 2013-2014 Chukong Technologies Inc.

 http://www.cocos2d-x.org

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

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

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

var LINE_SPACE = 40;
var ITEM_TAG_BASIC = 1000;

var TEST_NOTIFICATIONCENTER = 0;
var TEST_CCCONTROLBUTTON = 1;
var TEST_COCOSBUILDER = 2;
var TEST_HTTPCLIENT = 3;

var extensionsTestItemNames = [
    /*    {
     itemTitle:"NotificationCenterTest",
     testScene:function () {
     //runNotificationCenterTest();
     cc.log("not implement");
     }
     },*/
    {
        itemTitle:"CCControlButtonTest",
        testScene:function () {
            var pManager = ControlSceneManager.getInstance();
            var pScene = pManager.currentControlScene();
	        cc.director.runScene(pScene);
        }
    },
    {
        itemTitle:"CocosBuilderTest",
        testScene:function () {
            var pScene = new CocosBuilderTestScene();
            if (pScene) {
                pScene.runThisTest();
            }
        }
    },
    /*    {
     itemTitle:"HttpClientTest",
     testScene:function () {
     //runHttpClientTest();
     cc.log("not implement");
     }
     },*/
    {
        itemTitle:"TableViewTest",
        testScene:function () {
            runTableViewTest();
        }
    },
    {
        itemTitle:"EditBoxTest",
        testScene:function () {
            runEditBoxTest();
        }
    },
    {
        itemTitle:"WebSocketTest",
        testScene:function () {
            runWebSocketTest();
        }
    },
    {
        itemTitle:"SocketIOTest",
        testScene:function () {
            runSocketIOTest();
        }
    },
    {
        itemTitle:"CCPoolTest",
        testScene:function () {
            runCCPoolTest();
        }
    },
    {
        itemTitle:"PluginTest",
        testScene:function () {
            if(cc.sys.OS_ANDROID === cc.sys.os || cc.sys.OS_IOS === cc.sys.os){  //android/ios
                var testScene = pluginXSceneManager.currentPluginXScene();
                cc.director.runScene(testScene);
            }else if(!cc.sys.isNative){   //browser
                cc.loader.loadJs('', [
                    "../../frameworks/cocos2d-html5/external/pluginx/platform/facebook.js",
                    "../../frameworks/cocos2d-html5/external/pluginx/platform/facebook_sdk.js"
                ], function(){
                    var testScene = pluginXSceneManager.currentPluginXScene();
                    if (testScene) {
                        cc.director.runScene(testScene);
                    }
                });
            }else{  //desktop
                cc.log("Plugin-x doesn't support desktop platforms.");
            }
        }
    }
];
if (cc.sys.isNative) {
    extensionsTestItemNames.push({
        itemTitle:"AssetsManagerTest",
        testScene:function () {
            var testScene = new AssetsManagerLoaderScene();
            if (testScene) {
                testScene.runThisTest();
            }
        }
    });
}

var ExtensionsMainLayer = cc.Layer.extend({
    onEnter:function () {
        this._super();

        var winSize = cc.director.getWinSize();

        var pMenu = cc.Menu.create();
        pMenu.x = 0;
        pMenu.y = 0;
        cc.MenuItemFont.setFontName("Arial");
        cc.MenuItemFont.setFontSize(24);
        for (var i = 0; i < extensionsTestItemNames.length; ++i) {
            var selItem = extensionsTestItemNames[i];
            var pItem = cc.MenuItemFont.create(selItem.itemTitle, this.menuCallback, this);
            pItem.x = winSize.width / 2;
            pItem.y = winSize.height - (i + 1) * LINE_SPACE;
            pMenu.addChild(pItem, ITEM_TAG_BASIC + i);
        }
        this.addChild(pMenu);
    },

    menuCallback:function (sender) {
        var nIndex = sender.zIndex - ITEM_TAG_BASIC;
        extensionsTestItemNames[nIndex].testScene();
    }
});

var ExtensionsTestScene = TestScene.extend({
    runThisTest:function () {
        var pLayer = new ExtensionsMainLayer();
        this.addChild(pLayer);
	    cc.director.runScene(this);
    }
});
<|endoftext|>


<commit_before>'use strict';

function AnalyticsCtrl($scope, $location, $route, $http) {
	$scope.year = ($route.current.params.year ? $route.current.params.year : null);
	$scope.period = ($route.current.params.period ? $route.current.params.period : null);
	$scope.group = ($route.current.params.group ? $route.current.params.group : null);
	$scope.table = null;

	$scope.change = function(year, period, group) {
		$location.path("/analytics/" + year + "/" + period + "/" + group);
		$scope.safeApply();
	};
	$scope.click = function(item) {
		if ($scope.year) return;
		return $scope.change($scope.table.rows[item.row].c[0].v, "FY", "sector");
	};

	$scope.getdata = function() {
		var ochart=  {};
		ochart.options = {
		  legend:'none',
		  curveType:'function',
		  pointSize: 8,
		  interval: {
            'min': { 'style':'bars', 'color':'#428BCA', 'lineWidth': 1 },
            'quartile': { 'style':'boxes', 'color':'#428BCA', 'lineWidth': 1 },
            'max': { 'style':'bars', 'color':'#428BCA', 'lineWidth': 1 },
          },
		  colors:['#428BCA','#2A6496'],
		  width: "80%",
		  height: 500,
		  chartArea:{left:30,top:10,width:"90%",height:"80%"},
		  tooltip: { isHtml: true },
		  bar: { groupWidth: "30%" }
		};
		ochart.type = "LineChart";
		$scope.chart = ochart;

		if (!$scope.year)
		{
			// main chart
			$scope.table = {"cols": [
				{id: "year", label: "Year", type: "string"},
				{id: "median", label: "Median", type: "number"},
				{id: "min", label: "Min", type: "number", role: 'interval'},
				{id: "quartile", label: "Lower Quartile", type: "number", role: 'interval'},
				{id: "quartile", label: "Upper Quartile", type: "number", role: 'interval'},
				{id: "max", label: "Max", type: "number", role: 'interval'},
				{id: "", role: "tooltip", type: "string", p: { role: "tooltip", html: true } }
			], "rows": []};

			$scope.chart.data = $scope.table;

			$http({
					method: 'POST',
					url: 'http://secxbrl-info.xbrl.io/v1/_queries/public/ExtensionPercentUsageStatsByFiscalYear.jq',
					data: { domainsAndMembers: [] }
				}).
				success(function(data, status, headers, config) {
					if (data && data.ExtensionUsageStatsByYears)
						data.ExtensionUsageStatsByYears.forEach(function(item) {
							var key = item.fiscalYear;
							$scope.table.rows.push({c: [ {v: key}, {v: item.median}, {v: item.min}, {v: item.bottomQuartile}, {v: item.topQuartile}, {v: item.max}, {v: "

" + key + "

Minimum: " + item.min + "
Lower Quartile: " + item.bottomQuartile + "
Median: " + item.median + "
Upper Quartile: " + item.topQuartile + "
Maximum: " + item.max + "

" } ]});
						});

					$scope.chart.data = $scope.table;
				}).
				error(function(data, status, headers, config) {
					$scope.chart = null;
				});
		}
		else
		{
			$scope.table = {"cols": [
				{id: "domain", label: "Domain", type: "string"},
				{id: "median", label: "Median", type: "number"},
				{id: "min", label: "Min", type: "number", role: 'interval'},
				{id: "quartile", label: "Lower Quartile", type: "number", role: 'interval'},
				{id: "quartile", label: "Upper Quartile", type: "number", role: 'interval'},
				{id: "max", label: "Max", type: "number", role: 'interval'},
				{id: "", role: "tooltip", type: "string", p: { role: "tooltip", html: true } }
			], "rows": []};

			$scope.chart.data = $scope.table;

			$http({
					method: 'POST',
					url: 'http://secxbrl-info.xbrl.io/v1/_queries/public/ExtensionPercentUsageStatsByDomain.jq',
					data: { fiscalYearFocus: $scope.year, fiscalPeriodFocus: $scope.period, domainsAndMembers: [ { domain: $scope.group, members: $scope[$scope.group] } ] }
				}).
				success(function(data, status, headers, config) {
					if (data && data.ExtensionUsageStatsByDomain)
						data.ExtensionUsageStatsByDomain.forEach(function(item) {
							var p1 = item.selector.indexOf("'"), p2 = item.selector.lastIndexOf("'");
							var key = item.selector.substring(p1 + 1, p2);
							$scope.table.rows.push({c: [ {v: key}, {v: item.median}, {v: item.min}, {v: item.bottomQuartile}, {v: item.topQuartile}, {v: item.max}, {v: "

" + key + "

Minimum: " + item.min + "
Lower Quartile: " + item.bottomQuartile + "
Median: " + item.median + "
Upper Quartile: " + item.topQuartile + "
Maximum: " + item.max + "

" } ]});
						});

					$scope.chart.data = $scope.table;
				}).
				error(function(data, status, headers, config) {
					$scope.chart = null;
				});
		}
	};
	$scope.getdata();
};
<commit_msg>Implemented minimum value to 0<commit_after>'use strict';

function AnalyticsCtrl($scope, $location, $route, $http) {
	$scope.year = ($route.current.params.year ? $route.current.params.year : null);
	$scope.period = ($route.current.params.period ? $route.current.params.period : null);
	$scope.group = ($route.current.params.group ? $route.current.params.group : null);
	$scope.table = null;

	$scope.change = function(year, period, group) {
		$location.path("/analytics/" + year + "/" + period + "/" + group);
		$scope.safeApply();
	};
	$scope.click = function(item) {
		if ($scope.year) return;
		return $scope.change($scope.table.rows[item.row].c[0].v, "FY", "sector");
	};

	$scope.getdata = function() {
		var ochart=  {};
		ochart.options = {
		  legend:'none',
		  curveType:'function',
		  pointSize: 8,
		  interval: {
            'min': { 'style':'bars', 'color':'#428BCA', 'lineWidth': 1 },
            'quartile': { 'style':'boxes', 'color':'#428BCA', 'lineWidth': 1 },
            'max': { 'style':'bars', 'color':'#428BCA', 'lineWidth': 1 },
          },
		  colors:['#428BCA','#2A6496'],
		  width: "80%",
		  height: 500,
		  chartArea:{left:30,top:10,width:"90%",height:"80%"},
		  tooltip: { isHtml: true },
		  bar: { groupWidth: "30%" },
		  vAxis: { minValue: 0 }
		};
		ochart.type = "LineChart";
		$scope.chart = ochart;

		if (!$scope.year)
		{
			// main chart
			$scope.table = {"cols": [
				{id: "year", label: "Year", type: "string"},
				{id: "median", label: "Median", type: "number"},
				{id: "min", label: "Min", type: "number", role: 'interval'},
				{id: "quartile", label: "Lower Quartile", type: "number", role: 'interval'},
				{id: "quartile", label: "Upper Quartile", type: "number", role: 'interval'},
				{id: "max", label: "Max", type: "number", role: 'interval'},
				{id: "", role: "tooltip", type: "string", p: { role: "tooltip", html: true } }
			], "rows": []};

			$scope.chart.data = $scope.table;

			$http({
					method: 'POST',
					url: 'http://secxbrl-info.xbrl.io/v1/_queries/public/ExtensionPercentUsageStatsByFiscalYear.jq',
					data: { domainsAndMembers: [] }
				}).
				success(function(data, status, headers, config) {
					if (data && data.ExtensionUsageStatsByYears)
						data.ExtensionUsageStatsByYears.forEach(function(item) {
							var key = item.fiscalYear;
							$scope.table.rows.push({c: [ {v: key}, {v: item.median}, {v: item.min}, {v: item.bottomQuartile}, {v: item.topQuartile}, {v: item.max}, {v: "

" + key + "

Minimum: " + item.min + "
Lower Quartile: " + item.bottomQuartile + "
Median: " + item.median + "
Upper Quartile: " + item.topQuartile + "
Maximum: " + item.max + "

" } ]});
						});

					$scope.chart.data = $scope.table;
				}).
				error(function(data, status, headers, config) {
					$scope.chart = null;
				});
		}
		else
		{
			$scope.table = {"cols": [
				{id: "domain", label: "Domain", type: "string"},
				{id: "median", label: "Median", type: "number"},
				{id: "min", label: "Min", type: "number", role: 'interval'},
				{id: "quartile", label: "Lower Quartile", type: "number", role: 'interval'},
				{id: "quartile", label: "Upper Quartile", type: "number", role: 'interval'},
				{id: "max", label: "Max", type: "number", role: 'interval'},
				{id: "", role: "tooltip", type: "string", p: { role: "tooltip", html: true } }
			], "rows": []};

			$scope.chart.data = $scope.table;

			$http({
					method: 'POST',
					url: 'http://secxbrl-info.xbrl.io/v1/_queries/public/ExtensionPercentUsageStatsByDomain.jq',
					data: { fiscalYearFocus: $scope.year, fiscalPeriodFocus: $scope.period, domainsAndMembers: [ { domain: $scope.group, members: $scope[$scope.group] } ] }
				}).
				success(function(data, status, headers, config) {
					if (data && data.ExtensionUsageStatsByDomain)
						data.ExtensionUsageStatsByDomain.forEach(function(item) {
							var p1 = item.selector.indexOf("'"), p2 = item.selector.lastIndexOf("'");
							var key = item.selector.substring(p1 + 1, p2);
							$scope.table.rows.push({c: [ {v: key}, {v: item.median}, {v: item.min}, {v: item.bottomQuartile}, {v: item.topQuartile}, {v: item.max}, {v: "

" + key + "

Minimum: " + item.min + "
Lower Quartile: " + item.bottomQuartile + "
Median: " + item.median + "
Upper Quartile: " + item.topQuartile + "
Maximum: " + item.max + "

" } ]});
						});

					$scope.chart.data = $scope.table;
				}).
				error(function(data, status, headers, config) {
					$scope.chart = null;
				});
		}
	};
	$scope.getdata();
};
<|endoftext|>


<commit_before>// This can also be used on a per page basis by declaring the array at the bottom of the page
var ref = [];
ref[1] = '1. bushel';
ref[2] = '2. magnifying';
ref[3] = '3. unstandardizable';
ref[4] = '4. mudjar';
ref[5] = '5. judgment';
ref[6] = '6. estoile';
ref[7] = '7. hemielytron';
ref[8] = '8. fattiness';
ref[9] = '9. janissaries';
ref[10] = '10. supertemporal';
ref[11] = '11. recapitalized';
ref[12] = '12. original';
ref[13] = '13. misology';
ref[14] = '14. monophthongize';
ref[15] = '15. motto';
ref[16] = '16. dioicous';
ref[17] = '17. interrupted';
ref[18] = '18. tarne';
ref[19] = '19. playwright';
ref[20] = '20. dreadnaught';

// Shut JSHint up
var modalModule = modalModule || {};

var refsModule = (function () {
	'use strict';

	function init() {
		// Wrap in function to avoid immediate call
		$(document).on('click', '[data-refs]', function () {
			getRefs($(this).html());
		});
	}

	function getRefs(nums) {
		console.log(nums);

		var arr = nums.split(','),
			result = [];

		for (var i = 0; i < arr.length; i++) {
			if (arr[i].length === 1) {
				result.push(Number(arr[i]));
			} else {
				var split = arr[i].split('-'),
				high = split[1],
				low = split[0] - 1;

				while(low++ < high) {
					result.push(low);
				}
			}
		}

		console.log(result);
		openRef(result);
	}

	function openRef(data) {
		// Cache Ref Placeholder
		var refCon = $('#References');

		// Empty div
		refCon.empty();
		refCon.append('<button class="close-modal"></button>');

		$.each(data, function (i, refNum) {
			refCon.append('
' + ref[refNum] + '
');
		});

		// This is reliant on the modal module
		modalModule.openModal('References');
	}

	return {
		init: init
	};
})();
<commit_msg>Dotn't need that anymore<commit_after>// This can also be used on a per page basis by declaring the array at the bottom of the page
var ref = [];
ref[1] = '1. bushel';
ref[2] = '2. magnifying';
ref[3] = '3. unstandardizable';
ref[4] = '4. mudjar';
ref[5] = '5. judgment';
ref[6] = '6. estoile';
ref[7] = '7. hemielytron';
ref[8] = '8. fattiness';
ref[9] = '9. janissaries';
ref[10] = '10. supertemporal';
ref[11] = '11. recapitalized';
ref[12] = '12. original';
ref[13] = '13. misology';
ref[14] = '14. monophthongize';
ref[15] = '15. motto';
ref[16] = '16. dioicous';
ref[17] = '17. interrupted';
ref[18] = '18. tarne';
ref[19] = '19. playwright';
ref[20] = '20. dreadnaught';

// Shut JSHint up
var modalModule = modalModule || {};

var refsModule = (function () {
	'use strict';

	function init() {
		// Wrap in function to avoid immediate call
		$(document).on('click', '[data-refs]', function () {
			getRefs($(this).html());
		});
	}

	function getRefs(nums) {
		console.log(nums);

		var arr = nums.split(','),
			result = [];

		for (var i = 0; i < arr.length; i++) {
			if (arr[i].length === 1) {
				result.push(Number(arr[i]));
			} else {
				var split = arr[i].split('-'),
				high = split[1],
				low = split[0] - 1;

				while (low++ < high) {
					result.push(low);
				}
			}
		}

		openRef(result);
	}

	function openRef(data) {
		// Cache Ref Placeholder
		var refCon = $('#References');

		// Empty div
		refCon.empty();
		refCon.append('<button class="close-modal"></button>');

		$.each(data, function (i, refNum) {
			refCon.append('
' + ref[refNum] + '
');
		});

		// This is reliant on the modal module
		modalModule.openModal('References');
	}

	return {
		init: init
	};
})();
<|endoftext|>


<commit_before>var app = require('express').Router();

process.env.NTB_USER_AGENT = 'Hytteadmin/' + require('../package.json');
var turbasen = require('turbasen-auth');

app.get('/', function(req, res) {
  if (req.session && req.session.user) {
    res.json(req.session.user);
  } else {
    res.status(401);
    res.json({authenticated: false});
  }
});

app.get('/login/sherpa/signon', function(req, res) {
  throw new Error('Not Implemented');
});

app.get('/login/sherpa/callback', function(req, res) {
  throw new Error('Not Implemented');
});

app.post('/login/turbasen', turbasen.middleware, function(req, res, next) {
  if (req.turbasenAuth) {
    req.session.user = req.turbasenAuth;
    res.status(200);
    res.json(req.session.user);
  } else {
    req.session.destroy(function(err) {
      if (!err) {
        err = new Error('Invalid email or password');
        err.status = 401;
      }

      return next(err);
    });
  }
});

app.post('/logout', function(req, res) {
  req.session.destroy(function(err) {
    if (err) { throw err; }

    res.status(204).end();
  });
});

module.exports = app;
<commit_msg>Implement /auth/login/dnt route logic<commit_after>var app = require('express').Router();

process.env.NTB_USER_AGENT = 'Hytteadmin/' + require('../package.json');
var turbasen = require('turbasen-auth');

process.env.DNT_CONNECT_USER_AGENT = 'Hytteadmin/' + require('../package.json');
var Connect = require('dnt-connect');
var connect = new Connect(
  process.env.DNT_CONNECT_CLIENT,
  process.env.DNT_CONNECT_KEY
);

app.get('/', function(req, res) {
  if (req.session && req.session.user) {
    res.json(req.session.user);
  } else {
    res.status(401);
    res.json({authenticated: false});
  }
});

app.get('/login/dnt', connect.middleware('signon'), function(req, res, next) {
  if (!req.dntConnect)  {
    var err = new Error('DNT Connect: unknown error');
    err.status = 500;
    next(err);
  }

  if (req.dntConnect.err || !req.dntConnect.data.er_autentisert) {
    // @TODO redierect back to login page with error message
    return res.redirect('/login');
  }

  req.session.user = {
    id: 'sherpa3:' + req.dntConnect.data.sherpa_id,
    navn: req.dntConnect.data.fornavn + ' ' + req.dntConnect.data.etternavn,
    epost: req.dntConnect.data.epost,
    grupper: [] // @TODO get the groups
  };

  res.redirect('/hytter');
});

app.post('/login/turbasen', turbasen.middleware, function(req, res, next) {
  if (req.turbasenAuth) {
    req.session.user = req.turbasenAuth;
    res.status(200);
    res.json(req.session.user);
  } else {
    req.session.destroy(function(err) {
      if (!err) {
        err = new Error('Invalid email or password');
        err.status = 401;
      }

      return next(err);
    });
  }
});

app.post('/logout', function(req, res) {
  req.session.destroy(function(err) {
    if (err) { throw err; }

    res.status(204).end();
  });
});

module.exports = app;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import Menu from '@material-ui/core/Menu';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp';
import AppButton from '../AppButton';

class AppMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = { open: false, iconDown: true };
  }

  toggleMenu = (event) => {
    this.setState(prevState => ({
      open: !prevState.open,
      anchorEl: event.currentTarget,
      iconDown: !prevState.iconDown,
    }));
  };

  close = () => this.setState({ open: false, iconDown: true });

  // ES6
  flatten = list => list.reduce(
    (a, b) => a.concat(Array.isArray(b) ? this.flatten(b) : b), []
  );

  render() {
    const { titleMsg, showMenu, onTitleClick, menuComponent } = this.props;
    const { formatMessage } = this.props.intl;
    // const closeFxn = this.close;
    let newItems;
    if (menuComponent && menuComponent.props) {
      const flattenedMenu = this.flatten(menuComponent.props.children);
      newItems = flattenedMenu.map((m) => {
        const info = { // for each MenuItem, update the onClick event
          ...m,
          props: {
            ...m.props,
            onClick: () => {
              this.setState({ open: false, iconDown: true });
              m.props.onClick();
            },
          },
        };
        delete info.props.icon;
        return info;
      });
    }
    let menuHeader;
    if (showMenu) {
      const whichIcon = (this.state.iconDown) ? <ArrowDropDownIcon /> : <ArrowDropUpIcon />;
      menuHeader = (

          <AppButton
            variant="text"
            onClick={this.toggleMenu}
            label={formatMessage(titleMsg)}
            icon={whichIcon}
          />

      );
    } else {
      menuHeader = (
        <AppButton
          variant="text"
          onClick={event => onTitleClick(event)}
          label={formatMessage(titleMsg)}
        />
      );
    }
    return (

        {menuHeader}
        <Menu
          open={this.state.open}
          anchorEl={this.state.anchorEl}
          onClose={this.close}
        >
          {newItems}
        </Menu>

    );
  }
}

AppMenu.propTypes = {
  // parent
  titleMsg: PropTypes.object.isRequired,
  showMenu: PropTypes.bool,
  onTitleClick: PropTypes.func.isRequired,
  menuComponent: PropTypes.object,
  // from dispatch
  children: PropTypes.node,
  // from context
  intl: PropTypes.object.isRequired,
};

export default
injectIntl(
  AppMenu
);
<commit_msg>More work on app menu positioning<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import Menu from '@material-ui/core/Menu';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp';
import AppButton from '../AppButton';

class AppMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = { open: false, iconDown: true };
    this.buttonRef = React.createRef();
  }

  toggleMenu = (event) => {
    event.persist();
    this.setState(prevState => ({
      open: !prevState.open,
      iconDown: !prevState.iconDown,
    }));
  };

  close = () => this.setState({ open: false, iconDown: true });

  // ES6
  flatten = list => list.reduce(
    (a, b) => a.concat(Array.isArray(b) ? this.flatten(b) : b), []
  );

  render() {
    const { titleMsg, showMenu, onTitleClick, menuComponent } = this.props;
    const { formatMessage } = this.props.intl;
    // const closeFxn = this.close;
    let newItems;
    if (menuComponent && menuComponent.props) {
      const flattenedMenu = this.flatten(menuComponent.props.children);
      newItems = flattenedMenu.map((m) => {
        const info = { // for each MenuItem, update the onClick event
          ...m,
          props: {
            ...m.props,
            onClick: () => {
              this.setState({ open: false, iconDown: true });
              m.props.onClick();
            },
          },
        };
        delete info.props.icon;
        return info;
      });
    }
    let menuHeader;
    if (showMenu) {
      const whichIcon = (this.state.iconDown) ? <ArrowDropDownIcon /> : <ArrowDropUpIcon />;
      menuHeader = (
        <AppButton
          variant="text"
          onClick={this.toggleMenu}
          label={formatMessage(titleMsg)}
          icon={whichIcon}
        />
      );
    } else {
      menuHeader = (
        <AppButton
          variant="text"
          onClick={event => onTitleClick(event)}
          label={formatMessage(titleMsg)}
        />
      );
    }
    return (

{menuHeader}

        <Menu
          open={this.state.open}
          anchorEl={this.buttonRef.current}
          getContentAnchorEl={null}
          onClose={this.close}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
          transformOrigin={{ vertical: 'top', horizontal: 'left' }}
        >
          {newItems}
        </Menu>

    );
  }
}

AppMenu.propTypes = {
  // parent
  titleMsg: PropTypes.object.isRequired,
  showMenu: PropTypes.bool,
  onTitleClick: PropTypes.func.isRequired,
  menuComponent: PropTypes.object,
  // from dispatch
  children: PropTypes.node,
  // from context
  intl: PropTypes.object.isRequired,
};

export default
injectIntl(
  AppMenu
);
<|endoftext|>