<commit_before>'use strict';

/**
 * Returns `Set` class with custom equality comparisons.
 *
 * @param {function} hashFn — the function to determine the unique of value.
 * @returns {HashSet}
 */
module.exports = function hashSet(hashFn) {
    if (!hashFn) {
        throw new Error('You should specify hash function to create HashSet.');
    }

    /**
     * Set objects are collections of values, you can iterate its elements in insertion order.
     *
     * A value in the Set may only occur once; it is unique in the Set's collection.
     */
    return class HashSet {
        /**
         * The value of the length property is 0.
         */
        static get length() {
            return 0;
        }
        /**
         * Returns the function that created an instance's prototype.
         *
         * @param {Iterable} iterable — if an iterable object is passed, then all of its elements
         *                              will be added to the new Set. `null` is treated as undefined.
         * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of}
         */
        constructor(iterable) {
            this._map = new Map();

            if (iterable) {
                for (let item of iterable) {
                    this.add(item);
                }
            }
        }
        /**
         * The value of size is an integer representing how many entries the Set object has.
         * A set accessor function for size is undefined; you can not change this property.
         *
         * @returns {number} the number of elements in a Set object.
         */
        get size() {
            return this._map.size;
        }
        /**
         * Appends a new element with the given value to the Set object.
         *
         * @param {*} value — the value of the element to add to the Set object.
         * @returns {HashSet}.
         */
        add(value) {
            const id = hashFn(value);

            if (!this._map.has(id)) {
                this._map.set(id, value);
            }

            return this;
        }
        /**
         * Returns a boolean asserting whether an element is present with the given value in the Set object or not.
         *
         * @param {*} value — the value to test for presence in the Set object.
         * @returns {boolean} Returns true if an element with the specified value exists in the Set object;
         *                    otherwise false.
         */
        has(value) {
            const id = hashFn(value);

            return this._map.has(id);
        }
        /**
         * Removes the element associated to the value and returns the value that.
         *
         * `Set.prototype.has(value)` would have previously returned.
         * `Set.prototype.has(value)` will return false afterwards.
         *
         * @param {*} value — the value of the element to remove from the Set object.
         * @returns {boolean} Returns true if an element in the Set object has been removed successfully;
         *                    otherwise false.
         */
        delete(value) {
            const id = hashFn(value);

            return this._map.delete(id);
        }
        /**
         * Removes all elements from the Set object.
         */
        clear() {
            this._map.clear();
        }
        /**
         * Returns a new Iterator object that contains an array of [value, value] for each element in the Set object,
         * in insertion order.
         *
         * This is kept similar to the Map object, so that each entry has the same value for its key and value here.
         *
         * @returns {Iterator}
         */
        entries() {
            return this._map.values();
        }
        /**
         * Executes a provided function once per each value in the Set object, in insertion order.
         *
         * It is not invoked for values which have been deleted. However, it is executed for values which are present
         * but have the value undefined.
         *
         * Callback is invoked with three arguments:
         *   * the element value
         *   * the element value
         *   * the Set object being traversed
         *
         * @param {function} callbackFn — function to execute for each element.
         * @param {object} thisArg — value to use as this when executing callback. If a thisArg parameter is provided
         *                           to forEach, it will be used as the this value for each callback.
         */
        forEach(callbackFn, thisArg) {
            this._map.forEach(function(value) {
                callbackFn(value, value, this);
            }, thisArg);
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        values() {
            return this._map.values();
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        keys() {
            return this._map.values();
        }
        /**
         * The initial value of the @@iterator property is the same function object as the initial
         * value of the values property.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        [Symbol.iterator]() {
            return this._map.values();
        }
        /**
         * Returns Set object is equivalent to this HashSet object.
         *
         * @returns {Set}
         */
        valueOf() {
            return new Set(this._map.values());
        }
        /**
         * Returns a string representing object.
         *
         * @returns {string}
         */
        toString() {
            return '[object Set]';
        }
    };
}
<commit_msg>Fix forEach context passing<commit_after>'use strict';

/**
 * Returns `Set` class with custom equality comparisons.
 *
 * @param {function} hashFn — the function to determine the unique of value.
 * @returns {HashSet}
 */
module.exports = function hashSet(hashFn) {
    if (!hashFn) {
        throw new Error('You should specify hash function to create HashSet.');
    }

    /**
     * Set objects are collections of values, you can iterate its elements in insertion order.
     *
     * A value in the Set may only occur once; it is unique in the Set's collection.
     */
    return class HashSet {
        /**
         * The value of the length property is 0.
         */
        static get length() {
            return 0;
        }
        /**
         * Returns the function that created an instance's prototype.
         *
         * @param {Iterable} iterable — if an iterable object is passed, then all of its elements
         *                              will be added to the new Set. `null` is treated as undefined.
         * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of}
         */
        constructor(iterable) {
            this._map = new Map();

            if (iterable) {
                for (let item of iterable) {
                    this.add(item);
                }
            }
        }
        /**
         * The value of size is an integer representing how many entries the Set object has.
         * A set accessor function for size is undefined; you can not change this property.
         *
         * @returns {number} the number of elements in a Set object.
         */
        get size() {
            return this._map.size;
        }
        /**
         * Appends a new element with the given value to the Set object.
         *
         * @param {*} value — the value of the element to add to the Set object.
         * @returns {HashSet}.
         */
        add(value) {
            const id = hashFn(value);

            if (!this._map.has(id)) {
                this._map.set(id, value);
            }

            return this;
        }
        /**
         * Returns a boolean asserting whether an element is present with the given value in the Set object or not.
         *
         * @param {*} value — the value to test for presence in the Set object.
         * @returns {boolean} Returns true if an element with the specified value exists in the Set object;
         *                    otherwise false.
         */
        has(value) {
            const id = hashFn(value);

            return this._map.has(id);
        }
        /**
         * Removes the element associated to the value and returns the value that.
         *
         * `Set.prototype.has(value)` would have previously returned.
         * `Set.prototype.has(value)` will return false afterwards.
         *
         * @param {*} value — the value of the element to remove from the Set object.
         * @returns {boolean} Returns true if an element in the Set object has been removed successfully;
         *                    otherwise false.
         */
        delete(value) {
            const id = hashFn(value);

            return this._map.delete(id);
        }
        /**
         * Removes all elements from the Set object.
         */
        clear() {
            this._map.clear();
        }
        /**
         * Returns a new Iterator object that contains an array of [value, value] for each element in the Set object,
         * in insertion order.
         *
         * This is kept similar to the Map object, so that each entry has the same value for its key and value here.
         *
         * @returns {Iterator}
         */
        entries() {
            return this._map.values();
        }
        /**
         * Executes a provided function once per each value in the Set object, in insertion order.
         *
         * It is not invoked for values which have been deleted. However, it is executed for values which are present
         * but have the value undefined.
         *
         * Callback is invoked with three arguments:
         *   * the element value
         *   * the element value
         *   * the Set object being traversed
         *
         * @param {function} callbackFn — function to execute for each element.
         * @param {object} thisArg — value to use as this when executing callback. If a thisArg parameter is provided
         *                           to forEach, it will be used as the this value for each callback.
         */
        forEach(callbackFn, thisArg) {
            this._map.forEach(function(value) {
                callbackFn.call(thisArg, value, value, this);
            }, thisArg);
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        values() {
            return this._map.values();
        }
        /**
         * Returns a new Iterator object that contains the values for each element in the Set object in insertion order.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        keys() {
            return this._map.values();
        }
        /**
         * The initial value of the @@iterator property is the same function object as the initial
         * value of the values property.
         *
         * Is the same function as the values() function.
         *
         * @returns {Iterator}
         */
        [Symbol.iterator]() {
            return this._map.values();
        }
        /**
         * Returns Set object is equivalent to this HashSet object.
         *
         * @returns {Set}
         */
        valueOf() {
            return new Set(this._map.values());
        }
        /**
         * Returns a string representing object.
         *
         * @returns {string}
         */
        toString() {
            return '[object Set]';
        }
    };
}
<|endoftext|>


<commit_before>import React from 'react'
import Header from '../components/Header';
import Body from '../components/Body';
import Footer from '../components/Footer';
import EventHeader from '../components/EventHeader';
import ActionBar from '../components/ActionBar';
import NotFound from '../components/NotFound';
import Location from '../components/Location';
import HashLink from 'react-scrollchor';
import Tier from '../components/Tier';
import NotificationBar from '../components/NotificationBar';
import GetTicketForm from '../components/GetTicketForm';
import InterestedForm from '../components/InterestedForm';
import Responses from '../components/Responses';
import { filterCollection } from '../lib/utils';
import { addEventData } from '../graphql/queries';
import { addCreateResponseMutation } from '../graphql/mutations';
import Markdown from 'react-markdown';
import TicketsConfirmed from '../components/TicketsConfirmed';
import Loading from '../components/Loading';
import Error from '../components/Error';
import { FormattedMessage, FormattedDate, FormattedTime } from 'react-intl';

const defaultBackgroundImage = '/static/images/defaultBackgroundImage.png';

class Event extends React.Component {

  static propTypes = {
    collectiveSlug: React.PropTypes.string.required,
    eventSlug: React.PropTypes.string.required,
    data: React.PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.event = this.props.data.Event; // pre-loaded by SSR
    this.setInterested = this.setInterested.bind(this);
    this.updateResponse = this.updateResponse.bind(this);
    this.resetResponse = this.resetResponse.bind(this);
    this.handleGetTicketClick = this.handleGetTicketClick.bind(this);
    this.rsvp = this.rsvp.bind(this);
    this.closeModal = this.closeModal.bind(this);

    this.defaultActions = [
      {
        label: (<FormattedMessage id='actions.interested' defaultMessage='interested' />),
        // className: 'selected',
        // icon: 'star',
        onClick: this.setInterested
      },
      {
        className: 'whiteblue',
        component: <HashLink to="#tickets"><FormattedMessage id='actions.GetTicket' defaultMessage='get ticket' /></HashLink>
      }
    ];

    this.state = {
      view: 'default',
      showInterestedForm: false,
      response: {},
      api: { status: 'idle' },
      actions: this.defaultActions
    };
  }

  /**
   * If user is logged in, we directly create a response
   * Otherwise, we show the form to enter an email address
   */
  async setInterested(user) {
    if (user || this.user) {
      this.setState({ showInterestedForm: false });
      const tokens = user.email.substr(0, user.email.indexOf('@')).split('.');
      user.firstName = tokens[0] || '';
      user.lastName = tokens[1] || '';
      const response = {
        status: 'INTERESTED',
        user
      };
      try {
        await this.createResponse(response);
        this.event.responses.push(response);
        const actions = this.state.actions;
        actions[0].className = 'selected';
        actions[0].icon = 'star';
        this.setState({ actions, showInterestedForm: false });
      } catch (e) {
        this.error(`An error occured 😳. We couldn't register you as interested. Please try again in a few.`);
      }
      return;
    } else {
      this.setState({ showInterestedForm: !this.state.showInterestedForm });
      return;
    }
  }

  async rsvp(response) {
    try {
      await this.createResponse(response);
      this.setState({ response, view: 'default', modal: 'TicketsConfirmed' });
      window.scrollTo(0,0);
    } catch (e) {
      this.error(`An error occured 😳. We couldn't register you. Please try again in a few.`);
    }
  }

  closeModal() {
    this.setState({ modal: null });
  }

  changeView(view) {
    let actions;
    switch (view) {
      case 'GetTicket':
        actions = [{
          label: (<FormattedMessage id='actions.GoBack' defaultMessage={`go back`} />),
          onClick: this.resetResponse
        }];
        break;
      default:
        actions = this.defaultActions;
        break;
    }
    this.setState({view, actions});
    window.scrollTo(0,0);
  }

  async createResponse(response) {
    response.tier = response.tier || {};
    const ResponseInputType = {
      group: { slug: this.event.collective.slug },
      event: { slug: this.event.slug },
      tier: { id: response.tier.id },
      quantity: response.quantity,
      user: response.user,
      status: response.status
    };

    this.setState( { status: 'loading' });
    try {
      await this.props.createResponse(ResponseInputType);
      this.setState( { status: 'idle' });
    } catch (err) {
      console.error(">>> createResponse error: ", err);
      throw new Error(err.graphQLErrors[0].message);
    }
  }

  error(msg) {
    this.setState( {status: 'error', error: msg });
    setTimeout(() => {
      this.setState( { status: 'idle', error: null });
    }, 5000);
  }

  updateResponse(response) {
    this.setState({ response });
  }

  resetResponse() {
    this.setState({ response: {} });
    this.changeView('default');
  }

  handleGetTicketClick(response) {
    this.setState({ response, showInterestedForm: false });
    this.changeView('GetTicket');
  }

  render () {
    console.log("new state:", this.state, "data", this.props.data);
    const { Event, error, loading } = this.props.data;

    if (loading) return (<Loading />);

    this.event = Event;

    if ( error ) {
      console.error(error.message);
      return (<Error message="GraphQL error" />)
    }

    if (!loading && !this.props.data.Event) {
      return (<NotFound />)
    }

    const going = loading && filterCollection(Event.responses, {'status':'YES'});
    const interested = loading && filterCollection(Event.responses, {'status':'INTERESTED'});

    const info = (
      <HashLink to="#location">
        <FormattedDate value={Event.startsAt} weekday='short' day='numeric' month='long' />,
        <FormattedTime value={Event.startsAt} timeZone={Event.timezone} />  -
        {Event.location}
      </HashLink>
    );

    const backgroundImage = Event.backgroundImage || Event.collective.backgroundImage || defaultBackgroundImage;

    return (

        <TicketsConfirmed
          show={this.state.modal === 'TicketsConfirmed'}
          onClose={this.closeModal}
          event={this.event}
          response={this.state.response} />

            <div className={`EventPage ${this.state.modal && 'showModal'}`}>

              <NotificationBar status={this.state.status} error={this.state.error} />

              {this.state.view === 'loading' && <Loading /> }

              {this.state.view === 'default' &&
                <EventHeader
                  logo={Event.collective.logo}
                  title={Event.name}
                  backgroundImage={backgroundImage}
                  />
              }

              {this.state.view !== 'loading' &&
                <ActionBar
                  actions={this.state.actions}
                  info={info}
                  />
              }

              {this.state.showInterestedForm &&
                <InterestedForm onSubmit={this.setInterested} />
              }

              {this.state.view == 'GetTicket' &&
                <GetTicketForm
                  onCancel={this.resetResponse}
                  onSubmit={this.rsvp}
                  quantity={this.state.response.quantity}
                  stripePublishableKey={this.event.collective.stripePublishableKey}
                  tier={this.state.response.tier || Event.tiers[0]}
                  />
              }

              {this.state.view == 'default' &&

                      <Markdown source={Event.description} />

                      {Event.tiers.map((tier) =>
                        <Tier
                          key={tier.id}
                          className="tier"
                          tier={tier}
                          onChange={(response) => this.updateResponse(response)}
                          onClick={(response) => this.handleGetTicketClick(response)}
                          />
                      )}

                  <Location
                    location={Event.location}
                    address={Event.address}
                    lat={Event.lat}
                    long={Event.long}
                    />

                  { Event.responses.length > 0 &&

                        <FormattedMessage id='event.responses.title.going' values={{n: going.length}} defaultMessage={`{n} {n, plural, one {person going} other {people going}}`} />
                        { interested.length > 0 &&

                             -
                            <FormattedMessage id='event.responses.title.interested' values={{n: interested.length}} defaultMessage={`{n} interested`} />

                        }

                      <Responses responses={Event.responses} />

                  }

              }

    )
  }
}

const EventWithDataWithMutation = addCreateResponseMutation(addEventData(Event));

export default EventWithDataWithMutation;
<commit_msg>added back comment to easily test confirmation modal<commit_after>import React from 'react'
import Header from '../components/Header';
import Body from '../components/Body';
import Footer from '../components/Footer';
import EventHeader from '../components/EventHeader';
import ActionBar from '../components/ActionBar';
import NotFound from '../components/NotFound';
import Location from '../components/Location';
import HashLink from 'react-scrollchor';
import Tier from '../components/Tier';
import NotificationBar from '../components/NotificationBar';
import GetTicketForm from '../components/GetTicketForm';
import InterestedForm from '../components/InterestedForm';
import Responses from '../components/Responses';
import { filterCollection } from '../lib/utils';
import { addEventData } from '../graphql/queries';
import { addCreateResponseMutation } from '../graphql/mutations';
import Markdown from 'react-markdown';
import TicketsConfirmed from '../components/TicketsConfirmed';
import Loading from '../components/Loading';
import Error from '../components/Error';
import { FormattedMessage, FormattedDate, FormattedTime } from 'react-intl';

const defaultBackgroundImage = '/static/images/defaultBackgroundImage.png';

class Event extends React.Component {

  static propTypes = {
    collectiveSlug: React.PropTypes.string.required,
    eventSlug: React.PropTypes.string.required,
    data: React.PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.event = this.props.data.Event; // pre-loaded by SSR
    this.setInterested = this.setInterested.bind(this);
    this.updateResponse = this.updateResponse.bind(this);
    this.resetResponse = this.resetResponse.bind(this);
    this.handleGetTicketClick = this.handleGetTicketClick.bind(this);
    this.rsvp = this.rsvp.bind(this);
    this.closeModal = this.closeModal.bind(this);

    this.defaultActions = [
      {
        label: (<FormattedMessage id='actions.interested' defaultMessage='interested' />),
        // className: 'selected',
        // icon: 'star',
        onClick: this.setInterested
      },
      {
        className: 'whiteblue',
        component: <HashLink to="#tickets"><FormattedMessage id='actions.GetTicket' defaultMessage='get ticket' /></HashLink>
      }
    ];

    this.state = {
      view: 'default',
      showInterestedForm: false,
      response: {},
      api: { status: 'idle' },
      actions: this.defaultActions
    };

    // To test confirmation screen, uncomment the following:
    // this.state.modal = "TicketsConfirmed";
    // this.state.response = {
    //   user: { email: "etienne@gmail.com"},
    //   tier: this.event && this.event.tiers[0],
    //   quantity: 2
    // };

  }

  /**
   * If user is logged in, we directly create a response
   * Otherwise, we show the form to enter an email address
   */
  async setInterested(user) {
    if (user || this.user) {
      this.setState({ showInterestedForm: false });
      const tokens = user.email.substr(0, user.email.indexOf('@')).split('.');
      user.firstName = tokens[0] || '';
      user.lastName = tokens[1] || '';
      const response = {
        status: 'INTERESTED',
        user
      };
      try {
        await this.createResponse(response);
        this.event.responses.push(response);
        const actions = this.state.actions;
        actions[0].className = 'selected';
        actions[0].icon = 'star';
        this.setState({ actions, showInterestedForm: false });
      } catch (e) {
        this.error(`An error occured 😳. We couldn't register you as interested. Please try again in a few.`);
      }
      return;
    } else {
      this.setState({ showInterestedForm: !this.state.showInterestedForm });
      return;
    }
  }

  async rsvp(response) {
    try {
      await this.createResponse(response);
      this.setState({ response, view: 'default', modal: 'TicketsConfirmed' });
      window.scrollTo(0,0);
    } catch (e) {
      this.error(`An error occured 😳. We couldn't register you. Please try again in a few.`);
    }
  }

  closeModal() {
    this.setState({ modal: null });
  }

  changeView(view) {
    let actions;
    switch (view) {
      case 'GetTicket':
        actions = [{
          label: (<FormattedMessage id='actions.GoBack' defaultMessage={`go back`} />),
          onClick: this.resetResponse
        }];
        break;
      default:
        actions = this.defaultActions;
        break;
    }
    this.setState({view, actions});
    window.scrollTo(0,0);
  }

  async createResponse(response) {
    response.tier = response.tier || {};
    const ResponseInputType = {
      group: { slug: this.event.collective.slug },
      event: { slug: this.event.slug },
      tier: { id: response.tier.id },
      quantity: response.quantity,
      user: response.user,
      status: response.status
    };

    this.setState( { status: 'loading' });
    try {
      await this.props.createResponse(ResponseInputType);
      this.setState( { status: 'idle' });
    } catch (err) {
      console.error(">>> createResponse error: ", err);
      throw new Error(err.graphQLErrors[0].message);
    }
  }

  error(msg) {
    this.setState( {status: 'error', error: msg });
    setTimeout(() => {
      this.setState( { status: 'idle', error: null });
    }, 5000);
  }

  updateResponse(response) {
    this.setState({ response });
  }

  resetResponse() {
    this.setState({ response: {} });
    this.changeView('default');
  }

  handleGetTicketClick(response) {
    this.setState({ response, showInterestedForm: false });
    this.changeView('GetTicket');
  }

  render () {
    console.log("new state:", this.state, "data", this.props.data);
    const { Event, error, loading } = this.props.data;

    if (loading) return (<Loading />);

    this.event = Event;

    if ( error ) {
      console.error(error.message);
      return (<Error message="GraphQL error" />)
    }

    if (!loading && !this.props.data.Event) {
      return (<NotFound />)
    }

    const going = loading && filterCollection(Event.responses, {'status':'YES'});
    const interested = loading && filterCollection(Event.responses, {'status':'INTERESTED'});

    const info = (
      <HashLink to="#location">
        <FormattedDate value={Event.startsAt} weekday='short' day='numeric' month='long' />,
        <FormattedTime value={Event.startsAt} timeZone={Event.timezone} />  -
        {Event.location}
      </HashLink>
    );

    const backgroundImage = Event.backgroundImage || Event.collective.backgroundImage || defaultBackgroundImage;

    return (

        <TicketsConfirmed
          show={this.state.modal === 'TicketsConfirmed'}
          onClose={this.closeModal}
          event={this.event}
          response={this.state.response} />

            <div className={`EventPage ${this.state.modal && 'showModal'}`}>

              <NotificationBar status={this.state.status} error={this.state.error} />

              {this.state.view === 'loading' && <Loading /> }

              {this.state.view === 'default' &&
                <EventHeader
                  logo={Event.collective.logo}
                  title={Event.name}
                  backgroundImage={backgroundImage}
                  />
              }

              {this.state.view !== 'loading' &&
                <ActionBar
                  actions={this.state.actions}
                  info={info}
                  />
              }

              {this.state.showInterestedForm &&
                <InterestedForm onSubmit={this.setInterested} />
              }

              {this.state.view == 'GetTicket' &&
                <GetTicketForm
                  onCancel={this.resetResponse}
                  onSubmit={this.rsvp}
                  quantity={this.state.response.quantity}
                  stripePublishableKey={this.event.collective.stripePublishableKey}
                  tier={this.state.response.tier || Event.tiers[0]}
                  />
              }

              {this.state.view == 'default' &&

                      <Markdown source={Event.description} />

                      {Event.tiers.map((tier) =>
                        <Tier
                          key={tier.id}
                          className="tier"
                          tier={tier}
                          onChange={(response) => this.updateResponse(response)}
                          onClick={(response) => this.handleGetTicketClick(response)}
                          />
                      )}

                  <Location
                    location={Event.location}
                    address={Event.address}
                    lat={Event.lat}
                    long={Event.long}
                    />

                  { Event.responses.length > 0 &&

                        <FormattedMessage id='event.responses.title.going' values={{n: going.length}} defaultMessage={`{n} {n, plural, one {person going} other {people going}}`} />
                        { interested.length > 0 &&

                             -
                            <FormattedMessage id='event.responses.title.interested' values={{n: interested.length}} defaultMessage={`{n} interested`} />

                        }

                      <Responses responses={Event.responses} />

                  }

              }

    )
  }
}

const EventWithDataWithMutation = addCreateResponseMutation(addEventData(Event));

export default EventWithDataWithMutation;
<|endoftext|>


<commit_before>this.contentTypes = {
  "aiff": "audio/x-aiff",
  "arj": "application/x-arj-compressed",
  "asf": "video/x-ms-asf",
  "asx": "video/x-ms-asx",
  "au": "audio/ulaw",
  "avi": "video/x-msvideo",
  "bcpio": "application/x-bcpio",
  "ccad": "application/clariscad",
  "cod": "application/vnd.rim.cod",
  "com": "application/x-msdos-program",
  "cpio": "application/x-cpio",
  "cpt": "application/mac-compactpro",
  "csh": "application/x-csh",
  "css": "text/css",
  "deb": "application/x-debian-package",
  "dl": "video/dl",
  "doc": "application/msword",
  "drw": "application/drafting",
  "dvi": "application/x-dvi",
  "dwg": "application/acad",
  "dxf": "application/dxf",
  "dxr": "application/x-director",
  "etx": "text/x-setext",
  "ez": "application/andrew-inset",
  "fli": "video/x-fli",
  "flv": "video/x-flv",
  "gif": "image/gif",
  "gl": "video/gl",
  "gtar": "application/x-gtar",
  "gz": "application/x-gzip",
  "hdf": "application/x-hdf",
  "hqx": "application/mac-binhex40",
  "html": "text/html",
  "ice": "x-conference/x-cooltalk",
  "ief": "image/ief",
  "igs": "model/iges",
  "ips": "application/x-ipscript",
  "ipx": "application/x-ipix",
  "jad": "text/vnd.sun.j2me.app-descriptor",
  "jar": "application/java-archive",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "latex": "application/x-latex",
  "lsp": "application/x-lisp",
  "lzh": "application/octet-stream",
  "m": "text/plain",
  "m3u": "audio/x-mpegurl",
  "man": "application/x-troff-man",
  "me": "application/x-troff-me",
  "midi": "audio/midi",
  "mif": "application/x-mif",
  "mime": "www/mime",
  "movie": "video/x-sgi-movie",
  "mp4": "video/mp4",
  "mpg": "video/mpeg",
  "mpga": "audio/mpeg",
  "ms": "application/x-troff-ms",
  "nc": "application/x-netcdf",
  "oda": "application/oda",
  "ogm": "application/ogg",
  "pbm": "image/x-portable-bitmap",
  "pdf": "application/pdf",
  "pgm": "image/x-portable-graymap",
  "pgn": "application/x-chess-pgn",
  "pgp": "application/pgp",
  "pm": "application/x-perl",
  "png": "image/png",
  "pnm": "image/x-portable-anymap",
  "ppm": "image/x-portable-pixmap",
  "ppz": "application/vnd.ms-powerpoint",
  "pre": "application/x-freelance",
  "prt": "application/pro_eng",
  "ps": "application/postscript",
  "qt": "video/quicktime",
  "ra": "audio/x-realaudio",
  "rar": "application/x-rar-compressed",
  "ras": "image/x-cmu-raster",
  "rgb": "image/x-rgb",
  "rm": "audio/x-pn-realaudio",
  "rpm": "audio/x-pn-realaudio-plugin",
  "rtf": "text/rtf",
  "rtx": "text/richtext",
  "scm": "application/x-lotusscreencam",
  "set": "application/set",
  "sgml": "text/sgml",
  "sh": "application/x-sh",
  "shar": "application/x-shar",
  "silo": "model/mesh",
  "sit": "application/x-stuffit",
  "skt": "application/x-koan",
  "smil": "application/smil",
  "snd": "audio/basic",
  "sol": "application/solids",
  "spl": "application/x-futuresplash",
  "src": "application/x-wais-source",
  "stl": "application/SLA",
  "stp": "application/STEP",
  "sv4cpio": "application/x-sv4cpio",
  "sv4crc": "application/x-sv4crc",
  "swf": "application/x-shockwave-flash",
  "tar": "application/x-tar",
  "tcl": "application/x-tcl",
  "tex": "application/x-tex",
  "texinfo": "application/x-texinfo",
  "tgz": "application/x-tar-gz",
  "tiff": "image/tiff",
  "tr": "application/x-troff",
  "tsi": "audio/TSP-audio",
  "tsp": "application/dsptype",
  "tsv": "text/tab-separated-values",
  "txt": "text/plain",
  "unv": "application/i-deas",
  "ustar": "application/x-ustar",
  "vcd": "application/x-cdlink",
  "vda": "application/vda",
  "vivo": "video/vnd.vivo",
  "vrm": "x-world/x-vrml",
  "wav": "audio/x-wav",
  "wax": "audio/x-ms-wax",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "wmx": "video/x-ms-wmx",
  "wrl": "model/vrml",
  "wvx": "video/x-ms-wvx",
  "xbm": "image/x-xbitmap",
  "xlw": "application/vnd.ms-excel",
  "xml": "text/xml",
  "xpm": "image/x-xpixmap",
  "xwd": "image/x-xwindowdump",
  "xyz": "chemical/x-pdb",
  "zip": "application/zip"
};
<commit_msg>add 'less' mime type<commit_after>this.contentTypes = {
  "aiff": "audio/x-aiff",
  "arj": "application/x-arj-compressed",
  "asf": "video/x-ms-asf",
  "asx": "video/x-ms-asx",
  "au": "audio/ulaw",
  "avi": "video/x-msvideo",
  "bcpio": "application/x-bcpio",
  "ccad": "application/clariscad",
  "cod": "application/vnd.rim.cod",
  "com": "application/x-msdos-program",
  "cpio": "application/x-cpio",
  "cpt": "application/mac-compactpro",
  "csh": "application/x-csh",
  "css": "text/css",
  "deb": "application/x-debian-package",
  "dl": "video/dl",
  "doc": "application/msword",
  "drw": "application/drafting",
  "dvi": "application/x-dvi",
  "dwg": "application/acad",
  "dxf": "application/dxf",
  "dxr": "application/x-director",
  "etx": "text/x-setext",
  "ez": "application/andrew-inset",
  "fli": "video/x-fli",
  "flv": "video/x-flv",
  "gif": "image/gif",
  "gl": "video/gl",
  "gtar": "application/x-gtar",
  "gz": "application/x-gzip",
  "hdf": "application/x-hdf",
  "hqx": "application/mac-binhex40",
  "html": "text/html",
  "ice": "x-conference/x-cooltalk",
  "ief": "image/ief",
  "igs": "model/iges",
  "ips": "application/x-ipscript",
  "ipx": "application/x-ipix",
  "jad": "text/vnd.sun.j2me.app-descriptor",
  "jar": "application/java-archive",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "latex": "application/x-latex",
  "less": "text/css",
  "lsp": "application/x-lisp",
  "lzh": "application/octet-stream",
  "m": "text/plain",
  "m3u": "audio/x-mpegurl",
  "man": "application/x-troff-man",
  "me": "application/x-troff-me",
  "midi": "audio/midi",
  "mif": "application/x-mif",
  "mime": "www/mime",
  "movie": "video/x-sgi-movie",
  "mp4": "video/mp4",
  "mpg": "video/mpeg",
  "mpga": "audio/mpeg",
  "ms": "application/x-troff-ms",
  "nc": "application/x-netcdf",
  "oda": "application/oda",
  "ogm": "application/ogg",
  "pbm": "image/x-portable-bitmap",
  "pdf": "application/pdf",
  "pgm": "image/x-portable-graymap",
  "pgn": "application/x-chess-pgn",
  "pgp": "application/pgp",
  "pm": "application/x-perl",
  "png": "image/png",
  "pnm": "image/x-portable-anymap",
  "ppm": "image/x-portable-pixmap",
  "ppz": "application/vnd.ms-powerpoint",
  "pre": "application/x-freelance",
  "prt": "application/pro_eng",
  "ps": "application/postscript",
  "qt": "video/quicktime",
  "ra": "audio/x-realaudio",
  "rar": "application/x-rar-compressed",
  "ras": "image/x-cmu-raster",
  "rgb": "image/x-rgb",
  "rm": "audio/x-pn-realaudio",
  "rpm": "audio/x-pn-realaudio-plugin",
  "rtf": "text/rtf",
  "rtx": "text/richtext",
  "scm": "application/x-lotusscreencam",
  "set": "application/set",
  "sgml": "text/sgml",
  "sh": "application/x-sh",
  "shar": "application/x-shar",
  "silo": "model/mesh",
  "sit": "application/x-stuffit",
  "skt": "application/x-koan",
  "smil": "application/smil",
  "snd": "audio/basic",
  "sol": "application/solids",
  "spl": "application/x-futuresplash",
  "src": "application/x-wais-source",
  "stl": "application/SLA",
  "stp": "application/STEP",
  "sv4cpio": "application/x-sv4cpio",
  "sv4crc": "application/x-sv4crc",
  "swf": "application/x-shockwave-flash",
  "tar": "application/x-tar",
  "tcl": "application/x-tcl",
  "tex": "application/x-tex",
  "texinfo": "application/x-texinfo",
  "tgz": "application/x-tar-gz",
  "tiff": "image/tiff",
  "tr": "application/x-troff",
  "tsi": "audio/TSP-audio",
  "tsp": "application/dsptype",
  "tsv": "text/tab-separated-values",
  "txt": "text/plain",
  "unv": "application/i-deas",
  "ustar": "application/x-ustar",
  "vcd": "application/x-cdlink",
  "vda": "application/vda",
  "vivo": "video/vnd.vivo",
  "vrm": "x-world/x-vrml",
  "wav": "audio/x-wav",
  "wax": "audio/x-ms-wax",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "wmx": "video/x-ms-wmx",
  "wrl": "model/vrml",
  "wvx": "video/x-ms-wvx",
  "xbm": "image/x-xbitmap",
  "xlw": "application/vnd.ms-excel",
  "xml": "text/xml",
  "xpm": "image/x-xpixmap",
  "xwd": "image/x-xwindowdump",
  "xyz": "chemical/x-pdb",
  "zip": "application/zip"
};
<|endoftext|>


<commit_before>'use strict';

var assign          = require('es5-ext/object/assign')
  , ensureString    = require('es5-ext/object/validate-stringifiable-value')
  , endsWith        = require('es5-ext/string/#/ends-with')
  , d               = require('d')
  , ee              = require('event-emitter')
  , deferred        = require('deferred')
  , memoizeMethods  = require('memoizee/methods-plain')
  , getStamp        = require('time-uuid/time')
  , tokenizeKeyPath = require('dbjs/_setup/utils/resolve-property-path').tokenize

  , push = Array.prototype.push;

var getBriefDataEvents = function (obj, map, events) {
	var event = obj._lastOwnEvent_, idLength = obj.master.__id__.length + 1;
	if (event) events.push(event);
	obj._forEachOwnDescriptor_(function (desc) {
		if (!desc._sKey_) return;
		if (!map[desc.__valueId__.slice(idLength)]) return;
		event = desc._lastOwnEvent_;
		if (event) events.push(event);
	});
	obj._forEachOwnItem_(function (item) {
		if (!item._pSKey_) return;
		if (!map[item.object.__id__ + '/' + item._pSKey_].slice(idLength)) return;
		event = item._lastOwnEvent_;
		if (event) events.push(event);
	});
	obj._forEachOwnNestedObject_(function (object) {
		push.apply(events, getBriefDataEvents(object, map, events));
	});
	return events;
};

var resolveValue = function (obj, keyTokens) {
	var i, sKey;
	for (i = 0; (sKey = keyTokens[i]); ++i) {
		if (obj == null) return obj;
		obj = obj._get_(sKey);
	}
	return obj;
};

var resolveValueLastModified = function (obj, keyTokens) {
	var i, sKey, l = keyTokens.length - 1;
	for (i = 0; i < l; ++i) {
		if (obj == null) return obj;
		obj = obj._get_(keyTokens[i]);
	}
	if (!obj || !obj._getPropertyLastModified_) return null;
	sKey = keyTokens[l];
	return obj._getPropertyLastModified_(sKey);
};

var getCollectionSnapshot = function (collection, resolve, keyTokens) {
	var result = [];
	collection.forEach(function (obj) {
		result.push({ id: obj.__id__, sortIndex: resolve(obj, keyTokens) });
	});
	return result;
};

var DbjsCluster = module.exports = function (persistentDb) {
	if (!(this instanceof DbjsCluster)) return new DbjsCluster(persistentDb);
	this.persistentDb = persistentDb;
	this.db = persistentDb.db;
};
ee(Object.defineProperties(DbjsCluster.prototype, assign({
	getObjectData: d(function (id) {
		var obj = this.db.objects.getById(ensureString(id));
		if (!obj) return this.persistentDb.loadObject(id);
		return deferred(obj.getAllEvents());
	}),
	getObjectsSelectedData: d(function (ids, dataMap) {
		var events = [];
		return deferred.map(ids, function (id) {
			var obj = this.db.objects.getById(id);
			if (obj) {
				getBriefDataEvents(obj, dataMap, events);
				return;
			}
			return this.persistentDb.loadObject(id)(function () {
				return getBriefDataEvents(this.db.objects.getById(id), dataMap, events);
			}.bind(this));
		}.bind(this))(events);
	}),
	getCollectionView: d(function (collectionName, initSet, keyPath, filter, sortKeyPath) {
		return this._setupCollectionView(collectionName, initSet, keyPath, filter, sortKeyPath)(
			function (data) {  return data.getResult(); }
		);
	}),
	searchCollectionView: d(function (collectionName, filter) {
		return this._setupCollectionView(collectionName)(function (data) {
			var result = [];
			data.getResult().forEach(function (item) {
				if (filter(this.db.objects.getById(item.id))) result.push(item);
			}, this);
			return result;
		}.bind(this));
	}),
	getCollectionSize: d(function (collectionName, initSet, keyPath, filter) {
		return this._setupCollectionSize(collectionName, initSet, keyPath, filter)(function (data) {
			return data.getResult();
		});
	})
}, memoizeMethods({
	_loadAll: d(function () { return this.persistentDb.loadAll(); }),
	_setupCollection: d(function (collectionName, initSet, keyPath, filter) {
		return this._loadAll()(function () {
			return initSet.filterByKeyPath(keyPath, filter);
		});
	}, { length: 1 }),
	_setupCollectionView: d(function (collectionName, initSet, keyPath, filter, sortKeyPath) {
		return this._setupCollection(collectionName, initSet, keyPath, filter)(function (collection) {
			var compare, keyTokens, resolve;
			if (endsWith.call(sortKeyPath, ':lastModified')) {
				sortKeyPath = sortKeyPath.slice(0, -':lastModified'.length);
				resolve = resolveValueLastModified;
			} else {
				resolve = resolveValue;
			}
			keyTokens = tokenizeKeyPath(sortKeyPath);
			compare = function (a, b) { return resolve(a, keyTokens) - resolve(b, keyTokens); };
			collection = collection.toArray(compare);
			collection.on('change', function () {
				this.emit('collectionview',
					{ value: getCollectionSnapshot(collection, resolve, keyTokens), id: collectionName });
			}.bind(this));
			return { getResult: function () {
				return getCollectionSnapshot(collection, resolve, keyTokens);
			}, collection: collection };
		});
	}, { length: 1 }),
	_setupCollectionSize: d(function (collectionName, initSet, keyPath, filter) {
		return this._setupCollection(collectionName, initSet, keyPath, filter)(function (collection) {
			var value, stamp;
			collection._size.on('change', function (event) {
				stamp = getStamp();
				value = event.newValue;
				this.persistentDb.storeCustom('_size:' + collectionName, stamp + '.' + value).done();
				this.emit('collectionsize', { value: value, id: collectionName, stamp: stamp });
			}.bind(this));
			return this.persistentDb.getCustom('_size:' + collectionName)(function (value) {
				var index, stamp;
				if (value) {
					index = value.indexOf('.');
					stamp = Number(value.slice(0, index));
					value = Number(value.slice(index + 1));
				}
				if (value !== collection.size) {
					stamp = getStamp();
					value = collection.size;
					this.persistentDb.storeCustom('_size:' + collectionName, stamp + '.' + value).done();
				}
				return { getResult: function () { return { value: value, stamp: stamp }; },
					collection: collection };
			}.bind(this));
		}.bind(this));
	}, { length: 1 })
}))));
<commit_msg>Emit events also on initialisation<commit_after>'use strict';

var assign          = require('es5-ext/object/assign')
  , ensureString    = require('es5-ext/object/validate-stringifiable-value')
  , endsWith        = require('es5-ext/string/#/ends-with')
  , d               = require('d')
  , ee              = require('event-emitter')
  , deferred        = require('deferred')
  , memoizeMethods  = require('memoizee/methods-plain')
  , getStamp        = require('time-uuid/time')
  , tokenizeKeyPath = require('dbjs/_setup/utils/resolve-property-path').tokenize

  , push = Array.prototype.push;

var getBriefDataEvents = function (obj, map, events) {
	var event = obj._lastOwnEvent_, idLength = obj.master.__id__.length + 1;
	if (event) events.push(event);
	obj._forEachOwnDescriptor_(function (desc) {
		if (!desc._sKey_) return;
		if (!map[desc.__valueId__.slice(idLength)]) return;
		event = desc._lastOwnEvent_;
		if (event) events.push(event);
	});
	obj._forEachOwnItem_(function (item) {
		if (!item._pSKey_) return;
		if (!map[item.object.__id__ + '/' + item._pSKey_].slice(idLength)) return;
		event = item._lastOwnEvent_;
		if (event) events.push(event);
	});
	obj._forEachOwnNestedObject_(function (object) {
		push.apply(events, getBriefDataEvents(object, map, events));
	});
	return events;
};

var resolveValue = function (obj, keyTokens) {
	var i, sKey;
	for (i = 0; (sKey = keyTokens[i]); ++i) {
		if (obj == null) return obj;
		obj = obj._get_(sKey);
	}
	return obj;
};

var resolveValueLastModified = function (obj, keyTokens) {
	var i, sKey, l = keyTokens.length - 1;
	for (i = 0; i < l; ++i) {
		if (obj == null) return obj;
		obj = obj._get_(keyTokens[i]);
	}
	if (!obj || !obj._getPropertyLastModified_) return null;
	sKey = keyTokens[l];
	return obj._getPropertyLastModified_(sKey);
};

var getCollectionSnapshot = function (collection, resolve, keyTokens) {
	var result = [];
	collection.forEach(function (obj) {
		result.push({ id: obj.__id__, sortIndex: resolve(obj, keyTokens) });
	});
	return result;
};

var DbjsCluster = module.exports = function (persistentDb) {
	if (!(this instanceof DbjsCluster)) return new DbjsCluster(persistentDb);
	this.persistentDb = persistentDb;
	this.db = persistentDb.db;
};
ee(Object.defineProperties(DbjsCluster.prototype, assign({
	getObjectData: d(function (id) {
		var obj = this.db.objects.getById(ensureString(id));
		if (!obj) return this.persistentDb.loadObject(id);
		return deferred(obj.getAllEvents());
	}),
	getObjectsSelectedData: d(function (ids, dataMap) {
		var events = [];
		return deferred.map(ids, function (id) {
			var obj = this.db.objects.getById(id);
			if (obj) {
				getBriefDataEvents(obj, dataMap, events);
				return;
			}
			return this.persistentDb.loadObject(id)(function () {
				return getBriefDataEvents(this.db.objects.getById(id), dataMap, events);
			}.bind(this));
		}.bind(this))(events);
	}),
	getCollectionView: d(function (collectionName, initSet, keyPath, filter, sortKeyPath) {
		return this._setupCollectionView(collectionName, initSet, keyPath, filter, sortKeyPath)(
			function (data) {  return data.getResult(); }
		);
	}),
	searchCollectionView: d(function (collectionName, filter) {
		return this._setupCollectionView(collectionName)(function (data) {
			var result = [];
			data.getResult().forEach(function (item) {
				if (filter(this.db.objects.getById(item.id))) result.push(item);
			}, this);
			return result;
		}.bind(this));
	}),
	getCollectionSize: d(function (collectionName, initSet, keyPath, filter) {
		return this._setupCollectionSize(collectionName, initSet, keyPath, filter)(function (data) {
			return data.getResult();
		});
	})
}, memoizeMethods({
	_loadAll: d(function () { return this.persistentDb.loadAll(); }),
	_setupCollection: d(function (collectionName, initSet, keyPath, filter) {
		return this._loadAll()(function () {
			return initSet.filterByKeyPath(keyPath, filter);
		});
	}, { length: 1 }),
	_setupCollectionView: d(function (collectionName, initSet, keyPath, filter, sortKeyPath) {
		return this._setupCollection(collectionName, initSet, keyPath, filter)(function (collection) {
			var compare, keyTokens, resolve;
			if (endsWith.call(sortKeyPath, ':lastModified')) {
				sortKeyPath = sortKeyPath.slice(0, -':lastModified'.length);
				resolve = resolveValueLastModified;
			} else {
				resolve = resolveValue;
			}
			keyTokens = tokenizeKeyPath(sortKeyPath);
			compare = function (a, b) { return resolve(a, keyTokens) - resolve(b, keyTokens); };
			collection = collection.toArray(compare);
			collection.on('change', function () {
				this.emit('collectionview',
					{ value: getCollectionSnapshot(collection, resolve, keyTokens), id: collectionName });
			}.bind(this));
			this.emit('collectionview',
				{ value: getCollectionSnapshot(collection, resolve, keyTokens), id: collectionName });
			return { getResult: function () {
				return getCollectionSnapshot(collection, resolve, keyTokens);
			}, collection: collection };
		});
	}, { length: 1 }),
	_setupCollectionSize: d(function (collectionName, initSet, keyPath, filter) {
		return this._setupCollection(collectionName, initSet, keyPath, filter)(function (collection) {
			var value, stamp;
			collection._size.on('change', function (event) {
				stamp = getStamp();
				value = event.newValue;
				this.persistentDb.storeCustom('_size:' + collectionName, stamp + '.' + value).done();
				this.emit('collectionsize', { value: value, id: collectionName, stamp: stamp });
			}.bind(this));
			return this.persistentDb.getCustom('_size:' + collectionName)(function (value) {
				var index, stamp;
				if (value) {
					index = value.indexOf('.');
					stamp = Number(value.slice(0, index));
					value = Number(value.slice(index + 1));
				}
				if (value !== collection.size) {
					stamp = getStamp();
					value = collection.size;
					this.persistentDb.storeCustom('_size:' + collectionName, stamp + '.' + value).done();
				}
				this.emit('collectionsize', { value: value, id: collectionName, stamp: stamp });
				return { getResult: function () { return { value: value, stamp: stamp }; },
					collection: collection };
			}.bind(this));
		}.bind(this));
	}, { length: 1 })
}))));
<|endoftext|>


<commit_before>/*
 * Jake JavaScript build tool
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

var fs = require('fs')
  , exec = require('child_process').exec
  , utils = require('utilities')
  , currDir = process.cwd()
  , FileList = require('./file_list').FileList;

var NpmPublishTask = function () {
  var args = Array.prototype.slice.call(arguments)
    , arg
    , definition
    , createDef = function (arg) {
        return function () {
          this.packageFiles.include(arg);
        };
      };

  this.name = args.shift();

  while ((arg = args.pop())) {
    if (typeof arg == 'function') {
      definition = arg;
    }
    else if (Array.isArray(arg) || typeof arg == 'string') {
      definition = createDef(arg);
    }
  }

  this.packageFiles = new FileList();
  this.publishCmd = 'npm publish %filename';

  if (typeof definition == 'function') {
    definition.call(this);
  }
  this.define();
};

NpmPublishTask.prototype = new (function () {

  var _currentBranch = null;

  var getPackage = function () {
        var pkg = JSON.parse(fs.readFileSync(process.cwd() + '/package.json').toString());
        return pkg;
      }
    , getPackageVersionNumber = function () {
        return getPackage().version;
      };

  this.define = function () {
    var self = this;

    namespace('npm', function () {
      task('fetchTags', {async: true}, function () {
        // Make sure local tags are up to date
        var cmds = [
          'git fetch --tags'
        ];
        jake.exec(cmds, function () {
          console.log('Fetched remote tags.');
          complete();
        });
      });

      task('getCurrentBranch', {async: true}, function () {
        // Figure out what branch to push to
        exec('git symbolic-ref --short HEAD',
            function (err, stdout, stderr) {
          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }
          if (!stdout) {
            fail(new Error('No current Git branch found'));
          }
          _currentBranch = utils.string.trim(stdout);
          console.log('On branch ' + _currentBranch);
          complete();
        });
      });

      task('version', {async: true}, function () {
        // Only bump, push, and tag if the Git repo is clean
        exec('git status --porcelain --untracked-files=no',
            function (err, stdout, stderr) {
          var cmds
            , path
            , pkg
            , version
            , arr
            , patch
            , message;

          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }
          if (stdout.length) {
            fail(new Error('Git repository is not clean.'));
          }

          // Grab the current version-string
          path = process.cwd() + '/package.json';
          pkg = getPackage();
          version = pkg.version;
          // Increment the patch-number for the version
          arr = version.split('.');
          patch = parseInt(arr.pop(), 10) + 1;
          arr.push(patch);
          version = arr.join('.');
          // New package-version
          pkg.version = version;
          // Commit-message
          message = 'Version ' + version;

          // Update package.json with the new version-info
          fs.writeFileSync(path, JSON.stringify(pkg, true, 2));

          cmds = [
            'git commit package.json -m "' + message + '"'
          , 'git push origin ' + _currentBranch
          , 'git tag -a v' + version + ' -m "' + message + '"'
          , 'git push --tags'
          ];

          jake.exec(cmds, function () {
            var version = getPackageVersionNumber();
            console.log('Bumped version number to v' + version + '.');
            complete();
          });
        });
      });

      task('definePackage', function () {
        var version = getPackageVersionNumber()
          , t;
        t = new jake.PackageTask(self.name, 'v' + version, function () {
          // Replace the PackageTask's FileList with the NPMPublishTask's FileList
          this.packageFiles = self.packageFiles;
          this.needTarGz = true;
        });
      });

      task('package', {async: true}, function () {
        var definePack = jake.Task['npm:definePackage']
          , pack = jake.Task.package
          , version = getPackageVersionNumber();

        // May have already been run
        definePack.reenable(true);
        definePack.addListener('complete', function () {
          pack.addListener('complete', function () {
            console.log('Created package for ' + self.name + ' v' + version);
            complete();
          });
          pack.invoke();
        });
        definePack.invoke();
      });

      task('publish', {async: true}, function () {
        var version = getPackageVersionNumber()
          , cmds
          , filename
          , cmd;

        console.log('Publishing ' + self.name + ' v' + version);

        filename = 'pkg/' + self.name + '-v' + version + '.tar.gz'
        cmd = self.publishCmd.replace(/%filename/gi, filename);

        cmds = [
          cmd
        ];

        // Hackity hack -- NPM publish sometimes returns errror like:
        // Error sending version data\nnpm ERR!
        // Error: forbidden 0.2.4 is modified, should match modified time
        setTimeout(function () {
          jake.exec(cmds, function () {
            console.log('Published to NPM');
            complete();
          }, {stdout: true});
        }, 5000);
      });

      task('cleanup', function () {
        var clobber = jake.Task.clobber;
        clobber.reenable(true);
        clobber.invoke();
        console.log('Cleaned up package');
      });

    });

    desc('Bump version-number, package, and publish to NPM.');
    task('publish', ['npm:fetchTags', 'npm:getCurrentBranch', 'npm:version',
        'npm:package', 'npm:publish', 'npm:cleanup'], function () {});

    jake.Task['npm:definePackage'].invoke();
  };

})();

jake.NpmPublishTask = NpmPublishTask;
exports.NpmPublishTask = NpmPublishTask;

<commit_msg>Print stderr too when publishing to NPM<commit_after>/*
 * Jake JavaScript build tool
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

var fs = require('fs')
  , exec = require('child_process').exec
  , utils = require('utilities')
  , currDir = process.cwd()
  , FileList = require('./file_list').FileList;

var NpmPublishTask = function () {
  var args = Array.prototype.slice.call(arguments)
    , arg
    , definition
    , createDef = function (arg) {
        return function () {
          this.packageFiles.include(arg);
        };
      };

  this.name = args.shift();

  while ((arg = args.pop())) {
    if (typeof arg == 'function') {
      definition = arg;
    }
    else if (Array.isArray(arg) || typeof arg == 'string') {
      definition = createDef(arg);
    }
  }

  this.packageFiles = new FileList();
  this.publishCmd = 'npm publish %filename';

  if (typeof definition == 'function') {
    definition.call(this);
  }
  this.define();
};

NpmPublishTask.prototype = new (function () {

  var _currentBranch = null;

  var getPackage = function () {
        var pkg = JSON.parse(fs.readFileSync(process.cwd() + '/package.json').toString());
        return pkg;
      }
    , getPackageVersionNumber = function () {
        return getPackage().version;
      };

  this.define = function () {
    var self = this;

    namespace('npm', function () {
      task('fetchTags', {async: true}, function () {
        // Make sure local tags are up to date
        var cmds = [
          'git fetch --tags'
        ];
        jake.exec(cmds, function () {
          console.log('Fetched remote tags.');
          complete();
        });
      });

      task('getCurrentBranch', {async: true}, function () {
        // Figure out what branch to push to
        exec('git symbolic-ref --short HEAD',
            function (err, stdout, stderr) {
          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }
          if (!stdout) {
            fail(new Error('No current Git branch found'));
          }
          _currentBranch = utils.string.trim(stdout);
          console.log('On branch ' + _currentBranch);
          complete();
        });
      });

      task('version', {async: true}, function () {
        // Only bump, push, and tag if the Git repo is clean
        exec('git status --porcelain --untracked-files=no',
            function (err, stdout, stderr) {
          var cmds
            , path
            , pkg
            , version
            , arr
            , patch
            , message;

          if (err) {
            fail(err);
          }
          if (stderr) {
            fail(new Error(stderr));
          }
          if (stdout.length) {
            fail(new Error('Git repository is not clean.'));
          }

          // Grab the current version-string
          path = process.cwd() + '/package.json';
          pkg = getPackage();
          version = pkg.version;
          // Increment the patch-number for the version
          arr = version.split('.');
          patch = parseInt(arr.pop(), 10) + 1;
          arr.push(patch);
          version = arr.join('.');
          // New package-version
          pkg.version = version;
          // Commit-message
          message = 'Version ' + version;

          // Update package.json with the new version-info
          fs.writeFileSync(path, JSON.stringify(pkg, true, 2));

          cmds = [
            'git commit package.json -m "' + message + '"'
          , 'git push origin ' + _currentBranch
          , 'git tag -a v' + version + ' -m "' + message + '"'
          , 'git push --tags'
          ];

          jake.exec(cmds, function () {
            var version = getPackageVersionNumber();
            console.log('Bumped version number to v' + version + '.');
            complete();
          });
        });
      });

      task('definePackage', function () {
        var version = getPackageVersionNumber()
          , t;
        t = new jake.PackageTask(self.name, 'v' + version, function () {
          // Replace the PackageTask's FileList with the NPMPublishTask's FileList
          this.packageFiles = self.packageFiles;
          this.needTarGz = true;
        });
      });

      task('package', {async: true}, function () {
        var definePack = jake.Task['npm:definePackage']
          , pack = jake.Task.package
          , version = getPackageVersionNumber();

        // May have already been run
        definePack.reenable(true);
        definePack.addListener('complete', function () {
          pack.addListener('complete', function () {
            console.log('Created package for ' + self.name + ' v' + version);
            complete();
          });
          pack.invoke();
        });
        definePack.invoke();
      });

      task('publish', {async: true}, function () {
        var version = getPackageVersionNumber()
          , cmds
          , filename
          , cmd;

        console.log('Publishing ' + self.name + ' v' + version);

        filename = 'pkg/' + self.name + '-v' + version + '.tar.gz'
        cmd = self.publishCmd.replace(/%filename/gi, filename);

        cmds = [
          cmd
        ];

        // Hackity hack -- NPM publish sometimes returns errror like:
        // Error sending version data\nnpm ERR!
        // Error: forbidden 0.2.4 is modified, should match modified time
        setTimeout(function () {
          jake.exec(cmds, function () {
            console.log('Published to NPM');
            complete();
          }, {printStdout: true, printStderr: true});
        }, 5000);
      });

      task('cleanup', function () {
        var clobber = jake.Task.clobber;
        clobber.reenable(true);
        clobber.invoke();
        console.log('Cleaned up package');
      });

    });

    desc('Bump version-number, package, and publish to NPM.');
    task('publish', ['npm:fetchTags', 'npm:getCurrentBranch', 'npm:version',
        'npm:package', 'npm:publish', 'npm:cleanup'], function () {});

    jake.Task['npm:definePackage'].invoke();
  };

})();

jake.NpmPublishTask = NpmPublishTask;
exports.NpmPublishTask = NpmPublishTask;

<|endoftext|>


<commit_before>var bindings = require('./time');

exports.time = bindings.time;
exports.localtime = bindings.localtime;

// The user-facing 'tzset' function accepts a timezone String
// to set to, and returns an object with the zoneinfo for the
// timezone.
function tzset(tz) {
  if (tz) {
    process.env.TZ = tz;
  }
  var usedTz = process.env.TZ;
  var rtn = bindings.tzset();
  if (!rtn.tzname[1] && rtn.timezone === 0) {
    var err = new Error("Unknown Timezone: '" + usedTz + "'");
    for (var i in rtn) {
      err[i] = rtn[i];
    }
    throw err;
  }
  return rtn;
}
exports.tzset = tzset;

var DateProto = global.Date.prototype;

// The "setTimeZone" function is the "entry point" for a Date instance.
// It must be called after an instance has been created. After, the 'getSeconds()',
// 'getHours()', 'getDays()', etc. functions will return values relative
// to the time zone specified.
function setTimeZone(timezone) {
  var oldTz = process.env.TZ;
  tzset(timezone);
  this._timezone = timezone;
  var zoneInfo = bindings.localtime(this / 1000);
  if (oldTz) {
    tzset(oldTz);
  }

  // If we got to here without throwing an Error, then
  // a valid timezone was requested, and we should have
  // a valid zoneInfo Object.

  // Returns the day of the month (1-31) for the specified date according to local time.
  this.getDate = function getDate() {
    return zoneInfo.dayOfMonth;
  }
  // Returns the day of the week (0-6) for the specified date according to local time.
  this.getDay = function getDay() {
    return zoneInfo.dayOfWeek;
  }
  // Deprecated. Returns the year (usually 2-3 digits) in the specified date according
  // to local time. Use `getFullYear()` instead.
  this.getYear = function getYear() {
    return zoneInfo.year;
  }
  // Returns the year (4 digits for 4-digit years) of the specified date according to local time.
  this.getFullYear = function getFullYear() {
    return zoneInfo.year + 1900;
  }
  // Returns the hour (0-23) in the specified date according to local time.
  this.getHours = function getHours() {
    return zoneInfo.hours;
  }
  // Returns the minutes (0-59) in the specified date according to local time.
  this.getMinutes = function getMinutes() {
    return zoneInfo.minutes;
  }
  // Returns the month (0-11) in the specified date according to local time.
  this.getMonth = function getMonth() {
    return zoneInfo.month;
  }
  // Returns the seconds (0-59) in the specified date according to local time.
  this.getSeconds = function getSeconds() {
    return zoneInfo.seconds;
  }
}
DateProto.setTimeZone = setTimeZone;

// Returns a "String" of the last value set in "setTimeZone".
function getTimeZone() {
  return this._timezone;
}
DateProto.getTimeZone = getTimeZone;
<commit_msg>Export a modified version of the `Date` constructor, in case NODE_MODULE_CONTEXTS is set to true.<commit_after>var bindings = require('./time');

exports.time = bindings.time;
exports.localtime = bindings.localtime;

// The user-facing 'tzset' function accepts a timezone String
// to set to, and returns an object with the zoneinfo for the
// timezone.
function tzset(tz) {
  if (tz) {
    process.env.TZ = tz;
  }
  var usedTz = process.env.TZ;
  var rtn = bindings.tzset();
  if (!rtn.tzname[1] && rtn.timezone === 0) {
    var err = new Error("Unknown Timezone: '" + usedTz + "'");
    for (var i in rtn) {
      err[i] = rtn[i];
    }
    throw err;
  }
  return rtn;
}
exports.tzset = tzset;

var DateProto = global.Date.prototype;

// The "setTimeZone" function is the "entry point" for a Date instance.
// It must be called after an instance has been created. After, the 'getSeconds()',
// 'getHours()', 'getDays()', etc. functions will return values relative
// to the time zone specified.
function setTimeZone(timezone) {
  var oldTz = process.env.TZ;
  tzset(timezone);
  this._timezone = timezone;
  var zoneInfo = bindings.localtime(this / 1000);
  if (oldTz) {
    tzset(oldTz);
  }

  // If we got to here without throwing an Error, then
  // a valid timezone was requested, and we should have
  // a valid zoneInfo Object.

  // Returns the day of the month (1-31) for the specified date according to local time.
  this.getDate = function getDate() {
    return zoneInfo.dayOfMonth;
  }
  // Returns the day of the week (0-6) for the specified date according to local time.
  this.getDay = function getDay() {
    return zoneInfo.dayOfWeek;
  }
  // Deprecated. Returns the year (usually 2-3 digits) in the specified date according
  // to local time. Use `getFullYear()` instead.
  this.getYear = function getYear() {
    return zoneInfo.year;
  }
  // Returns the year (4 digits for 4-digit years) of the specified date according to local time.
  this.getFullYear = function getFullYear() {
    return zoneInfo.year + 1900;
  }
  // Returns the hour (0-23) in the specified date according to local time.
  this.getHours = function getHours() {
    return zoneInfo.hours;
  }
  // Returns the minutes (0-59) in the specified date according to local time.
  this.getMinutes = function getMinutes() {
    return zoneInfo.minutes;
  }
  // Returns the month (0-11) in the specified date according to local time.
  this.getMonth = function getMonth() {
    return zoneInfo.month;
  }
  // Returns the seconds (0-59) in the specified date according to local time.
  this.getSeconds = function getSeconds() {
    return zoneInfo.seconds;
  }
}
Date.prototype.setTimeZone = DateProto.setTimeZone = setTimeZone;

// Returns a "String" of the last value set in "setTimeZone".
function getTimeZone() {
  return this._timezone;
}
Date.prototype.getTimeZone = DateProto.getTimeZone = getTimeZone;

// Export the modified 'Date' instance in case NODE_MODULE_CONTEXTS is set.
exports.Date = Date;
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const Trailpack = require('trailpack')
const lib = require('./lib')

/**
 * trailpack-router
 *
 * Unify all route handlers into a single, standard route object format. Route
 * objects are structured as Hapi.js routes.
 *
 * @see http://hapijs.com/api#route-configuration
 * @see https://github.com/trailsjs/trailpack-hapi
 * @see https://github.com/trailsjs/trailpack-koa
 * @see https://github.com/trailsjs/trailpack-express4
 */
module.exports = class Router extends Trailpack {

  validate () {
    return Promise.all(_.map(this.app.config.routes, lib.Validator.validateRoute))
  }

  configure () {
    this.models = _.mapKeys(_.omit(this.app.api.models, 'inspect'), (model, modelName) => {
      return modelName.toLowerCase()
    })
  }

  /**
   * Merge route configuration and store in app.routes. Trailpacks that wish to
   * extend/add new routes should do so in the configure() lifecycle method.
   *
   * 1. ETL controller handlers into the standard route format.
   *    api.controllers.handlers  --> (map)
   *                              --> [ { controllerId, controllerName, handlerName } ]
   *                              --> (map)
   *                              --> [ { id, method, path, handler } ]
   *               config.routes  --> (group by path + handler)
   *                              --> { routeId: [ { id, method, path, handler } ] }
   *               config.routes  --> (merge each route group)
   *                              --> [ { id, method, path, handler } ]
   *                              --> app.routes
   *
   * 2. Create CRUD Route definition which maps to api.controllers.FootprintController
   *
   *    Operation | Method | Path         | ORM Action
   *    ----------+--------+--------------+------------
   *    Create    | POST   | /model       | .create
   *    Read      | GET    | /model/{id?} | .find
   *    Update    | PUT    | /model/{id?} | .update
   *    Delete    | DELETE | /model/{id?} | .destroy
   *
   * 3. Attach Policies as prerequisites.
   *    @see http://hapijs.com/api#route-prerequisites
   */
  initialize () {
    const footprintRoutes = lib.RouteBuilder.buildFootprintRoutes(this.app.config, this.app.api)
    const allRoutes = lib.RouteBuilder.buildCustomRoutes(this.app.config, footprintRoutes)
    const completedRoutes = lib.RouteBuilder.buildRoutesWithPrerequisites(this.app.config, this.app.api, allRoutes)

    this.app.routes = completedRoutes
  }

  constructor (app) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }
}

<commit_msg>[refactor] inspect omit is no longer necessary<commit_after>'use strict'

const _ = require('lodash')
const Trailpack = require('trailpack')
const lib = require('./lib')

/**
 * trailpack-router
 *
 * Unify all route handlers into a single, standard route object format. Route
 * objects are structured as Hapi.js routes.
 *
 * @see http://hapijs.com/api#route-configuration
 * @see https://github.com/trailsjs/trailpack-hapi
 * @see https://github.com/trailsjs/trailpack-koa
 * @see https://github.com/trailsjs/trailpack-express4
 */
module.exports = class Router extends Trailpack {

  validate () {
    return Promise.all(_.map(this.app.config.routes, lib.Validator.validateRoute))
  }

  configure () {
    this.models = _.mapKeys(this.app.api.models), (model, modelName) => {
      return modelName.toLowerCase()
    })
  }

  /**
   * Merge route configuration and store in app.routes. Trailpacks that wish to
   * extend/add new routes should do so in the configure() lifecycle method.
   *
   * 1. ETL controller handlers into the standard route format.
   *    api.controllers.handlers  --> (map)
   *                              --> [ { controllerId, controllerName, handlerName } ]
   *                              --> (map)
   *                              --> [ { id, method, path, handler } ]
   *               config.routes  --> (group by path + handler)
   *                              --> { routeId: [ { id, method, path, handler } ] }
   *               config.routes  --> (merge each route group)
   *                              --> [ { id, method, path, handler } ]
   *                              --> app.routes
   *
   * 2. Create CRUD Route definition which maps to api.controllers.FootprintController
   *
   *    Operation | Method | Path         | ORM Action
   *    ----------+--------+--------------+------------
   *    Create    | POST   | /model       | .create
   *    Read      | GET    | /model/{id?} | .find
   *    Update    | PUT    | /model/{id?} | .update
   *    Delete    | DELETE | /model/{id?} | .destroy
   *
   * 3. Attach Policies as prerequisites.
   *    @see http://hapijs.com/api#route-prerequisites
   */
  initialize () {
    const footprintRoutes = lib.RouteBuilder.buildFootprintRoutes(this.app.config, this.app.api)
    const allRoutes = lib.RouteBuilder.buildCustomRoutes(this.app.config, footprintRoutes)
    const completedRoutes = lib.RouteBuilder.buildRoutesWithPrerequisites(this.app.config, this.app.api, allRoutes)

    this.app.routes = completedRoutes
  }

  constructor (app) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }
}

