<commit_before>/** MIT License (c) copyright B Cavalier & J Hann */

(function (define) {
define(function (require) {
"use strict";

	var methodsToForward, syncProperties, when, map;

	when = require('when');

	map = require('../map');
	syncProperties = require('./syncProperties');

	methodsToForward = ['add', 'remove'];

	/**
	 * Sets up mediation between two collection adapters
	 * @param primary {Object} collection adapter
	 * @param secondary {Object} collection adapter
	 * @param resolver {Function} function (object, type) { returns Adapter; }
	 * @param options {Object} options
	 * @param options.bind if truthy, immediately synchronize data primary
	 *   primary secondary secondary.
	 */
	return function syncCollections (primary, secondary, resolver, options) {

		var itemMap1, itemMap2, mediationHandler1, mediationHandler2,
			watchHandler1, unwatch1, unwatch2;

		if (!options) options = {};

		// if adapter2 wants a keyFunc and doesn't have one, copy it from adapter1
		if ('symbolizer' in secondary && !secondary.symbolizer && primary.symbolizer) {
			secondary.symbolizer = primary.symbolizer;
		}
		// if adapter2 wants a comparator and doesn't have one, copy it from adapter1
		if ('comparator' in secondary && !secondary.comparator && primary.comparator) {
			secondary.comparator = primary.comparator;
		}

		// these maps keep track of items that are being watched
		itemMap1 = map.create({ symbolizer: primary.symbolizer, comparator: primary.comparator });
		itemMap2 = map.create({ symbolizer: secondary.symbolizer, comparator: secondary.comparator });

		// these functions handle any item-to-item mediation
		mediationHandler1 = createItemMediatorHandler(primary, itemMap1, resolver);
		mediationHandler2 = createItemMediatorHandler(secondary, itemMap2, resolver);

		// this function handles property changes that could affect collection order
		watchHandler1 = createItemWatcherHandler(primary, secondary, resolver);

		// TODO: This intitial sync may need to cause other operations to delay
		// until it is complete (which may happen async if secondary is async)
		if (!('sync' in options) || options.sync) {
			primary.forEach(function (item) {
				// watch for item changes
				watchHandler1(item, primary, itemMap1);
				// push item into secondary
				when(secondary.add(item), function(copy) {
					// if secondary returns a copy
					if (copy) {
						mediationHandler1(copy, item, secondary);
					}

					return copy;
				});
			});
		}

		unwatch1 = initForwarding(primary, secondary, mediationHandler1);
		unwatch2 = initForwarding(secondary, primary, mediationHandler2);

		return function () {
			itemMap1.forEach(unwatchItemData);
			itemMap2.forEach(unwatchItemData);
			unwatch1();
			unwatch2();
		};
	};

	function unwatchItemData (data) {
		if (data.unwatch) data.unwatch();
		if (data.unmediate) data.unmediate();
	}

	function createAdapter (object, resolver, type, options) {
		var Adapter = resolver(object, type);
		if (!Adapter) throw new Error('syncCollections: could not find Adapter constructor for ' + type);
		return new Adapter(object, options);
	}

	function createItemWatcherHandler (primary, secondary, resolver) {
		if (typeof primary.checkPosition == 'function' || typeof secondary.checkPosition == 'function') {
			return function watchItem (item, target, itemMap) {
				var itemData;
				itemData = itemMap.get(item);
				if (itemData) {
					// the item was already being watched
					// TODO: do we care?
					if (itemData.unwatch) itemData.unwatch();
				}
				else {
					itemData = itemMap.set(item, {
						adapter: createAdapter(item, resolver, 'object', target.getOptions())
					});
				}
				itemData.unwatch = itemData.adapter.watchAll(function (prop, value) {
					// if primary requires ordering, tell it that the item may have moved
					// TODO: if adapter returned another copy, lose previous copy, adapt this one, and start watching it
					if (typeof primary.checkPosition == 'function') primary.checkPosition(item);
					// if secondary requires ordering, tell it that the item may have moved
					// TODO: if adapter returned another copy, lose previous copy, adapt this one, and start watching it
					if (typeof secondary.checkPosition == 'function') secondary.checkPosition(item);
				});
				return itemData;
			}
		}
		else {
			return noop;
		}
	}

	function createItemMediatorHandler (sender, itemMap, resolver) {
		return function discoverItem (newItem, refItem, target) {
			var itemData, newAdapter;
			itemData = itemMap.get(refItem);
			if (itemData) {
				// the item was already being mediated
				if (itemData.unmediate) itemData.unmediate();
			}
			else {
				itemData = itemMap.set(refItem, {
					adapter: createAdapter(refItem, resolver, 'object', sender.getOptions())
				});
			}
			newAdapter = createAdapter(newItem, resolver, 'object', target.getOptions());
			itemData.unmediate = syncProperties(itemData.adapter, newAdapter);
		}
	}

	function createForwarder (method, discoveryCallback) {
		return function doForward(target, item, index) {
			return when(target[method](item, index),
				function(copy) {
					// if adapter2 returns a copy we need to propagate it
					if (copy) {
						return discoveryCallback(copy, item, target);
					}
				}
			);
		};
	}

	function createCallback (forwarder, to) {
		return function (item, index) {
			return forwarder(to, item, index);
		}
	}

	function initForwarding (from, to, discoveryCallback) {
		var forwarder, callbacks, i, len;

		callbacks = [];
		for (i = 0, len = methodsToForward.length; i < len; i++) {
			forwarder = createForwarder(methodsToForward[i], discoveryCallback);
			callbacks.push(createCallback(forwarder, to));
		}

		return from.watch.apply(from, callbacks);
	}

	function noop () {}

});
}(
	typeof define == 'function'
		? define
		: function (factory) { module.exports = factory(require); }
));
<commit_msg>syncColections expects to be handed an adapterCreator instead of an adapter resolver. wire/cola must be updated too<commit_after>/** MIT License (c) copyright B Cavalier & J Hann */

(function (define) {
define(function (require) {
"use strict";

	var methodsToForward, syncProperties, when, map;

	when = require('when');

	map = require('../map');
	syncProperties = require('./syncProperties');

	methodsToForward = ['add', 'remove'];

	/**
	 * Sets up mediation between two collection adapters
	 * @param primary {Object} collection adapter
	 * @param secondary {Object} collection adapter
	 * @param createAdapter {Function} function (object, type, options) { returns adapter; }
	 * @param options {Object} options
	 * @param options.bind if truthy, immediately synchronize data primary
	 *   primary secondary secondary.
	 */
	return function syncCollections (primary, secondary, createAdapter, options) {

		var itemMap1, itemMap2, mediationHandler1, mediationHandler2,
			watchHandler1, unwatch1, unwatch2;

		if (!options) options = {};

		// if adapter2 wants a keyFunc and doesn't have one, copy it from adapter1
		if ('symbolizer' in secondary && !secondary.symbolizer && primary.symbolizer) {
			secondary.symbolizer = primary.symbolizer;
		}
		// if adapter2 wants a comparator and doesn't have one, copy it from adapter1
		if ('comparator' in secondary && !secondary.comparator && primary.comparator) {
			secondary.comparator = primary.comparator;
		}

		// these maps keep track of items that are being watched
		itemMap1 = map.create({ symbolizer: primary.symbolizer, comparator: primary.comparator });
		itemMap2 = map.create({ symbolizer: secondary.symbolizer, comparator: secondary.comparator });

		// these functions handle any item-to-item mediation
		mediationHandler1 = createItemMediatorHandler(primary, itemMap1, createAdapter, options);
		mediationHandler2 = createItemMediatorHandler(secondary, itemMap2, createAdapter, options);

		// this function handles property changes that could affect collection order
		watchHandler1 = createItemWatcherHandler(primary, secondary, createAdapter);

		// TODO: This intitial sync may need to cause other operations to delay
		// until it is complete (which may happen async if secondary is async)
		if (!('sync' in options) || options.sync) {
			primary.forEach(function (item) {
				// watch for item changes
				watchHandler1(item, primary, itemMap1);
				// push item into secondary
				when(secondary.add(item), function(copy) {
					// if secondary returns a copy
					if (copy) {
						mediationHandler1(copy, item, secondary);
					}

					return copy;
				});
			});
		}

		unwatch1 = initForwarding(primary, secondary, mediationHandler1);
		unwatch2 = initForwarding(secondary, primary, mediationHandler2);

		return function () {
			itemMap1.forEach(unwatchItemData);
			itemMap2.forEach(unwatchItemData);
			unwatch1();
			unwatch2();
		};
	};

	function unwatchItemData (data) {
		if (data.unwatch) data.unwatch();
		if (data.unmediate) data.unmediate();
	}

//	function createAdapter (object, resolver, type, options) {
//		var Adapter = resolver(object, type);
//		if (!Adapter) throw new Error('syncCollections: could not find Adapter constructor for ' + type);
//		return new Adapter(object, options);
//	}

	function createItemWatcherHandler (primary, secondary, createAdapter) {
		if (typeof primary.checkPosition == 'function' || typeof secondary.checkPosition == 'function') {
			return function watchItem (item, target, itemMap) {
				var itemData;
				itemData = itemMap.get(item);
				if (itemData) {
					// the item was already being watched
					// TODO: do we care?
					if (itemData.unwatch) itemData.unwatch();
				}
				else {
					itemData = itemMap.set(item, {
						adapter: createAdapter(item, 'object', target.getOptions())
					});
				}
				itemData.unwatch = itemData.adapter.watchAll(function (prop, value) {
					// if primary requires ordering, tell it that the item may have moved
					// TODO: if adapter returned another copy, lose previous copy, adapt this one, and start watching it
					if (typeof primary.checkPosition == 'function') primary.checkPosition(item);
					// if secondary requires ordering, tell it that the item may have moved
					// TODO: if adapter returned another copy, lose previous copy, adapt this one, and start watching it
					if (typeof secondary.checkPosition == 'function') secondary.checkPosition(item);
				});
				return itemData;
			}
		}
		else {
			return noop;
		}
	}

	function createItemMediatorHandler (sender, itemMap, createAdapter, options) {
		return function discoverItem (newItem, refItem, target) {
			var itemData, newAdapter;
			itemData = itemMap.get(refItem);
			if (itemData) {
				// the item was already being mediated
				if (itemData.unmediate) itemData.unmediate();
			}
			else {
				itemData = itemMap.set(refItem, {
					adapter: createAdapter(refItem, 'object', sender.getOptions())
				});
			}
			newAdapter = createAdapter(newItem, 'object', target.getOptions());
			itemData.unmediate = syncProperties(itemData.adapter, newAdapter, options);
		}
	}

	function createForwarder (method, discoveryCallback) {
		return function doForward(target, item, index) {
			return when(target[method](item, index),
				function(copy) {
					// if adapter2 returns a copy we need to propagate it
					if (copy) {
						return discoveryCallback(copy, item, target);
					}
				}
			);
		};
	}

	function createCallback (forwarder, to) {
		return function (item, index) {
			return forwarder(to, item, index);
		}
	}

	function initForwarding (from, to, discoveryCallback) {
		var forwarder, callbacks, i, len;

		callbacks = [];
		for (i = 0, len = methodsToForward.length; i < len; i++) {
			forwarder = createForwarder(methodsToForward[i], discoveryCallback);
			callbacks.push(createCallback(forwarder, to));
		}

		return from.watch.apply(from, callbacks);
	}

	function noop () {}

});
}(
	typeof define == 'function'
		? define
		: function (factory) { module.exports = factory(require); }
));
<|endoftext|>


<commit_before>import React from 'react';
import ReactDom from 'react-dom';

import Title from 'react-title-component';
import Mousetrap from 'mousetrap';
import GithubCorner from 'react-github-corner';

import Footer from './../Footer/Footer';

export default class Pomodoro extends React.Component {

  constructor() {
    super();
    this.state = {
      time: 0,
      play: false,
      timeType: 0,
      title: ''
    };
    // Bind early, avoid function creation on render loop
    this.setTimeForCode = this.setTime.bind(this, 1500);
    this.setTimeForSocial = this.setTime.bind(this, 300);
    this.setTimeForCoffee = this.setTime.bind(this, 900);
    this.reset = this.reset.bind(this);
    this.play = this.play.bind(this);
    this.elapseTime = this.elapseTime.bind(this);
  }

  componentDidMount() {
    this.setDefaultTime();
    this.startShortcuts();
    Notification.requestPermission();
  }

  elapseTime() {
    if (this.state.time === 0) {
      this.reset(0);
      this.alert();
    }
    if (this.state.play === true) {
      let newState = this.state.time - 1;
      this.setState({time: newState, title: this.getTitle(newState)});
    }
  }

  format(seconds) {
    let m = Math.floor(seconds % 3600 / 60);
    let s = Math.floor(seconds % 3600 % 60);
    let timeFormated = (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
    return timeFormated;
  }

  getFormatTypes() {
    return [
      {type: "code", time: 1500},
      {type: "social", time: 300},
      {type: "coffee", time: 900}
    ];
  }

  formatType(timeType) {
    let timeTypes = this.getFormatTypes();
    for(let i=0; i<timeTypes.length; i++) {
      let timeObj = timeTypes[i];
      if(timeObj.time === timeType) {
        return timeObj.type;
      }
    }
    return null;
  }

  restartInterval() {
    clearInterval(this.interval);
    this.interval = setInterval(this.elapseTime, 1000);
  }

  play() {
    if (true === this.state.play) return;

    this.restartInterval();

    this.setState({
      play: true
    });
  }

  reset(resetFor = this.state.time) {
    clearInterval(this.interval);
    let time = this.format(resetFor);
    this.setState({play: false});
  }

  togglePlay() {
    if (true === this.state.play)
      return this.reset();

    return this.play();
  }

  setTime(newTime) {
    this.restartInterval();

    this.setState({
      time: newTime,
      timeType: newTime,
      title: this.getTitle(newTime),
      play: true
    });
  }

  setDefaultTime() {
    let defaultTime = 1500;

    this.setState({
      time: defaultTime,
      timeType: defaultTime,
      title: this.getTitle(defaultTime),
      play: false
    });
  }

  getTitle(time) {
    time = typeof time === 'undefined' ? this.state.time : time;
    let _title = this.format(time) + ' | Pomodoro timer';
    return _title;
  }

  startShortcuts() {
    Mousetrap.bind('space', this.togglePlay.bind(this));
    Mousetrap.bind(['ctrl+left', 'meta+left'], this.toggleMode.bind(this,-1));
    Mousetrap.bind(['ctrl+right', 'meta+right'], this.toggleMode.bind(this,1));
  }

  toggleMode(gotoDirection) {
    let timeTypes = this.getFormatTypes();
    let currentPosition = -1;

    for (let i = 0; i < timeTypes.length; i++) {
      if (timeTypes[i].time === this.state.timeType) {
        currentPosition = i;
        break;
      };
    };

    if (currentPosition !== -1) {
      let newMode = timeTypes[currentPosition + gotoDirection];
      if (newMode) this.setTime(newMode.time);
    };
  }

  _setLocalStorage (item, element) {
    let value = element.target.checked;
    localStorage.setItem('react-pomodoro-' + item, value);
  }

  _getLocalStorage (item) {
    return (localStorage.getItem('react-pomodoro-' + item) == 'true') ? true : false;
  }

  alert() {
    // vibration
    if(this.refs.vibrate.checked) {
      window.navigator.vibrate(1000);
    }
    // audio
    if(this.refs.audio.checked) {
      let audio = new Audio('songs/alarm.mp3');
      audio.play();
      setTimeout(()=> audio.pause(), 1400);
    }
    // notification
    if(this.refs.notification.checked) {
      if (this.state.timeType === 1500) {
        let notification = new Notification("Relax :)", {
          icon: "img/coffee.png",
          lang: "en",
          body: "Go talk or drink a coffee."
        });
      } else {
        let notification = new Notification("The time is over!", {
          icon: "img/code.png",
          lang: "en",
          body: "Hey, back to code!"
        });
      }
    }
  }

  render() {

    return (

        <GithubCorner
          href="https://github.com/afonsopacifer/react-pomodoro"
          bannerColor="#2BA0A0"
          octoColor="#272727"
        />

        <Title render={this.state.title} />

        {/* Main section
        ------------------------------- */}

            {this.format(this.state.time)}
            The {this.formatType(this.state.timeType)} time!

            <button className="btn code" onClick={this.setTimeForCode}>Code</button>
            <button className="btn social" onClick={this.setTimeForSocial}>Social</button>
            <button className="btn coffee" onClick={this.setTimeForCoffee}>Coffee</button>

              <button className="play btnIcon" onClick={this.play}></button>
              <button className="stop btnIcon" onClick={this.reset}></button>

 {/* main */}

        {/* Bottom section
        ------------------------------- */}

                What is Pomodoro?

                  <input
                    type="checkbox"
                    ref="notification"
                    id="notification"
                    defaultChecked={this._getLocalStorage('notification')}
                    onChange={this._setLocalStorage.bind(this, 'notification')}
                  />

                  Notification

                  <input
                    type="checkbox"
                    ref="audio"
                    id="audio"
                    defaultChecked={this._getLocalStorage('audio')}
                    onChange={this._setLocalStorage.bind(this, 'audio')}
                  />

                  Sound

                  <input
                    type="checkbox"
                    ref="vibrate"
                    id="vibrate"
                    defaultChecked={this._getLocalStorage('vibrate')}
                    onChange={this._setLocalStorage.bind(this, 'vibrate')}
                  />

                  Vibration

 {/* controlsCheck */}

 {/* container */}

 {/* controls */}

 {/* bottomBar */}

 /* bottomBar */
    );
  }
};
<commit_msg>fix classname<commit_after>import React from 'react';
import ReactDom from 'react-dom';

import Title from 'react-title-component';
import Mousetrap from 'mousetrap';
import GithubCorner from 'react-github-corner';

import Footer from './../Footer/Footer';

export default class Pomodoro extends React.Component {

  constructor() {
    super();
    this.state = {
      time: 0,
      play: false,
      timeType: 0,
      title: ''
    };
    // Bind early, avoid function creation on render loop
    this.setTimeForCode = this.setTime.bind(this, 1500);
    this.setTimeForSocial = this.setTime.bind(this, 300);
    this.setTimeForCoffee = this.setTime.bind(this, 900);
    this.reset = this.reset.bind(this);
    this.play = this.play.bind(this);
    this.elapseTime = this.elapseTime.bind(this);
  }

  componentDidMount() {
    this.setDefaultTime();
    this.startShortcuts();
    Notification.requestPermission();
  }

  elapseTime() {
    if (this.state.time === 0) {
      this.reset(0);
      this.alert();
    }
    if (this.state.play === true) {
      let newState = this.state.time - 1;
      this.setState({time: newState, title: this.getTitle(newState)});
    }
  }