<|endoftext|>


<commit_before>'use strict';

var path = require('path');

module.exports = {
	extends: path.join(__dirname, 'base.js'),
	env: {
		es6: true
	},
	parserOptions: {
		ecmaVersion: 6,
		sourceType: 'module'
	},
	rules: {
		// ECMAScript 6
		'arrow-body-style': [2, 'as-needed'],
		'arrow-parens': [2, 'as-needed'],
		'arrow-spacing': [2, { before: true, after: true }],
		'constructor-super': 2,
		'generator-star-spacing': [2, 'after'],
		'no-class-assign': 2,
		'no-confusing-arrow': 2,
		'no-const-assign': 2,
		'no-dupe-class-members': 2,
		'no-new-symbol': 2,
		'no-restricted-imports': 0,
		'no-this-before-super': 2,
		'no-useless-constructor': 2,
		'no-var': 2,
		'object-shorthand': [2, 'always'],
		'prefer-arrow-callback': 2,
		'prefer-const': 0,
		'prefer-reflect': 0,
		'prefer-rest-params': 2,
		'prefer-spread': 2,
		'prefer-template': 2,
		'require-yield': 2,
		'template-curly-spacing': 2,
		'yield-star-spacing': [2, 'after']
	}
};
<commit_msg>ES6 arrow parens<commit_after>'use strict';