  format(seconds) {
    let m = Math.floor(seconds % 3600 / 60);
    let s = Math.floor(seconds % 3600 % 60);
    let timeFormated = (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
    return timeFormated;
  }

  getFormatTypes() {
    return [
      {type: "code", time: 1500},
      {type: "social", time: 300},
      {type: "coffee", time: 900}
    ];
  }

  formatType(timeType) {
    let timeTypes = this.getFormatTypes();
    for(let i=0; i<timeTypes.length; i++) {
      let timeObj = timeTypes[i];
      if(timeObj.time === timeType) {
        return timeObj.type;
      }
    }
    return null;
  }

  restartInterval() {
    clearInterval(this.interval);
    this.interval = setInterval(this.elapseTime, 1000);
  }

  play() {
    if (true === this.state.play) return;

    this.restartInterval();

    this.setState({
      play: true
    });
  }

  reset(resetFor = this.state.time) {
    clearInterval(this.interval);
    let time = this.format(resetFor);
    this.setState({play: false});
  }

  togglePlay() {
    if (true === this.state.play)
      return this.reset();

    return this.play();
  }

  setTime(newTime) {
    this.restartInterval();

    this.setState({
      time: newTime,
      timeType: newTime,
      title: this.getTitle(newTime),
      play: true
    });
  }

  setDefaultTime() {
    let defaultTime = 1500;

    this.setState({
      time: defaultTime,
      timeType: defaultTime,
      title: this.getTitle(defaultTime),
      play: false
    });
  }

  getTitle(time) {
    time = typeof time === 'undefined' ? this.state.time : time;
    let _title = this.format(time) + ' | Pomodoro timer';
    return _title;
  }

  startShortcuts() {
    Mousetrap.bind('space', this.togglePlay.bind(this));
    Mousetrap.bind(['ctrl+left', 'meta+left'], this.toggleMode.bind(this,-1));
    Mousetrap.bind(['ctrl+right', 'meta+right'], this.toggleMode.bind(this,1));
  }

  toggleMode(gotoDirection) {
    let timeTypes = this.getFormatTypes();
    let currentPosition = -1;

    for (let i = 0; i < timeTypes.length; i++) {
      if (timeTypes[i].time === this.state.timeType) {
        currentPosition = i;
        break;
      };
    };

    if (currentPosition !== -1) {
      let newMode = timeTypes[currentPosition + gotoDirection];
      if (newMode) this.setTime(newMode.time);
    };
  }

  _setLocalStorage (item, element) {
    let value = element.target.checked;
    localStorage.setItem('react-pomodoro-' + item, value);
  }

  _getLocalStorage (item) {
    return (localStorage.getItem('react-pomodoro-' + item) == 'true') ? true : false;
  }

  alert() {
    // vibration
    if(this.refs.vibrate.checked) {
      window.navigator.vibrate(1000);
    }
    // audio
    if(this.refs.audio.checked) {
      let audio = new Audio('songs/alarm.mp3');
      audio.play();
      setTimeout(()=> audio.pause(), 1400);
    }
    // notification
    if(this.refs.notification.checked) {
      if (this.state.timeType === 1500) {
        let notification = new Notification("Relax :)", {
          icon: "img/coffee.png",
          lang: "en",
          body: "Go talk or drink a coffee."
        });
      } else {
        let notification = new Notification("The time is over!", {
          icon: "img/code.png",
          lang: "en",
          body: "Hey, back to code!"
        });
      }
    }
  }

  render() {

    return (

        <GithubCorner
          href="https://github.com/afonsopacifer/react-pomodoro"
          bannerColor="#2BA0A0"
          octoColor="#272727"
        />

        <Title render={this.state.title} />

        {/* Main section
        ------------------------------- */}

            {this.format(this.state.time)}
            The {this.formatType(this.state.timeType)} time!

            <button className="btn code" onClick={this.setTimeForCode}>Code</button>
            <button className="btn social" onClick={this.setTimeForSocial}>Social</button>
            <button className="btn coffee" onClick={this.setTimeForCoffee}>Coffee</button>

              <button className="play btnIcon" onClick={this.play}></button>
              <button className="stop btnIcon" onClick={this.reset}></button>

 {/* main */}

        {/* Bottom section
        ------------------------------- */}

                What is Pomodoro?

                  <input
                    type="checkbox"
                    ref="notification"
                    id="notification"
                    defaultChecked={this._getLocalStorage('notification')}
                    onChange={this._setLocalStorage.bind(this, 'notification')}
                  />

                  Notification

                  <input
                    type="checkbox"
                    ref="audio"
                    id="audio"
                    defaultChecked={this._getLocalStorage('audio')}
                    onChange={this._setLocalStorage.bind(this, 'audio')}
                  />

                  Sound

                  <input
                    type="checkbox"
                    ref="vibrate"
                    id="vibrate"
                    defaultChecked={this._getLocalStorage('vibrate')}
                    onChange={this._setLocalStorage.bind(this, 'vibrate')}
                  />

                  Vibration

 {/* controlsCheck */}

 {/* container */}

 {/* controls */}

 {/* bottomBar */}

 /* bottomBar */
    );
  }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Facebook from 'components/SocialLogin/icons/svg/facebook'
import IconButton from 'material-ui/IconButton'
import Instagram from 'components/SocialLogin/icons/svg/instagram'
import Pinterest from 'components/SocialLogin/icons/svg/pinterest'
import YouTube from 'components/SocialLogin/icons/svg/youtube'
import Twitter from 'components/SocialLogin/icons/svg/twitter'

const styles = {
  smallIcon: {
    width: 36,
    height: 36
  },
  small: {
    width: 72,
    height: 72,
    padding: 16
  }
}

export default class SocialLinks extends Component {

  render() {
    return (

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Facebook color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Twitter color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <YouTube color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Instagram color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Pinterest color='white' hoverColor='black' />
          </IconButton>

    )
  }
}
<commit_msg>change socialLinks order<commit_after>import React, { Component } from 'react'
import Facebook from 'components/SocialLogin/icons/svg/facebook'
import IconButton from 'material-ui/IconButton'
import Instagram from 'components/SocialLogin/icons/svg/instagram'
import Pinterest from 'components/SocialLogin/icons/svg/pinterest'
import YouTube from 'components/SocialLogin/icons/svg/youtube'
import Twitter from 'components/SocialLogin/icons/svg/twitter'

const styles = {
  smallIcon: {
    width: 36,
    height: 36
  },
  small: {
    width: 72,
    height: 72,
    padding: 16
  }
}

export default class SocialLinks extends Component {

  render() {
    return (

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Instagram color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Facebook color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Pinterest color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <Twitter color='white' hoverColor='black' />
          </IconButton>

          <IconButton
            iconStyle={styles.smallIcon}
            style={styles.small}
          >
            <YouTube color='white' hoverColor='black' />
          </IconButton>

    )
  }
}
<|endoftext|>


<commit_before>import Ember from "ember";
import AjaxPromise from '../utils/ajax-promise';
import config from '../config/environment';

export default Ember.Component.extend({
  tagName: "input",
  type:    "file",
  accept:  "image/*",
  name:    "file",
  classNames: ["cloudinary-fileupload", "hidden"],
  "data-cloudinary-field": "image_upload",
  "data-url": config.APP.CLOUD_URL,
  disabled: true,
  attributeBindings: [ "name", "type", "value", "data-cloudinary-field",
    "data-url", "data-form-data", "disabled", "style", "accept", "offerId"],
  alert: Ember.inject.service(),
  offerId: null,
  i18n: Ember.inject.service(),

  didInsertElement: function() {
    var _this = this;

    // https://github.com/blueimp/jQuery-File-Upload/wiki/Options
    var options = {
      dataType: 'json',
      timeout: 60000,// 1 minute
      imageMaxHeight: 800,
      imageMaxWidth: 800,
      disableImageResize: false,

      fail: function() {
        if(this.type !== "file") {
          this.get("alert").show(this.get("i18n").t('upload-image.upload_error'));
        }
      }
    };

    // forward cloudinary events
    ["submit","progress","always","fail","done"].forEach(ev => {
      if (this[ev]) {
        options[ev] = (e, data) => Ember.run(() => this.sendAction(ev, e, data));
      }
    });

    var reqData = this.get("offerId") ? { tags: "offer_" + this.get("offerId") } : {};
    new AjaxPromise("/images/generate_signature", "GET", this.get('session.authToken'), reqData)
      .then(function(data) {
        Ember.$(_this.element)
          .attr("data-form-data", JSON.stringify(data))
          .cloudinary_fileupload(options);
        _this.set("disabled", false);
        _this.sendAction("ready");
      });
  }
});
<commit_msg>fixed ember-error 'calling set on destroyed object' while visiting offer-details and item pages<commit_after>import Ember from "ember";
import AjaxPromise from '../utils/ajax-promise';
import config from '../config/environment';

export default Ember.Component.extend({
  tagName: "input",
  type:    "file",
  accept:  "image/*",
  name:    "file",
  classNames: ["cloudinary-fileupload", "hidden"],
  "data-cloudinary-field": "image_upload",
  "data-url": config.APP.CLOUD_URL,
  disabled: true,
  attributeBindings: [ "name", "type", "value", "data-cloudinary-field",
    "data-url", "data-form-data", "disabled", "style", "accept", "offerId"],
  alert: Ember.inject.service(),
  offerId: null,
  i18n: Ember.inject.service(),

  didInsertElement: function() {
    var _this = this;

    // https://github.com/blueimp/jQuery-File-Upload/wiki/Options
    var options = {
      dataType: 'json',
      timeout: 60000,// 1 minute
      imageMaxHeight: 800,
      imageMaxWidth: 800,
      disableImageResize: false,

      fail: function() {
        if(this.type !== "file") {
          this.get("alert").show(this.get("i18n").t('upload-image.upload_error'));
        }
      }
    };

    // forward cloudinary events
    ["submit","progress","always","fail","done"].forEach(ev => {
      if (this[ev]) {
        options[ev] = (e, data) => Ember.run(() => this.sendAction(ev, e, data));
      }
    });

    var reqData = this.get("offerId") ? { tags: "offer_" + this.get("offerId") } : {};
    new AjaxPromise("/images/generate_signature", "GET", this.get('session.authToken'), reqData)
      .then(function(data) {
        if ( !(_this.get('isDestroyed') || _this.get('isDestroying')) ) {
          Ember.$(_this.element)
            .attr("data-form-data", JSON.stringify(data))
            .cloudinary_fileupload(options);
          _this.set("disabled", false);
          _this.sendAction("ready");
        }
      });
  }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router'
import { Image, Segment, Header, Grid, List, Label, Rating, Comment, Form, Icon, Button, Modal } from 'semantic-ui-react';

import ModalEditEvent from './modal-edit-event';

import axios from 'axios';

const styles = {
  image: {
    // marginTop: '-10%'
  },
  background: {
    backgroundColor:"rgb(247, 247, 247)"
  },
  label: {
    marginTop: '2px'
  },
  column: {
    paddingTop: '.5rem',
    paddingBottom: '.5rem'
  },
  row: {
    paddingTop: 0,
    paddingBottom: 0
  }
};

export default class IndividualEvent extends Component {

  renderInterestedUsers() {
    if(!this.state.eventInfo.interested) {
      return null;
    }
    return this.state.eventInfo.interested.map((user) => {
      return (
        <List.Item key={user.user_id}>
          <Image avatar src={user.image_path}/>
          <List.Content>
            <List.Header
              as={Link} to={'/students/' + user.user_id} >
              {user.first_name + ' ' + user.last_name}
            </List.Header>
          </List.Content>
        </List.Item>
      );
    })
  }

  renderDetails() {
    if(!this.state.eventInfo) {
      return null;
    }
    const { association_name, start_date, end_date, start_time, end_time, room, registration_link } = this.state.eventInfo;
    return (
      <List>
        <List.Item
          icon='users'
          content={association_name} />
        <List.Item
          icon='wait'
          content={start_time + ' - ' + end_time} />
        <List.Item
          icon='calendar'
          content={start_date + ((start_date === end_date) ? '': ' - ' + end_date)} />
        <List.Item
          icon='marker'
          content={room} />
        {(registration_link === '')? null:
          <List.Item
            icon='linkify'
            content={Registration} />
        }
        <Modal trigger={<Button color="teal">Entrance Fee</Button>}>
    <Modal.Header style={{backgroundColor:"rgb(35, 37, 40)", color:"white"}}>Event Payment <Icon name="payment"></Icon></Modal.Header>
    <Modal.Content>
      <Form>

        <Form.Group widths="equal">
           <Form.Input label='Credit Card Number' name='creditCard'
             placeholder='Card Number' />
           <Form.Input label="Expiration Date" name='expirationDate'
             placeholder='MM/YYYY'/>
           <Form.Input label="Security Code (CCV)" name="securityCode"
             placeholder="123"></Form.Input>
         </Form.Group>

       <Form.Group widths="equal">
         <Form.Input label="First Name" name="firstName" placeholder="First Name"/>
         <Form.Input label="Last Name" name="lastName" placeholder="Last Name"/>
       </Form.Group>

       <Form.Input label="Billing Address" name="addressLine1"
         placeholder="Address Line 1"/>
       <Form.Input name="addressLine2"
         placeholder="Address Line 2"/>

       <Form.Group widths="equal">
         <Form.Input label="City" name="city" placeholder="City"/>
         <Form.Input label="State" name="state" placeholder="State"/>
       </Form.Group>

       <Form.Group widths="equal">
         <Form.Input label="Post Code" name="postCode" placeholder="Post Code"/>
         <Form.Select label="Country" name="country"/>
       </Form.Group>

      </Form>
      <Modal.Description>
        Proceed to Checkout
      </Modal.Description>
    </Modal.Content>
    <Modal.Actions style={{backgroundColor:"rgb(35, 37, 40)", color:"white"}}>
      <Button primary>
        Proceed <Icon name='right chevron' />
      </Button>
    </Modal.Actions>
  </Modal>
      </List>
    );
  }

  renderCategories() {
    if(!this.state.eventInfo.categories) {
      return null;
    }
    console.log(this.state.eventInfo.categories);
    return this.state.eventInfo.categories.map((cat) => {
      return (

      );
    });
  }

  renderUpdates() {
    if(!this.state.eventInfo.updates) {
      return null;
    }
    return this.state.eventInfo.updates.map((update) => {
      const { notification_id, notification_name, notification_text, date_sent } = update;
      return (
        <Comment key={notification_id}>
          <Comment.Avatar src={this.state.eventInfo.image_path} />
          <Comment.Content>
            <Comment.Author as='span'>{notification_name}</Comment.Author>
            <Comment.Metadata>
              {date_sent}
            </Comment.Metadata>
            <Comment.Text>
              {notification_text}
            </Comment.Text>
          </Comment.Content>
        </Comment>
      );
    });
  }

  renderReviews() {
    if(!this.state.eventInfo.reviews) {
      return null;
    }
    return this.state.eventInfo.reviews.map((reviews) => {
      const { review_id, first_name, last_name, image_path, review, date_created, rating, user_id } = reviews;
      return (
        <Comment key={review_id}>
          <Comment.Avatar src={image_path} />
          <Comment.Content>
            <Comment.Author as={Link} to={'/students/' + user_id}>{first_name + ' ' + last_name}</Comment.Author>
            <Comment.Metadata>
              {date_created}
            </Comment.Metadata>
            <Comment.Text>
              <Rating icon='star' defaultRating={rating} maxRating={5} />

              {review}
            </Comment.Text>
          </Comment.Content>
        </Comment>
      );
    })
  }

  constructor () {
    super();
    this.state = {eventInfo: {}};
  }
  componentWillMount() {
    const tick = this;
    // Get Events Data to render
    axios.get('/api/event/'+this.props.params.eventID)
    .then(function (response) {
      console.log(response);
      const temp = response.data;
      // temp.interested = interested;
      // temp.categories = eventCategories;
      // temp.updates = updates;
      // temp.reviews = reviews;
      temp.associationImage = "/images/defaults/default-profile.jpg";
      tick.setState({eventInfo: temp})
    })
    .catch(function (error) {
      console.log(error);
      tick.setState(
        {
          eventInfo:{
          name: "Hackathon",
          id: "1",
          associationName: "HackPR",
          associationId: "45239847",
          image: "http://hack.pr/wp-content/uploads/2016/09/Facebook-Banner-HackPR-1.png",
          startDate: "Oct. 15, 2016",
          endDate: "Oct. 16, 2016",
          startTime: "9:00 am",
          endTime: "5:00 pm",
          location: "Roberto Clemente",
          description: "HackPR 2016 is the perfect \
            meeting place for the hacker and technology innovation \
            community in Puerto Rico. Join us as a student or \
            professional hacker to win more than {'5k'} in prizes or \
            as a  visitors to participate in our job fair, \
            exhibitors area, workshops and final hacks (projects) \
            presentation at the end of the event. ",
          registrationLink:"google.com",
          interested: interested,
          categories: eventCategories,
          updates: updates,
          reviews: reviews,
          associationImage: "/images/defaults/default-profile.jpg"
        }
      })
    });
  }

  render(){
    return (

        <Grid padded>
          <Grid.Row style={styles.row}>
            <Grid.Column style={styles.column} >
              <Segment>
                <Image
                  src={this.state.eventInfo.image_path}
                  size='big'
                  style={{width:"90%", marginTop:10, marginBottom:10}}
                  bordered
                  centered/>
              </Segment>
            </Grid.Column>
          </Grid.Row>
          <Grid.Row style={styles.row} verticalAlign='bottom'>
            <Grid.Column width={16} style={styles.column}>

                  {this.state.eventInfo.event_name} {' '}
                  <ModalEditEvent eventInfo={this.state.eventInfo} />

                {this.renderCategories()}

              <Segment attached>
                {this.state.eventInfo.description}
              </Segment>
            </Grid.Column>
          </Grid.Row>
          <Grid.Row style={styles.row}>
            <Grid.Column  computer={11} tablet={11} mobile={16} stretched>
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="red"name='announcement'/>
                      Updates

                  <Segment attached>
                    <Comment.Group>
                      {this.renderUpdates()}
                    </Comment.Group>
                  </Segment>
                </Grid.Column>
              </Grid.Row>
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="blue"name='comments'/>
                      Reviews
                      <Rating icon='star' defaultRating={3} maxRating={5} />

                  <Segment attached>
                    <Comment.Group>
                      {this.renderReviews()}
                    </Comment.Group>
                  </Segment>
                </Grid.Column>
              </Grid.Row>
            </Grid.Column>
            <Grid.Column computer={5} tablet={5} mobile={16} >
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="teal"name='search' />
                      Details

                  <Segment attached>
                    {this.renderDetails()}
                  </Segment>
                </Grid.Column>
              </Grid.Row>
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="yellow"name='users'/>
                      Interested

                  <Segment attached>
                    <List>
                      {this.renderInterestedUsers()}
                    </List>
                  </Segment>
                </Grid.Column>
              </Grid.Row>
            </Grid.Column>
          </Grid.Row>
        </Grid>

    );
  }
}

const updates = [
  {
    id: 1,
    title: 'Title of the Update',
    text: 'Update 1',
    timestamp: 'Time'
  },
  {
    id: 2,
    title: 'Title of the Update',
    text: 'Update 2',
    timestamp: 'Time'
  },
  {
    id: 3,
    title: 'Title of the Update',
    text: 'Update 3',
    timestamp: 'Time'
  },
  {
    id: 4,
    title: 'Title of the Update',
    text: 'Update 4',
    timestamp: 'Time'
  }
];

const reviews = [
  {
    id: 1,
    firstName: 'Joe',
    lastName: 'Doe',
    image: 'http://semantic-ui.com/images/avatar/small/joe.jpg',
    comment: 'Thats Pretty Good!',
    timestamp: 'Time',
    stars: 5,
    userId: 1
  },
  {
    id: 2,
    firstName: 'Christian',
    lastName: 'Hendrix',
    image: 'http://semantic-ui.com/images/avatar/small/christian.jpg',
    comment: 'It was aight...',
    timestamp: 'Time',
    stars: 3,
    userId: 2
  },
  {
    id: 3,
    firstName: 'Jenny',
    lastName: 'Murphy',
    image: 'http://semantic-ui.com/images/avatar/small/jenny.jpg',
    comment: 'It suuucked!',
    timestamp: 'Time',
    stars: 0,
    userId: 3
  }
];

const interested = [
  {
    firstName: 'Maria',
    lastName: 'Jimenez',
    image: 'http://semantic-ui.com/images/avatar/small/helen.jpg',
    id: 1
  },
  {
    firstName: 'John',
    lastName: 'Doe',
    image: 'http://semantic-ui.com/images/avatar/small/daniel.jpg',
    id: 2,
  },
  {
    firstName: 'Joe',
    lastName: 'Doe',
    image: 'http://semantic-ui.com/images/avatar/small/joe.jpg',
    id: 3
  },
  {
    firstName: 'Elliot',
    lastName: 'Fu',
    image: 'http://semantic-ui.com/images/avatar/small/elliot.jpg',
    id: 4
  },
  {
    firstName: 'Paola',
    lastName: 'Xiau',
    image: 'http://semantic-ui.com/images/avatar/small/stevie.jpg',
    id: 5
  },
  {
    firstName: 'Christian',
    lastName: 'Hendrix',
    image: 'http://semantic-ui.com/images/avatar/small/christian.jpg',
    id: 6
  },
  {
    firstName: 'Jenny',
    lastName: 'Murphy',
    image: 'http://semantic-ui.com/images/avatar/small/jenny.jpg',
    id: 7
  }
];

const eventCategories = [
  'Food',
  'Music',
  'Fundraiser',
  'Arts',
  'Social',
  'Educational',
  'Business',
  'Sports',
  'Competition',
  'Other'
];

const categories = {
  Food: {
    color: 'red',
    icon: 'food'// food or spoon
  },
  Music: {
    color: 'blue',
    icon: 'music'// music or unmute or sound
  },
  Fundraiser: {
    color: 'violet',
    icon: 'ticket' // ticket or money
  },
  Arts: {
    color: 'teal',
    icon: 'paint brush'
  },
  Social: {
    color: 'green',
    icon: 'users'
  },
  Educational: {
    color: 'orange',
    icon: 'student' // student or book
  },
  Business: {
    color: 'yellow',
    icon: 'travel'
  },
  Sports: {
    color: 'grey',
    icon: 'soccer'
  },
  Competition: {
    color: 'purple',
    icon: 'trophy'
  },
  Other: {
    color: 'olive',
    icon: 'idea'
  }
};
<commit_msg>Made the segment of Updates and Reviews of the  events-individual page act different if the event does not have a single review or update.<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router'
import { Image, Segment, Header, Grid, List, Label, Rating, Comment, Form, Icon, Button, Modal } from 'semantic-ui-react';

import ModalEditEvent from './modal-edit-event';

import axios from 'axios';

const styles = {
  image: {
    // marginTop: '-10%'
  },
  background: {
    backgroundColor:"rgb(247, 247, 247)"
  },
  label: {
    marginTop: '2px'
  },
  column: {
    paddingTop: '.5rem',
    paddingBottom: '.5rem'
  },
  row: {
    paddingTop: 0,
    paddingBottom: 0
  }
};

export default class IndividualEvent extends Component {

  renderInterestedUsers() {
    if(!this.state.eventInfo.interested) {
      return null;
    }
    return this.state.eventInfo.interested.map((user) => {
      return (
        <List.Item key={user.user_id}>
          <Image avatar src={user.image_path}/>
          <List.Content>
            <List.Header
              as={Link} to={'/students/' + user.user_id} >
              {user.first_name + ' ' + user.last_name}
            </List.Header>
          </List.Content>
        </List.Item>
      );
    })
  }

  renderDetails() {
    if(!this.state.eventInfo) {
      return null;
    }
    const { association_name, start_date, end_date, start_time, end_time, room, registration_link } = this.state.eventInfo;
    return (
      <List>
        <List.Item
          icon='users'
          content={association_name} />
        <List.Item
          icon='wait'
          content={start_time + ' - ' + end_time} />
        <List.Item
          icon='calendar'
          content={start_date + ((start_date === end_date) ? '': ' - ' + end_date)} />
        <List.Item
          icon='marker'
          content={room} />
        {(registration_link === '')? null:
          <List.Item
            icon='linkify'
            content={Registration} />
        }
        <Modal trigger={<Button color="teal">Entrance Fee</Button>}>
    <Modal.Header style={{backgroundColor:"rgb(35, 37, 40)", color:"white"}}>Event Payment <Icon name="payment"></Icon></Modal.Header>
    <Modal.Content>
      <Form>

        <Form.Group widths="equal">
           <Form.Input label='Credit Card Number' name='creditCard'
             placeholder='Card Number' />
           <Form.Input label="Expiration Date" name='expirationDate'
             placeholder='MM/YYYY'/>
           <Form.Input label="Security Code (CCV)" name="securityCode"
             placeholder="123"></Form.Input>
         </Form.Group>

       <Form.Group widths="equal">
         <Form.Input label="First Name" name="firstName" placeholder="First Name"/>
         <Form.Input label="Last Name" name="lastName" placeholder="Last Name"/>
       </Form.Group>

       <Form.Input label="Billing Address" name="addressLine1"
         placeholder="Address Line 1"/>
       <Form.Input name="addressLine2"
         placeholder="Address Line 2"/>

       <Form.Group widths="equal">
         <Form.Input label="City" name="city" placeholder="City"/>
         <Form.Input label="State" name="state" placeholder="State"/>
       </Form.Group>

       <Form.Group widths="equal">
         <Form.Input label="Post Code" name="postCode" placeholder="Post Code"/>
         <Form.Select label="Country" name="country"/>
       </Form.Group>

      </Form>
      <Modal.Description>
        Proceed to Checkout
      </Modal.Description>
    </Modal.Content>
    <Modal.Actions style={{backgroundColor:"rgb(35, 37, 40)", color:"white"}}>
      <Button primary>
        Proceed <Icon name='right chevron' />
      </Button>
    </Modal.Actions>
  </Modal>
      </List>
    );
  }

  renderCategories() {
    if(!this.state.eventInfo.categories) {
      return null;
    }
    console.log(this.state.eventInfo.categories);
    return this.state.eventInfo.categories.map((cat) => {
      return (

      );
    });
  }

  renderUpdates() {
    if(!this.state.eventInfo.updates) {
      return null;
    }
    return this.state.eventInfo.updates.map((update) => {
      const { notification_id, notification_name, notification_text, date_sent } = update;
      return (
        <Comment key={notification_id}>
          <Comment.Avatar src={this.state.eventInfo.image_path} />
          <Comment.Content>
            <Comment.Author as='span'>{notification_name}</Comment.Author>
            <Comment.Metadata>
              {date_sent}
            </Comment.Metadata>
            <Comment.Text>
              {notification_text}
            </Comment.Text>
          </Comment.Content>
        </Comment>
      );
    });
  }

  renderReviews() {
    if(!this.state.eventInfo.reviews) {
      return null;
    }
    return this.state.eventInfo.reviews.map((reviews) => {
      const { review_id, first_name, last_name, image_path, review, date_created, rating, user_id } = reviews;
      return (
        <Comment key={review_id}>
          <Comment.Avatar src={image_path} />
          <Comment.Content>
            <Comment.Author as={Link} to={'/students/' + user_id}>{first_name + ' ' + last_name}</Comment.Author>
            <Comment.Metadata>
              {date_created}
            </Comment.Metadata>
            <Comment.Text>
              <Rating icon='star' defaultRating={rating} maxRating={5} />

              {review}
            </Comment.Text>
          </Comment.Content>
        </Comment>
      );
    })
  }

  constructor () {
    super();
    this.state = {eventInfo: {}};
  }
  componentWillMount() {
    const tick = this;
    // Get Events Data to render
    axios.get('/api/event/'+this.props.params.eventID)
    .then(function (response) {
      console.log(response);
      const temp = response.data;
      // temp.interested = interested;
      // temp.categories = eventCategories;
      // temp.updates = updates;
      // temp.reviews = reviews;
      temp.associationImage = "/images/defaults/default-profile.jpg";
      tick.setState({eventInfo: temp})
    })
    .catch(function (error) {
      console.log(error);
      tick.setState(
        {
          eventInfo:{
          name: "Hackathon",
          id: "1",
          associationName: "HackPR",
          associationId: "45239847",
          image: "http://hack.pr/wp-content/uploads/2016/09/Facebook-Banner-HackPR-1.png",
          startDate: "Oct. 15, 2016",
          endDate: "Oct. 16, 2016",
          startTime: "9:00 am",
          endTime: "5:00 pm",
          location: "Roberto Clemente",
          description: "HackPR 2016 is the perfect \
            meeting place for the hacker and technology innovation \
            community in Puerto Rico. Join us as a student or \
            professional hacker to win more than {'5k'} in prizes or \
            as a  visitors to participate in our job fair, \
            exhibitors area, workshops and final hacks (projects) \
            presentation at the end of the event. ",
          registrationLink:"google.com",
          interested: interested,
          categories: eventCategories,
          updates: updates,
          reviews: reviews,
          associationImage: "/images/defaults/default-profile.jpg"
        }
      })
    });
  }

  render(){
    if(!this.state.eventInfo.reviews)
      return null;
    return (

        <Grid padded>
          <Grid.Row style={styles.row}>
            <Grid.Column style={styles.column} >
              <Segment>
                <Image
                  src={this.state.eventInfo.image_path}
                  size='big'
                  style={{width:"90%", marginTop:10, marginBottom:10}}
                  bordered
                  centered/>
              </Segment>
            </Grid.Column>
          </Grid.Row>
          <Grid.Row style={styles.row} verticalAlign='bottom'>
            <Grid.Column width={16} style={styles.column}>

                  {this.state.eventInfo.event_name} {' '}
                  <ModalEditEvent eventInfo={this.state.eventInfo} />

                {this.renderCategories()}

              <Segment attached>
                {this.state.eventInfo.description}
              </Segment>
            </Grid.Column>
          </Grid.Row>
          <Grid.Row style={styles.row}>
            <Grid.Column  computer={11} tablet={11} mobile={16} stretched>
              { this.state.eventInfo.reviews.length === 0 ? null:
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="red"name='announcement'/>
                      Updates

                  <Segment attached>
                    <Comment.Group>
                      {this.renderUpdates()}
                    </Comment.Group>
                  </Segment>
                </Grid.Column>
              </Grid.Row>
              }
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="blue"name='comments'/>
                      Reviews
                      <Rating icon='star' defaultRating={3} maxRating={5} />

                  <Segment attached>
                    { this.state.eventInfo.reviews.length === 0 ?
                      There are no reviews yet. Be the first one to write a review.:
                    <Comment.Group>
                      {this.renderReviews()}
                    </Comment.Group>
                    }
                  </Segment>
                </Grid.Column>
              </Grid.Row>
            </Grid.Column>
            <Grid.Column computer={5} tablet={5} mobile={16} >
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="teal"name='search' />
                      Details

                  <Segment attached>
                    {this.renderDetails()}
                  </Segment>
                </Grid.Column>
              </Grid.Row>
              <Grid.Row style={styles.row}>
                <Grid.Column width={16} style={styles.column}>

                      <Icon color="yellow"name='users'/>
                      Interested

                  <Segment attached>
                    <List>
                      {this.renderInterestedUsers()}
                    </List>
                  </Segment>
                </Grid.Column>
              </Grid.Row>
            </Grid.Column>
          </Grid.Row>
        </Grid>

    );
  }
}

const updates = [
  {
    id: 1,
    title: 'Title of the Update',
    text: 'Update 1',
    timestamp: 'Time'
  },
  {
    id: 2,
    title: 'Title of the Update',
    text: 'Update 2',
    timestamp: 'Time'
  },
  {
    id: 3,
    title: 'Title of the Update',
    text: 'Update 3',
    timestamp: 'Time'
  },
  {
    id: 4,
    title: 'Title of the Update',
    text: 'Update 4',
    timestamp: 'Time'
  }
];

const reviews = [
  {
    id: 1,
    firstName: 'Joe',
    lastName: 'Doe',
    image: 'http://semantic-ui.com/images/avatar/small/joe.jpg',
    comment: 'Thats Pretty Good!',
    timestamp: 'Time',
    stars: 5,
    userId: 1
  },
  {
    id: 2,
    firstName: 'Christian',
    lastName: 'Hendrix',
    image: 'http://semantic-ui.com/images/avatar/small/christian.jpg',
    comment: 'It was aight...',
    timestamp: 'Time',
    stars: 3,
    userId: 2
  },
  {
    id: 3,
    firstName: 'Jenny',
    lastName: 'Murphy',
    image: 'http://semantic-ui.com/images/avatar/small/jenny.jpg',
    comment: 'It suuucked!',
    timestamp: 'Time',
    stars: 0,
    userId: 3
  }
];

const interested = [
  {
    firstName: 'Maria',
    lastName: 'Jimenez',
    image: 'http://semantic-ui.com/images/avatar/small/helen.jpg',
    id: 1
  },
  {
    firstName: 'John',
    lastName: 'Doe',
    image: 'http://semantic-ui.com/images/avatar/small/daniel.jpg',
    id: 2,
  },
  {
    firstName: 'Joe',
    lastName: 'Doe',
    image: 'http://semantic-ui.com/images/avatar/small/joe.jpg',
    id: 3
  },
  {
    firstName: 'Elliot',
    lastName: 'Fu',
    image: 'http://semantic-ui.com/images/avatar/small/elliot.jpg',
    id: 4
  },
  {
    firstName: 'Paola',
    lastName: 'Xiau',
    image: 'http://semantic-ui.com/images/avatar/small/stevie.jpg',
    id: 5
  },
  {
    firstName: 'Christian',
    lastName: 'Hendrix',
    image: 'http://semantic-ui.com/images/avatar/small/christian.jpg',
    id: 6
  },
  {
    firstName: 'Jenny',
    lastName: 'Murphy',
    image: 'http://semantic-ui.com/images/avatar/small/jenny.jpg',
    id: 7
  }
];

const eventCategories = [
  'Food',
  'Music',
  'Fundraiser',
  'Arts',
  'Social',
  'Educational',
  'Business',
  'Sports',
  'Competition',
  'Other'
];

const categories = {
  Food: {
    color: 'red',
    icon: 'food'// food or spoon
  },
  Music: {
    color: 'blue',
    icon: 'music'// music or unmute or sound
  },
  Fundraiser: {
    color: 'violet',
    icon: 'ticket' // ticket or money
  },
  Arts: {
    color: 'teal',
    icon: 'paint brush'
  },
  Social: {
    color: 'green',
    icon: 'users'
  },
  Educational: {
    color: 'orange',
    icon: 'student' // student or book
  },
  Business: {
    color: 'yellow',
    icon: 'travel'
  },
  Sports: {
    color: 'grey',
    icon: 'soccer'
  },
  Competition: {
    color: 'purple',
    icon: 'trophy'
  },
  Other: {
    color: 'olive',
    icon: 'idea'
  }
};
<|endoftext|>


<commit_before>/*global define*/
define([
        './defaultValue',
        './DeveloperError',
        './Math',
        './Matrix3',
        './Matrix4',
        './Cartesian2',
        './Cartesian3',
        './Cartesian4',
        './TimeConstants',
        './Ellipsoid'
    ],
    function(
        defaultValue,
        DeveloperError,
        CesiumMath,
        Matrix3,
        Matrix4,
        Cartesian2,
        Cartesian3,
        Cartesian4,
        TimeConstants,
        Ellipsoid) {
    "use strict";

    var EarthOrientationData = {

            eop : [],

            clear : function(){
                EarthOrientationData.eop = [];
            },

            computeOrientationParameters : function (dateTai){

                //if(this.eop.length !== 0){
                    //return EarthOrientationData.eop[0];
//                }
//                else {
                    return new EarthOrientationData.OrientationParameterData(0,0,0,0,0);
//                }
            },

            OrientationParameterData : function(xVal, yVal, ut1MinusUtc, xPoleOffset, yPoleOffset){
                this.xPoleWander = xVal;
                this.yPoleWander = yVal;
                this.ut1MinusUtc = ut1MinusUtc;
                this.xPoleOffset = xPoleOffset;
                this.yPoleOffset = yPoleOffset;
                //this.lengthOfDayCorrection
                //this.deltaPsiCorrection
                //this.deltaEpsilonCorrection
            }
    };

    return EarthOrientationData;
});<commit_msg>Fix failing ICRF tests.<commit_after>/*global define*/
define([
        './defaultValue',
        './DeveloperError',
        './Math',
        './Matrix3',
        './Matrix4',
        './Cartesian2',
        './Cartesian3',
        './Cartesian4',
        './TimeConstants',
        './Ellipsoid'
    ],
    function(
        defaultValue,
        DeveloperError,
        CesiumMath,
        Matrix3,
        Matrix4,
        Cartesian2,
        Cartesian3,
        Cartesian4,
        TimeConstants,
        Ellipsoid) {
    "use strict";

    var EarthOrientationData = {

            eop : [],

            clear : function(){
                EarthOrientationData.eop = [];
            },

            computeOrientationParameters : function (dateTai){

                if (EarthOrientationData.eop.length !== 0){
                    return EarthOrientationData.eop[0];
                } else {
                    return new EarthOrientationData.OrientationParameterData(0,0,0,0,0);
                }
            },

            OrientationParameterData : function(xVal, yVal, ut1MinusUtc, xPoleOffset, yPoleOffset){
                this.xPoleWander = xVal;
                this.yPoleWander = yVal;
                this.ut1MinusUtc = ut1MinusUtc;
                this.xPoleOffset = xPoleOffset;
                this.yPoleOffset = yPoleOffset;
                //this.lengthOfDayCorrection
                //this.deltaPsiCorrection
                //this.deltaEpsilonCorrection
            }
    };

    return EarthOrientationData;
});<|endoftext|>


<commit_before>// Copyright (C) 2014 Erik Ringsmuth <erik.ringsmuth@gmail.com>
define(function(require) {
  'use strict';
  var config = require('config'),
      Ractive = require('Ractive'),
      xhrPanelTemplate = require('rv!./xhrPanelTemplate'),
      sequence = require('components/apiSequence/sequence'),
      utilities = require('components/util/utilities'),
      prettify = require('prettify'),
      URI = require('bower_components/URIjs/src/URI'),
      vkbeautify = require('vkbeautify'),
      $ = require('jquery');
  require('Ractive-transitions-slide');

  var XhrPanel = Ractive.extend({
    template: xhrPanelTemplate,

    el: '#api-sequence-placeholder',

    append: true,

    // prototype
    data: {
      id: null,
      isPublic: true,
      headers: '',
      body: '',
      corsEnabled: false,
      depricated: false,
      callCount: 0,
      forkedFrom: null,

      // State
      starred: false,
      signedIn: config.session.signedIn,
      responseBody: '',
      showOptions: false,
      saveButtonClass: 'default',
      sendButtonClass: 'default',
      sendButtonDisabled: false,
      showMoreButton: false,
      fullScreen: false,
      formatNumber: function(number) {
        return number.toLocaleString();
      },
      formatDate: function(date) {
        var d = new Date(date);
        return d.getFullYear() + '-' + d.getMonth() + '-' + d.getDay() + ' ' + d.getHours() + ':' + d.getMinutes();
      }
    },

    init: function() {
      // non-prototype defaults
      this.set('panelId', utilities.guid());
      if (typeof(this.get('name')) === 'undefined') this.set('name', 'XHR');
      if (typeof(this.get('method')) === 'undefined') this.set('method', 'GET');
      if (typeof(this.get('url')) === 'undefined') this.set('url', 'http://www.suri.io/');
      if (typeof(this.get('headerOptions')) === 'undefined') this.set('headerOptions', []);
      if (typeof(this.get('queryParameterOptions')) === 'undefined') this.set('queryParameterOptions', []);
      if (typeof(this.get('tags')) === 'undefined') this.set('tags', []);
      if (typeof(this.get('stars')) === 'undefined') this.set('stars', []);
      if (typeof(this.get('forks')) === 'undefined') this.set('forks', []);
      if (typeof(this.get('owner')) === 'undefined') this.set('owner', config.session.userId);
      this.set('isOwner', !this.get('id') || config.session.userId === this.get('owner'));
      if (this.get('stars').indexOf(config.session.userId) !== -1) {
        this.set('starred', true);
      }

      sequence.add(this);

      this.on({
        // All panels
        teardown: function teardown(event) {
          this.detach();
          sequence.remove(this);
          if (event && event.original && event.original.stopPropagation) {
            event.original.stopPropagation();
          }
        },

        toggleOptions: function() {
          this.set('showOptions', !this.get('showOptions'));
          this.fire('setupTooltips');
        },

        setupTooltips: function() {
          $('.bs-tooltip').tooltip();
        },

        scrollToPanel: function scrollToPanel() {
          $('html,body').animate({
            scrollTop: document.getElementById(this.get('panelId')).offsetTop + $('#api-sequence').offset().top - 15
          }, 200, 'easeOutQuint');
        },

        sendOnEnter: function sendOnEnter(event) {
          if (event.original.keyCode === 13) {
            this.fire('send');
          }
        },

        toggleFullscreen: function() {
          this.set('fullScreen', !this.get('fullScreen'));
        },

        send: function send() {
          // Clear and disable send button
          this.set('sendButtonClass', 'default');
          this.set('sendButtonDisabled', true);

          // Parse the raw header text
          var headerLines = this.get('headers').split('\n');
          if (headerLines.length === 1 && headerLines[0].trim() === '') {
            headerLines = []; // because callling split on an empty string returns ['']
          }
          var headers = {};
          for (var i = 0; i < headerLines.length; i++) {
            var headerParts = headerLines[i].split(':');
            var header = headerParts[0].trim();
            if (header) {
              headers[header] = headerParts.splice(1).join(':').trim();
            }
          }

          // Increment the call count locally, this gets set server-side by the api-id header
          this.set('callCount', this.get('callCount') + 1);
          headers['api-id'] = this.get('id');

          // Make sure URL the protocol is included otherwise default to HTTP
          var url = this.get('url');
          if (url.indexOf('://') === -1) {
            url = 'http://' + url;
          }
          var apiUri = new URI(url);
          var suriHost = new URI(window.location.href).host();
          if (!this.get('corsEnabled') && apiUri.host() !== suriHost) {
            // Proxy through the suri.io server
            headers['api-host'] = apiUri.protocol() + '://' + apiUri.authority();
            apiUri.authority(suriHost);
            apiUri.protocol(window.location.protocol); // Suri doesn't support HTTPS yet
          }

          // Send the request
          $.ajax({
            type: this.get('method'),
            url: apiUri,
            headers: headers,
            data: this.get('body')
          })
          .done(function(data, textStatus, jqXHR) {
            this.fire('displayResponse', jqXHR);
          }.bind(this))
          .fail(function(jqXHR) {
            this.fire('displayResponse', jqXHR);
          }.bind(this));
        },

        displayResponse: function displayResponse(jqXHR) {
          // update send button
          this.set('sendButtonDisabled', false);
          if (jqXHR.status >= 200 && jqXHR.status < 300) {
            this.set('sendButtonClass', 'success');
          } else {
            this.set('sendButtonClass', 'danger');
          }

          // headers
          this.set('responseHeaders', 'HTTP/1.1 ' + jqXHR.status + ' ' + jqXHR.statusText + '\n' + jqXHR.getAllResponseHeaders());

          // body
          this.set('responseBody', '');

          if (typeof(jqXHR.responseJSON) !== 'undefined') {
            // JSON
            this.set('responseBody', utilities.escape(JSON.stringify(jqXHR.responseJSON, null, 2)));
          }
          else if (typeof(jqXHR.responseXML) !== 'undefined') {
            // XML
            this.set('responseBody', utilities.escape(vkbeautify.xml(new XMLSerializer().serializeToString(jqXHR.responseXML), 2)));
          }
          else {
            var contentType = jqXHR.getResponseHeader('content-type');
            if (contentType && contentType.indexOf('javascript') !== -1) {
              // This could still be JSON, Google does this :P
              var parsedResponse;
              try {
                parsedResponse = JSON.stringify(JSON.parse(jqXHR.responseText), null, 2);
              } catch (e) {
                parsedResponse = jqXHR.responseText;
              }
              this.set('responseBody', utilities.escape(parsedResponse));
            }
            else {
              // Plain text, html, or something
              this.set('responseBody', utilities.escape(jqXHR.responseText));
            }
          }

          if (this.get('responseBody').length > 3000) {
            this.nodes.responseBody.innerHTML = prettify.prettyPrintOne(this.get('responseBody').substring(0, 3000));
            this.set('showMoreButton', true);
          } else {
            this.fire('displayEntireResponse');
          }
        },

        displayEntireResponse: function displayEntireResponse() {
          this.nodes.responseBody.innerHTML = prettify.prettyPrintOne(this.get('responseBody'));
          this.set('showMoreButton', false);
        },

        fork: function() {
          var fork = new XhrPanel({data: this.data});
          fork.set('id', null);
          fork.set('isOwner', true);
          fork.set('owner', config.session.userId);
          fork.set('callCount', 0);
          fork.set('forks', []);
          fork.set('forkedFrom', this.get('id'));
          fork.fire('save');
          this.data.forks.push(''); // increment the forks count, this is faking out what's happening server side
        },

        save: function() {
          this.set('saveButtonClass', 'default');

          if (!this.get('signedIn')) return;

          if (this.get('id')) {
            // update
            $.ajax('/xhr/' + this.get('id'), {
              type: 'PUT',
              contentType: 'application/json',
              data: JSON.stringify(this.data)
            })
              .done(function() {
                this.set('saveButtonClass', 'success');
              }.bind(this))
              .fail(function() {
                this.set('saveButtonClass', 'danger');
              }.bind(this));
          }
          else {
            // save
            $.ajax('/xhr', {
              type: 'POST',
              contentType: 'application/json',
              data: JSON.stringify(this.data)
            })
              .done(function(data) {
                this.set('saveButtonClass', 'success');
                this.set('id', data._id);
              }.bind(this))
              .fail(function() {
                this.set('saveButtonClass', 'danger');
              }.bind(this));
          }
        },

        delete: function() {
          if (!this.get('id')) {
            // This was never saved, remove the panel
            this.teardown();
          } else {
            $.ajax('/xhr/' + this.get('id'), {
              type: 'DELETE'
            })
              .done(function() {
                this.teardown();
              }.bind(this));
          }
        },

        star: function() {
          if (this.get('starred')) {
            // Unstar
            $.ajax('/xhr/' + this.get('id') + '/stars/' + config.session.userId, {
              method: 'DELETE'
            })
              .done(function() {
                this.data.stars.splice(sequence.indexOf(config.session.userId), 1);
                this.set('starred', false);
              }.bind(this));
          } else {
            // Star
            $.ajax('/xhr/' + this.get('id') + '/stars', {
              method: 'POST',
              data: config.session.userId
            })
              .done(function() {
                this.data.stars.push(config.session.userId);
                this.set('starred', true);
              }.bind(this));
          }
        },

        addTagOnEnter: function(event) {
          if (event.original.keyCode === 13) {
            var tag = event.node.value.replace(/\s/g, '').toLowerCase();
            if (this.get('tags').indexOf(tag) === -1) {
              this.get('tags').push(tag);
              event.node.value = '';
            }
          }
        },

        deleteTag: function(event, tag) {
          this.get('tags').splice(this.get('tags').indexOf(tag), 1);
        }
      });

      // Scroll to the panel when it's created
      this.fire('scrollToPanel');
      this.fire('setupTooltips');
    }
  });

  return XhrPanel;
});
<commit_msg>prevent default when deleting a tag<commit_after>// Copyright (C) 2014 Erik Ringsmuth <erik.ringsmuth@gmail.com>
define(function(require) {
  'use strict';
  var config = require('config'),
      Ractive = require('Ractive'),
      xhrPanelTemplate = require('rv!./xhrPanelTemplate'),
      sequence = require('components/apiSequence/sequence'),
      utilities = require('components/util/utilities'),
      prettify = require('prettify'),
      URI = require('bower_components/URIjs/src/URI'),
      vkbeautify = require('vkbeautify'),
      $ = require('jquery');
  require('Ractive-transitions-slide');

  var XhrPanel = Ractive.extend({
    template: xhrPanelTemplate,

    el: '#api-sequence-placeholder',

    append: true,

    // prototype
    data: {
      id: null,
      isPublic: true,
      headers: '',
      body: '',
      corsEnabled: false,
      depricated: false,
      callCount: 0,
      forkedFrom: null,

      // State
      starred: false,
      signedIn: config.session.signedIn,
      responseBody: '',
      showOptions: false,
      saveButtonClass: 'default',
      sendButtonClass: 'default',
      sendButtonDisabled: false,
      showMoreButton: false,
      fullScreen: false,
      formatNumber: function(number) {
        return number.toLocaleString();
      },
      formatDate: function(date) {
        var d = new Date(date);
        return d.getFullYear() + '-' + d.getMonth() + '-' + d.getDay() + ' ' + d.getHours() + ':' + d.getMinutes();
      }
    },

    init: function() {
      // non-prototype defaults
      this.set('panelId', utilities.guid());
      if (typeof(this.get('name')) === 'undefined') this.set('name', 'XHR');
      if (typeof(this.get('method')) === 'undefined') this.set('method', 'GET');
      if (typeof(this.get('url')) === 'undefined') this.set('url', 'http://www.suri.io/');
      if (typeof(this.get('headerOptions')) === 'undefined') this.set('headerOptions', []);
      if (typeof(this.get('queryParameterOptions')) === 'undefined') this.set('queryParameterOptions', []);
      if (typeof(this.get('tags')) === 'undefined') this.set('tags', []);
      if (typeof(this.get('stars')) === 'undefined') this.set('stars', []);
      if (typeof(this.get('forks')) === 'undefined') this.set('forks', []);
      if (typeof(this.get('owner')) === 'undefined') this.set('owner', config.session.userId);
      this.set('isOwner', !this.get('id') || config.session.userId === this.get('owner'));
      if (this.get('stars').indexOf(config.session.userId) !== -1) {
        this.set('starred', true);
      }

      sequence.add(this);

      this.on({
        // All panels
        teardown: function teardown(event) {
          this.detach();
          sequence.remove(this);
          if (event && event.original && event.original.stopPropagation) {
            event.original.stopPropagation();
          }
        },

        toggleOptions: function() {
          this.set('showOptions', !this.get('showOptions'));
          this.fire('setupTooltips');
        },

        setupTooltips: function() {
          $('.bs-tooltip').tooltip();
        },

        scrollToPanel: function scrollToPanel() {
          $('html,body').animate({
            scrollTop: document.getElementById(this.get('panelId')).offsetTop + $('#api-sequence').offset().top - 15
          }, 200, 'easeOutQuint');
        },

        sendOnEnter: function sendOnEnter(event) {
          if (event.original.keyCode === 13) {
            this.fire('send');
          }
        },

        toggleFullscreen: function() {
          this.set('fullScreen', !this.get('fullScreen'));
        },

        send: function send() {
          // Clear and disable send button
          this.set('sendButtonClass', 'default');
          this.set('sendButtonDisabled', true);

          // Parse the raw header text
          var headerLines = this.get('headers').split('\n');
          if (headerLines.length === 1 && headerLines[0].trim() === '') {
            headerLines = []; // because callling split on an empty string returns ['']
          }
          var headers = {};
          for (var i = 0; i < headerLines.length; i++) {
            var headerParts = headerLines[i].split(':');
            var header = headerParts[0].trim();
            if (header) {
              headers[header] = headerParts.splice(1).join(':').trim();
            }
          }

          // Increment the call count locally, this gets set server-side by the api-id header
          this.set('callCount', this.get('callCount') + 1);
          headers['api-id'] = this.get('id');

          // Make sure URL the protocol is included otherwise default to HTTP
          var url = this.get('url');
          if (url.indexOf('://') === -1) {
            url = 'http://' + url;
          }
          var apiUri = new URI(url);
          var suriHost = new URI(window.location.href).host();
          if (!this.get('corsEnabled') && apiUri.host() !== suriHost) {
            // Proxy through the suri.io server
            headers['api-host'] = apiUri.protocol() + '://' + apiUri.authority();
            apiUri.authority(suriHost);
            apiUri.protocol(window.location.protocol); // Suri doesn't support HTTPS yet
          }

          // Send the request
          $.ajax({
            type: this.get('method'),
            url: apiUri,
            headers: headers,
            data: this.get('body')
          })
          .done(function(data, textStatus, jqXHR) {
            this.fire('displayResponse', jqXHR);
          }.bind(this))
          .fail(function(jqXHR) {
            this.fire('displayResponse', jqXHR);
          }.bind(this));
        },

        displayResponse: function displayResponse(jqXHR) {
          // update send button
          this.set('sendButtonDisabled', false);
          if (jqXHR.status >= 200 && jqXHR.status < 300) {
            this.set('sendButtonClass', 'success');
          } else {
            this.set('sendButtonClass', 'danger');
          }

          // headers
          this.set('responseHeaders', 'HTTP/1.1 ' + jqXHR.status + ' ' + jqXHR.statusText + '\n' + jqXHR.getAllResponseHeaders());

          // body
          this.set('responseBody', '');

          if (typeof(jqXHR.responseJSON) !== 'undefined') {
            // JSON
            this.set('responseBody', utilities.escape(JSON.stringify(jqXHR.responseJSON, null, 2)));
          }
          else if (typeof(jqXHR.responseXML) !== 'undefined') {
            // XML
            this.set('responseBody', utilities.escape(vkbeautify.xml(new XMLSerializer().serializeToString(jqXHR.responseXML), 2)));
          }
          else {
            var contentType = jqXHR.getResponseHeader('content-type');
            if (contentType && contentType.indexOf('javascript') !== -1) {
              // This could still be JSON, Google does this :P
              var parsedResponse;
              try {
                parsedResponse = JSON.stringify(JSON.parse(jqXHR.responseText), null, 2);
              } catch (e) {
                parsedResponse = jqXHR.responseText;
              }
              this.set('responseBody', utilities.escape(parsedResponse));
            }
            else {
              // Plain text, html, or something
              this.set('responseBody', utilities.escape(jqXHR.responseText));
            }
          }

          if (this.get('responseBody').length > 3000) {
            this.nodes.responseBody.innerHTML = prettify.prettyPrintOne(this.get('responseBody').substring(0, 3000));
            this.set('showMoreButton', true);
          } else {
            this.fire('displayEntireResponse');
          }
        },

        displayEntireResponse: function displayEntireResponse() {
          this.nodes.responseBody.innerHTML = prettify.prettyPrintOne(this.get('responseBody'));
          this.set('showMoreButton', false);
        },

        fork: function() {
          var fork = new XhrPanel({data: this.data});
          fork.set('id', null);
          fork.set('isOwner', true);
          fork.set('owner', config.session.userId);
          fork.set('callCount', 0);
          fork.set('forks', []);
          fork.set('forkedFrom', this.get('id'));
          fork.fire('save');
          this.data.forks.push(''); // increment the forks count, this is faking out what's happening server side
        },

        save: function() {
          this.set('saveButtonClass', 'default');

          if (!this.get('signedIn')) return;

          if (this.get('id')) {
            // update
            $.ajax('/xhr/' + this.get('id'), {
              type: 'PUT',
              contentType: 'application/json',
              data: JSON.stringify(this.data)
            })
              .done(function() {
                this.set('saveButtonClass', 'success');
              }.bind(this))
              .fail(function() {
                this.set('saveButtonClass', 'danger');
              }.bind(this));
          }
          else {
            // save
            $.ajax('/xhr', {
              type: 'POST',
              contentType: 'application/json',
              data: JSON.stringify(this.data)
            })
              .done(function(data) {
                this.set('saveButtonClass', 'success');
                this.set('id', data._id);
              }.bind(this))
              .fail(function() {
                this.set('saveButtonClass', 'danger');
              }.bind(this));
          }
        },

        delete: function() {
          if (!this.get('id')) {
            // This was never saved, remove the panel
            this.teardown();
          } else {
            $.ajax('/xhr/' + this.get('id'), {
              type: 'DELETE'
            })
              .done(function() {
                this.teardown();
              }.bind(this));
          }
        },

        star: function() {
          if (this.get('starred')) {
            // Unstar
            $.ajax('/xhr/' + this.get('id') + '/stars/' + config.session.userId, {
              method: 'DELETE'
            })
              .done(function() {
                this.data.stars.splice(sequence.indexOf(config.session.userId), 1);
                this.set('starred', false);
              }.bind(this));
          } else {
            // Star
            $.ajax('/xhr/' + this.get('id') + '/stars', {
              method: 'POST',
              data: config.session.userId
            })
              .done(function() {
                this.data.stars.push(config.session.userId);
                this.set('starred', true);
              }.bind(this));
          }
        },

        addTagOnEnter: function(event) {
          if (event.original.keyCode === 13) {
            var tag = event.node.value.replace(/\s/g, '').toLowerCase();
            if (this.get('tags').indexOf(tag) === -1) {
              this.get('tags').push(tag);
              event.node.value = '';
            }
          }
        },

        deleteTag: function(event, tag) {
          this.get('tags').splice(this.get('tags').indexOf(tag), 1);
          event.original.preventDefault();
        }
      });

      // Scroll to the panel when it's created
      this.fire('scrollToPanel');
      this.fire('setupTooltips');
    }
  });

  return XhrPanel;
});
<|endoftext|>


<commit_before>'use strict'
const Promise = require('bluebird')
const config = require('../server/init/configuration')
const log = require('../server/init/logging')
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()

const {addDescription} = require('message-type')
const handleMessage = require('./handleMessage')
require('colors')
const {Client: AMQPClient, Policy} = require('amqp10')
const urlencode = require('urlencode')
const client = new AMQPClient(Policy.Utils.RenewOnSettle(1, 1, Policy.ServiceBusQueue))

function start () {
  return client.connect(`amqps://${config.full.azure.SharedAccessKeyName}:${urlencode(config.secure.azure.SharedAccessKey)}@${config.full.azure.host}`)
    .then(() => client.createReceiver(config.secure.azure.queueName || config.full.azure.queueName))
    .then(receiver => {
      log.info('receiver created....')

      receiver.on('errorReceived', err => log.warn('An error occured when trying to receive message from queue', err))

      receiver.on('message', message => {
        log.info('New message from ug queue', message)

        Promise.resolve(message)
        .then(initLogger)
        .then(() => {
          if (message.body) {
            return _processMessage(message)
          } else {
            log.info('Message is empty or undefined, deleting from queue...', message)
            return receiver.accept(message)
          }
        })
        .then(() => {
          // Init logger without settings from this message
          initLogger()
        })
      })

      function _processMessage (MSG) {
        let result
        return Promise.resolve(MSG.body)
        .then(addDescription)
        .then(handleMessage)
        .then(_result => {
          log.info('result from handleMessage', _result)
          result = _result
        })
        .then(() => receiver.accept(MSG))
        .then(() => eventEmitter.emit('messageProcessed', MSG, result))
        .catch(e => {
          log.error(e)
          log.info('Error Occured, releaseing message back to queue...', MSG)
          return receiver.modify(MSG, {undeliverableHere: false, deliveryFailed: true})
        })
      }

      return receiver
    })
}

function initLogger (msg) {
  let config
  if (msg) {
    const {body} = msg
    config = {
      kthid: body && body.kthid,
      ug1Name: body && body.ug1Name,
      ugversion: (msg && msg.applicationProperties && msg.applicationProperties.UGVersion) || undefined,
      messageId: (msg && msg.properties && msg.properties.messageId) || undefined
    }
  } else {
    config = {}
  }

  log.init(config)

  return msg && msg.body
}

module.exports = {
  start, eventEmitter
}
<commit_msg>minor spelling<commit_after>'use strict'
const Promise = require('bluebird')
const config = require('../server/init/configuration')
const log = require('../server/init/logging')
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()

const {addDescription} = require('message-type')
const handleMessage = require('./handleMessage')
require('colors')
const {Client: AMQPClient, Policy} = require('amqp10')
const urlencode = require('urlencode')
const client = new AMQPClient(Policy.Utils.RenewOnSettle(1, 1, Policy.ServiceBusQueue))

function start () {
  return client.connect(`amqps://${config.full.azure.SharedAccessKeyName}:${urlencode(config.secure.azure.SharedAccessKey)}@${config.full.azure.host}`)
    .then(() => client.createReceiver(config.secure.azure.queueName || config.full.azure.queueName))
    .then(receiver => {
      log.info('receiver created....')

      receiver.on('errorReceived', err => log.warn('An error occured when trying to receive message from queue', err))

      receiver.on('message', message => {
        log.info('New message from ug queue', message)

        Promise.resolve(message)
        .then(initLogger)
        .then(() => {
          if (message.body) {
            return _processMessage(message)
          } else {
            log.info('Message is empty or undefined, deleting from queue...', message)
            return receiver.accept(message)
          }
        })
        .then(() => {
          // Init logger without settings from this message
          initLogger()
        })
      })

      function _processMessage (MSG) {
        let result
        return Promise.resolve(MSG.body)
        .then(addDescription)
        .then(handleMessage)
        .then(_result => {
          log.info('result from handleMessage', _result)
          result = _result
        })
        .then(() => receiver.accept(MSG))
        .then(() => eventEmitter.emit('messageProcessed', MSG, result))
        .catch(e => {
          log.error(e)
          log.info('Error Occured, releasing message back to queue...', MSG)
          return receiver.modify(MSG, {undeliverableHere: false, deliveryFailed: true})
        })
      }

      return receiver
    })
}

function initLogger (msg) {
  let config
  if (msg) {
    const {body} = msg
    config = {
      kthid: body && body.kthid,
      ug1Name: body && body.ug1Name,
      ugversion: (msg && msg.applicationProperties && msg.applicationProperties.UGVersion) || undefined,
      messageId: (msg && msg.properties && msg.properties.messageId) || undefined
    }
  } else {
    config = {}
  }

  log.init(config)

  return msg && msg.body
}

module.exports = {
  start, eventEmitter
}
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createStructuredSelector } from 'reselect';

import Header from 'containers/Header';
import makeSelectAddBookPage from './selectors';
import Search from './Search';
import { searchRequest } from './actions';

export class AddBookPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  render() {
    return (

        <Helmet
          title="AddBookPage"
          meta={[
            { name: 'description', content: 'Description of AddBookPage' },
          ]}
        />

          <Search search={this.props.searchRequest} />

    );
  }
}

AddBookPage.propTypes = {
  location: PropTypes.object,
  searchRequest: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  AddBookPage: makeSelectAddBookPage(),
});

function mapDispatchToProps(dispatch) {
  return {
    searchRequest: (payload) => dispatch(searchRequest(payload)),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(AddBookPage);
<commit_msg>Add styles and propvalidation to AddBookPage<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createStructuredSelector } from 'reselect';
import { Row, Col } from 'react-bootstrap';

import Header from 'containers/Header';
import Title from 'components/Title';
import Card from 'components/Card';
import makeSelectAddBookPage from './selectors';
import Search from './Search';
import { searchRequest } from './actions';

export class AddBookPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  render() {
    return (

        <Helmet
          title="AddBookPage"
          meta={[
            { name: 'description', content: 'Description of AddBookPage' },
          ]}
        />

          <Title>Search for Your Book</Title>
          <Row>
            <Col xs={12} xsOffset={0} sm={6} smOffset={3} md={4} mdOffset={4} >
              <Search search={this.props.searchRequest} />
            </Col>
          </Row>
          {this.props.AddBookPage.books ?
            <Card>
              <Row>
              </Row>
            </Card> :
            null
          }

    );
  }
}

AddBookPage.propTypes = {
  location: PropTypes.object,
  searchRequest: PropTypes.func.isRequired,
  AddBookPage: PropTypes.shape({
    searching: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
    error: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
    books: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
    selectedBook: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
  }),
};

const mapStateToProps = createStructuredSelector({
  AddBookPage: makeSelectAddBookPage(),
});

function mapDispatchToProps(dispatch) {
  return {
    searchRequest: (payload) => dispatch(searchRequest(payload)),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(AddBookPage);
<|endoftext|>