var path = require('path');

module.exports = {
	extends: path.join(__dirname, 'base.js'),
	env: {
		es6: true
	},
	parserOptions: {
		ecmaVersion: 6,
		sourceType: 'module'
	},
	rules: {
		// ECMAScript 6
		'arrow-body-style': [2, 'as-needed'],
		'arrow-parens': [2, 'always'],
		'arrow-spacing': [2, { before: true, after: true }],
		'constructor-super': 2,
		'generator-star-spacing': [2, 'after'],
		'no-class-assign': 2,
		'no-confusing-arrow': 2,
		'no-const-assign': 2,
		'no-dupe-class-members': 2,
		'no-new-symbol': 2,
		'no-restricted-imports': 0,
		'no-this-before-super': 2,
		'no-useless-constructor': 2,
		'no-var': 2,
		'object-shorthand': [2, 'always'],
		'prefer-arrow-callback': 2,
		'prefer-const': 0,
		'prefer-reflect': 0,
		'prefer-rest-params': 2,
		'prefer-spread': 2,
		'prefer-template': 2,
		'require-yield': 2,
		'template-curly-spacing': 2,
		'yield-star-spacing': [2, 'after']
	}
};
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import escapeRegExp from 'escape-string-regexp';
import styled from 'styled-components';

import BookList from './BookList';

import type { BookType } from '../common/flowTypes';

const FlybraryShelf = styled.div`padding: 10;`;

const Shelf = (props: {
	title: string,
	books: Array<BookType>,
	filterQuery: string,
	clearQuery: () => void,
	handleShelfUpdate: (BookType, string) => void,
	findShelf: string => string
}) => {
	const {
		books,
		filterQuery,
		clearQuery,
		handleShelfUpdate,
		findShelf
	} = props;
	let showingBooks;

	if (filterQuery) {
		const match = new RegExp(escapeRegExp(filterQuery), 'i');
		showingBooks = books.filter(
			book => match.test(book.title) || match.test(book.subtitle)
		);
	} else {
		showingBooks = books;
	}

	return (
		<FlybraryShelf className="shelf">
			{books.length !== showingBooks.length &&

show all
}

			<BookList
				books={showingBooks}
				handleShelfUpdate={handleShelfUpdate}
				findShelf={findShelf}
			/>
		</FlybraryShelf>
	);
};

export default Shelf;
<commit_msg>fix css error in Shelf styles<commit_after>// @flow

import React from 'react';
import escapeRegExp from 'escape-string-regexp';
import styled from 'styled-components';

import BookList from './BookList';

import type { BookType } from '../common/flowTypes';

const FlybraryShelf = styled.div`padding: 10px;`;

const Shelf = (props: {
	title: string,
	books: Array<BookType>,
	filterQuery: string,
	clearQuery: () => void,
	handleShelfUpdate: (BookType, string) => void,
	findShelf: string => string
}) => {
	const {
		books,
		filterQuery,
		clearQuery,
		handleShelfUpdate,
		findShelf
	} = props;
	let showingBooks;

	if (filterQuery) {
		const match = new RegExp(escapeRegExp(filterQuery), 'i');
		showingBooks = books.filter(
			book => match.test(book.title) || match.test(book.subtitle)
		);
	} else {
		showingBooks = books;
	}

	return (
		<FlybraryShelf className="shelf">
			{books.length !== showingBooks.length &&

show all
}

			<BookList
				books={showingBooks}
				handleShelfUpdate={handleShelfUpdate}
				findShelf={findShelf}
			/>
		</FlybraryShelf>
	);
};

export default Shelf;
<|endoftext|>


<commit_before>var VError, request, async, uri;

VError = require('verror');
request = require('request');
async = require('async');

/**
* @method
* @summary Setups default base uri
*
* @param {String} newUri
*/
exports.configUri = function (newUri) {
  'use strict';

  uri = newUri;
};
<commit_msg>basic driver comunication<commit_after>var VError, httpRequest, async, uri;
VError = require('verror');
httpRequest = require('request');
async = require('async');

exports.configUri = function (newUri) {
  'use strict';

  uri = newUri;
};

function downloadPages(url, next) {
  'use strict';

  var lastPage, results, lastLength;
  results = [];
  lastLength = 0;
  lastPage = 0;
  async.doWhilst(function (next) {
    return httpRequest({
      'url'  : uri + url,
      'json' : true,
      'qs'   : {'page' : lastPage}
    }, function (error, res, body) {
      if (error) {
        return next(error);
      }
      results = results.concat(body);
      lastLength = body.length;
      lastPage++;
      return next();
    });
  }, function () {
    return lastLength > 0;
  }, function (error) {
    return next(error, results);
  });
}

exports.enrollments = function (user, next) {
  'use strict';

  return downloadPages('/users/' + user + '/enrollments', next);
};

exports.enrollment = function (user, id, next) {
  'use strict';

  return httpRequest({
    'url'  : uri + '/users/' + user + '/enrollments/' + id,
    'json' : true
  }, function (error, res, body) {
    next(error, body);
  });
};

exports.requirements = function (user, enrollment, next) {
  'use strict';

  return downloadPages('/users/' + user + '/enrollments/' + enrollment + '/requirements', next);
};

exports.requirement = function (user, enrollment, id, next) {
  'use strict';

  return httpRequest({
    'url'  : uri + '/users/' + user + '/enrollments/' + enrollment + '/requirements/' + id,
    'json' : true
  }, function (error, res, body) {
    next(error, body);
  });
};<|endoftext|>


<commit_before>import React from "react";
import Banner from "./banner";
import Footer from "./footer";

export default class About extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (

              <Banner/>

About Us

My name is Ralph Rookwood and I'm a music producer from Brooklyn, New York. I love to create and arrange music to put smiles and joy onto people's faces. I'm a very simple and understanding type of guy and hope you will feel
                  comfortable with me and my team as we produce great and refreshing music for you.

The Team

Siahh

My name is Siahh and I'm a singer, rapper, songwriter from Brooklyn, New York. My style of music stems from the 90s era: very simplistic, to the point and filled with everlasting messages for my listeners. One listen at a time, I'm hoping to change the opinions of many, especially those of the youth.

Chival

Hey everyone, I'm a composer and musician from West Babylon, New York, and I have a passion for creating great music. The music I create reflects a fusion of several genres, most importantly jazz, electronic, and rock. I believe that good music serves a higher purpose that not only includes engaging the mind but healing the soul and it's my hope that my creations can do that for you.

        )
    }
}<commit_msg>modified about description<commit_after>import React from "react";
import Banner from "./banner";
import Footer from "./footer";

export default class About extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (

              <Banner/>

About Us

My name is Ralph Rookwood and I'm a music producer from Brooklyn, New York. I love to create and arrange music to put smiles and joy onto people's faces. I'm a very simple and understanding type of guy and hope you will feel
                  comfortable with me and my team as we produce great and refreshing music for you.

The Team

Siahh

My name is Siahh and I'm a singer, rapper, songwriter from Brooklyn, New York. My style of music stems from the 90s era: very simplistic, to the point and filled with everlasting messages for my listeners. One listen at a time, I'm hoping to change the opinions of many, especially those of the youth.

Nick

Hey everyone, I'm a composer and musician from West Babylon, New York, and I have a passion for creating great music. The music I create reflects a fusion of several genres, most importantly jazz, electronic, and rock. I believe that good music serves a higher purpose that not only includes engaging the mind but healing the soul and it's my hope that my creations can do that for you.

        )
    }
}<|endoftext|>