<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { get } from 'lodash';

import loadEntities from '../../commons/redux/util/loadEntities';

import ProductListItems from '../components/ProductListItems';

import { ApiAction } from '../redux/actions';
const { loadProducts } = ApiAction;

const Home = React.createClass({
  propTypes: {
    products: PropTypes.array,
    categories: PropTypes.object.isRequired,
    loadProducts: PropTypes.func.isRequired,
  },
  contextTypes: {
    activeLocale: PropTypes.string,
    activeCurrency: PropTypes.string,
  },
  getInitialState() {
    return {};
  },
  componentDidMount() {
    this.props.loadProducts();
    $('.main-banner').owlCarousel({ autoPlay: 10000, items: 1 });
    $('.center-slide').owlCarousel({ autoPlay: 10000, items: 1 });
  },
  render() {
    const { products = [] } = this.props;
    const { activeCurrency, activeLocale } = this.context;
    const renderCurationTopic = () => {
      const linkItems = [
        { link: '/products', text: 'Fall Dresses', colorNum: 0 },
        { link: '/products', text: 'Casual Dresses', colorNum: 1 },
        { link: '/products', text: 'Cardigans', colorNum: 0 },
        { link: '/products', text: 'Summer Dresses', colorNum: 1 },
        { link: '/products', text: 'Blazers', colorNum: 0 },
        { link: '/products', text: 'Jumpsuits', colorNum: 0 },
        { link: '/products', text: 'Blouses & Shirts', colorNum: 1 },
        { link: '/products', text: 'T-Shirts', colorNum: 0 },
        { link: '/products', text: 'Sunglasses', colorNum: 1 },
        { link: '/products', text: 'Scarves', colorNum: 0 },
        { link: '/products', text: 'Hair Accessories', colorNum: 0 },
      ];
      const renderItem = (item) => {
        return (
          <a href={item.link} key={item.text} className={`left-category-item item-color-${item.colorNum}`}>
            {item.text}

        );
      };
      const slideItems = [
        { img: 'https://img.alicdn.com/tps/TB1Lqf1LFXXXXbVXpXXXXXXXXXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i2/TB1UHPPLFXXXXc0XpXXL2TJPFXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i3/TB19sDBLFXXXXaOaXXXL2TJPFXX-480-550.jpg' },
      ];
      const renderSlideItem = (item) => {
        return (

        );
      };
      const smallBanners = [
        { title: 'New in 2016 Spring', subTitle: 'For Her', img: 'https://img.alicdn.com/tps/TB1oh4kLFXXXXcqXXXXXXXXXXXX-180-195.png' },
        { title: 'New in 2016 April', subTitle: 'Vintage Style', img: 'https://img.alicdn.com/tps/TB1gdcLLpXXXXbpXpXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2015 Spring', subTitle: 'For You', img: 'https://img.alicdn.com/tps/TB1n15zKXXXXXcLXVXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2014 Spring', subTitle: 'For Me', img: 'https://img.alicdn.com/tps/TB1LYMJLpXXXXbxXpXXXXXXXXXX-180-195.jpg' },
      ];
      const renderSmallBanner = (item) => {
        return (

{item.title}

{item.subTitle}

        );
      };
      return (

WOMENS CLOTHING

            {linkItems.map((item) => renderItem(item))}

            {slideItems.map((item) => renderSlideItem(item))}

            {smallBanners.map((item) => renderSmallBanner(item))}

      );
    };
    const renderCategories = () => {
      const renderHoverCategory = () => {
        const { hoverCategory } = this.state;
        if (hoverCategory) {
          const children = hoverCategory.children || [];
          return (

              {children.map((c, i) => (

{c.name[activeLocale]}

              ))}

          );
        }
      };
      const topCategories = get(this.props.categories, 'tree.children', []);
      return (

          {topCategories.map((c, i) => (

 this.setState({ hoverCategory: c })}>{c.name[activeLocale]}

          ))}
          {renderHoverCategory()}

      );
    };
    return (

CATEGORIES See All >

Super Deals

Super Market

Featured Brands

Best Selling

IT Company

            {renderCategories()}

          {renderCurationTopic()}
          <ProductListItems products={products} />

    );
  },
});

export default connect(
  state => ({
    categories: state.categories,
    ...loadEntities(state, 'products', 'products'),
  }),
  { loadProducts }
)(Home);
<commit_msg>add Link to category item.<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { get } from 'lodash';

import loadEntities from '../../commons/redux/util/loadEntities';

import ProductListItems from '../components/ProductListItems';

import { ApiAction } from '../redux/actions';
const { loadProducts } = ApiAction;

const Home = React.createClass({
  propTypes: {
    products: PropTypes.array,
    categories: PropTypes.object.isRequired,
    loadProducts: PropTypes.func.isRequired,
  },
  contextTypes: {
    activeLocale: PropTypes.string,
    activeCurrency: PropTypes.string,
  },
  getInitialState() {
    return {};
  },
  componentDidMount() {
    this.props.loadProducts();
    $('.main-banner').owlCarousel({ autoPlay: 10000, items: 1 });
    $('.center-slide').owlCarousel({ autoPlay: 10000, items: 1 });
  },
  render() {
    const { products = [] } = this.props;
    const { activeCurrency, activeLocale } = this.context;
    const renderCurationTopic = () => {
      const linkItems = [
        { link: '/products', text: 'Fall Dresses', colorNum: 0 },
        { link: '/products', text: 'Casual Dresses', colorNum: 1 },
        { link: '/products', text: 'Cardigans', colorNum: 0 },
        { link: '/products', text: 'Summer Dresses', colorNum: 1 },
        { link: '/products', text: 'Blazers', colorNum: 0 },
        { link: '/products', text: 'Jumpsuits', colorNum: 0 },
        { link: '/products', text: 'Blouses & Shirts', colorNum: 1 },
        { link: '/products', text: 'T-Shirts', colorNum: 0 },
        { link: '/products', text: 'Sunglasses', colorNum: 1 },
        { link: '/products', text: 'Scarves', colorNum: 0 },
        { link: '/products', text: 'Hair Accessories', colorNum: 0 },
      ];
      const renderItem = (item) => {
        return (
          <a href={item.link} key={item.text} className={`left-category-item item-color-${item.colorNum}`}>
            {item.text}

        );
      };
      const slideItems = [
        { img: 'https://img.alicdn.com/tps/TB1Lqf1LFXXXXbVXpXXXXXXXXXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i2/TB1UHPPLFXXXXc0XpXXL2TJPFXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i3/TB19sDBLFXXXXaOaXXXL2TJPFXX-480-550.jpg' },
      ];
      const renderSlideItem = (item) => {
        return (

        );
      };
      const smallBanners = [
        { title: 'New in 2016 Spring', subTitle: 'For Her', img: 'https://img.alicdn.com/tps/TB1oh4kLFXXXXcqXXXXXXXXXXXX-180-195.png' },
        { title: 'New in 2016 April', subTitle: 'Vintage Style', img: 'https://img.alicdn.com/tps/TB1gdcLLpXXXXbpXpXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2015 Spring', subTitle: 'For You', img: 'https://img.alicdn.com/tps/TB1n15zKXXXXXcLXVXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2014 Spring', subTitle: 'For Me', img: 'https://img.alicdn.com/tps/TB1LYMJLpXXXXbxXpXXXXXXXXXX-180-195.jpg' },
      ];
      const renderSmallBanner = (item) => {
        return (

{item.title}

{item.subTitle}

        );
      };
      return (

WOMENS CLOTHING

            {linkItems.map((item) => renderItem(item))}

            {slideItems.map((item) => renderSlideItem(item))}

            {smallBanners.map((item) => renderSmallBanner(item))}

      );
    };
    const renderCategories = () => {
      const renderHoverCategory = () => {
        const { hoverCategory } = this.state;
        if (hoverCategory) {
          const children = hoverCategory.children || [];
          return (

              {children.map((c, i) => (
                <Link key={i} to={'/categories/' + c.id}>

{c.name[activeLocale]}

                </Link>
              ))}

          );
        }
      };
      const topCategories = get(this.props.categories, 'tree.children', []);
      return (

          {topCategories.map((c, i) => (
            <Link key={i} to={'/categories/' + c.id}>

 this.setState({ hoverCategory: c })}>{c.name[activeLocale]}

            </Link>
          ))}
          {renderHoverCategory()}

      );
    };
    return (

CATEGORIES See All >

Super Deals

Super Market

Featured Brands

Best Selling

IT Company

            {renderCategories()}

          {renderCurationTopic()}
          <ProductListItems products={products} />

    );
  },
});

export default connect(
  state => ({
    categories: state.categories,
    ...loadEntities(state, 'products', 'products'),
  }),
  { loadProducts }
)(Home);
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { get } from 'lodash';

import loadEntities from '../../commons/redux/util/loadEntities';

import ProductListItems from '../components/ProductListItems';

import { ApiAction } from '../redux/actions';
const { loadProducts } = ApiAction;

const Home = React.createClass({
  propTypes: {
    products: PropTypes.array,
    categories: PropTypes.object.isRequired,
    loadProducts: PropTypes.func.isRequired,
  },
  contextTypes: {
    activeLocale: PropTypes.string,
    activeCurrency: PropTypes.string,
  },
  getInitialState() {
    return {};
  },
  componentDidMount() {
    this.props.loadProducts();
    $('.main-banner').owlCarousel({ autoPlay: 10000, items: 1 });
    $('.center-slide').owlCarousel({ autoPlay: 10000, items: 1 });
  },
  render() {
    const { products = [] } = this.props;
    const { activeCurrency, activeLocale } = this.context;
    const renderCurationTopic = () => {
      const linkItems = [
        { link: '/products', text: 'Fall Dresses', colorNum: 0 },
        { link: '/products', text: 'Casual Dresses', colorNum: 1 },
        { link: '/products', text: 'Cardigans', colorNum: 0 },
        { link: '/products', text: 'Summer Dresses', colorNum: 1 },
        { link: '/products', text: 'Blazers', colorNum: 0 },
        { link: '/products', text: 'Jumpsuits', colorNum: 0 },
        { link: '/products', text: 'Blouses & Shirts', colorNum: 1 },
        { link: '/products', text: 'T-Shirts', colorNum: 0 },
        { link: '/products', text: 'Sunglasses', colorNum: 1 },
        { link: '/products', text: 'Scarves', colorNum: 0 },
        { link: '/products', text: 'Hair Accessories', colorNum: 0 },
      ];
      const renderItem = (item) => {
        return (
          <a href={item.link} key={item.text} className={`left-category-item item-color-${item.colorNum}`}>
            {item.text}

        );
      };
      const slideItems = [
        { img: 'https://img.alicdn.com/tps/TB1Lqf1LFXXXXbVXpXXXXXXXXXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i2/TB1UHPPLFXXXXc0XpXXL2TJPFXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i3/TB19sDBLFXXXXaOaXXXL2TJPFXX-480-550.jpg' },
      ];
      const renderSlideItem = (item) => {
        return (

        );
      };
      const smallBanners = [
        { title: 'New in 2016 Spring', subTitle: 'For Her', img: 'https://img.alicdn.com/tps/TB1oh4kLFXXXXcqXXXXXXXXXXXX-180-195.png' },
        { title: 'New in 2016 April', subTitle: 'Vintage Style', img: 'https://img.alicdn.com/tps/TB1gdcLLpXXXXbpXpXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2015 Spring', subTitle: 'For You', img: 'https://img.alicdn.com/tps/TB1n15zKXXXXXcLXVXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2014 Spring', subTitle: 'For Me', img: 'https://img.alicdn.com/tps/TB1LYMJLpXXXXbxXpXXXXXXXXXX-180-195.jpg' },
      ];
      const renderSmallBanner = (item) => {
        return (

{item.title}

{item.subTitle}

        );
      };
      return (

WOMENS CLOTHING

            {linkItems.map((item) => renderItem(item))}

            {slideItems.map((item) => renderSlideItem(item))}

            {smallBanners.map((item) => renderSmallBanner(item))}

      );
    };
    const renderCategories = () => {
      const renderHoverCategory = () => {
        const { hoverCategory } = this.state;
        if (hoverCategory) {
          const children = hoverCategory.children || [];
          return (

              {children.map((c, i) => (
                <Link key={i} to={'/categories/' + c.id}>

{c.name[activeLocale]}

                </Link>
              ))}

          );
        }
      };
      const topCategories = get(this.props.categories, 'tree.children', []);
      return (

          {topCategories.map((c, i) => (
            <Link key={i} to={'/categories/' + c.id}>

 this.setState({ hoverCategory: c })}
              >{c.name[activeLocale]}

            </Link>
          ))}
          {renderHoverCategory()}

      );
    };
    return (

CATEGORIES See All >

Super Deals

Super Market

Featured Brands

Best Selling

IT Company

            {renderCategories()}

          {renderCurationTopic()}
          <ProductListItems products={products} />

    );
  },
});

export default connect(
  state => ({
    categories: state.categories,
    ...loadEntities(state, 'products', 'products'),
  }),
  { loadProducts }
)(Home);
<commit_msg>show more categories.<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { get } from 'lodash';

import loadEntities from '../../commons/redux/util/loadEntities';

import ProductListItems from '../components/ProductListItems';

import { ApiAction } from '../redux/actions';
const { loadProducts } = ApiAction;

const Home = React.createClass({
  propTypes: {
    products: PropTypes.array,
    categories: PropTypes.object.isRequired,
    loadProducts: PropTypes.func.isRequired,
  },
  contextTypes: {
    activeLocale: PropTypes.string,
    activeCurrency: PropTypes.string,
  },
  getInitialState() {
    return {};
  },
  componentDidMount() {
    this.props.loadProducts();
    $('.main-banner').owlCarousel({ autoPlay: 10000, items: 1 });
    $('.center-slide').owlCarousel({ autoPlay: 10000, items: 1 });
  },
  render() {
    const { products = [] } = this.props;
    const { activeCurrency, activeLocale } = this.context;
    const renderCurationTopic = () => {
      const linkItems = [
        { link: '/products', text: 'Fall Dresses', colorNum: 0 },
        { link: '/products', text: 'Casual Dresses', colorNum: 1 },
        { link: '/products', text: 'Cardigans', colorNum: 0 },
        { link: '/products', text: 'Summer Dresses', colorNum: 1 },
        { link: '/products', text: 'Blazers', colorNum: 0 },
        { link: '/products', text: 'Jumpsuits', colorNum: 0 },
        { link: '/products', text: 'Blouses & Shirts', colorNum: 1 },
        { link: '/products', text: 'T-Shirts', colorNum: 0 },
        { link: '/products', text: 'Sunglasses', colorNum: 1 },
        { link: '/products', text: 'Scarves', colorNum: 0 },
        { link: '/products', text: 'Hair Accessories', colorNum: 0 },
      ];
      const renderItem = (item) => {
        return (
          <a href={item.link} key={item.text} className={`left-category-item item-color-${item.colorNum}`}>
            {item.text}

        );
      };
      const slideItems = [
        { img: 'https://img.alicdn.com/tps/TB1Lqf1LFXXXXbVXpXXXXXXXXXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i2/TB1UHPPLFXXXXc0XpXXL2TJPFXX-480-550.jpg' },
        { img: 'http://img.alicdn.com/tps/i3/TB19sDBLFXXXXaOaXXXL2TJPFXX-480-550.jpg' },
      ];
      const renderSlideItem = (item) => {
        return (

        );
      };
      const smallBanners = [
        { title: 'New in 2016 Spring', subTitle: 'For Her', img: 'https://img.alicdn.com/tps/TB1oh4kLFXXXXcqXXXXXXXXXXXX-180-195.png' },
        { title: 'New in 2016 April', subTitle: 'Vintage Style', img: 'https://img.alicdn.com/tps/TB1gdcLLpXXXXbpXpXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2015 Spring', subTitle: 'For You', img: 'https://img.alicdn.com/tps/TB1n15zKXXXXXcLXVXXXXXXXXXX-180-195.jpg' },
        { title: 'New in 2014 Spring', subTitle: 'For Me', img: 'https://img.alicdn.com/tps/TB1LYMJLpXXXXbxXpXXXXXXXXXX-180-195.jpg' },
      ];
      const renderSmallBanner = (item) => {
        return (

{item.title}

{item.subTitle}

        );
      };
      return (

WOMENS CLOTHING

            {linkItems.map((item) => renderItem(item))}

            {slideItems.map((item) => renderSlideItem(item))}

            {smallBanners.map((item) => renderSmallBanner(item))}

      );
    };
    const renderCategories = () => {
      const renderHoverCategory = () => {
        const { hoverCategory } = this.state;
        if (hoverCategory) {
          const children = hoverCategory.children || [];
          // FIXME
          return (

              {children.map((c, i) => (

                  <Link to={'/categories/' + c.id}>

{c.name[activeLocale]}

                  </Link>
                  {(c.children || []).map((gc, gi) => (
                    <Link key={gi} to={'/categories/' + gc.id}>

{gc.name[activeLocale]}

                    </Link>
                  ))}

              ))}

          );
        }
      };
      const topCategories = get(this.props.categories, 'tree.children', []);
      return (

          {topCategories.map((c, i) => (
            <Link key={i} to={'/categories/' + c.id}>

 this.setState({ hoverCategory: c })}
              >{c.name[activeLocale]}

            </Link>
          ))}
          {renderHoverCategory()}

      );
    };
    return (

CATEGORIES See All >

Super Deals

Super Market

Featured Brands

Best Selling

IT Company

            {renderCategories()}

          {renderCurationTopic()}
          <ProductListItems products={products} />

    );
  },
});

export default connect(
  state => ({
    categories: state.categories,
    ...loadEntities(state, 'products', 'products'),
  }),
  { loadProducts }
)(Home);
<|endoftext|>


<commit_before>/**
 * @file Guild events file.
 * @author Capuccino
 * @author Ovyerus
 */

/* eslint-env node */

module.exports = bot => {
    bot.on('guildCreate', g => {
        if (g.members.filter(m => m.bot).size / g.members.size >= 0.50) {
            logger.info(`Leaving bot collection '${g.name}' (${g.id})`);
            g.leave();
        } else {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildDelete', g => {
        if (!(g.members.filter(m => m.bot).size/g.members.size >= 0.50)) {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildMemberAdd', (g, m) => {
        bot.getGuildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.greeting.message) {
                return null;
            }
            let msg = res.greeting.message.replace(/\{\{user\}\}/g, m.mention).replace(/\{\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.greeting.channelID).createMessage(msg);
        });
    });

    bot.on('guildMemberDelete', (g, m) => {
        bot.guildSettings(g.id).then(res => {
            if (!res || !res.goodbyes || !res.goodbyes.enabled || !res.goodbyes.channelID || !res.goodbyes.message) {
                return null;
            }
            let msg = res.goodbyes.message.replace(/\{\user\}\}/g, m.mention).replace(/\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.goodbyes.channelID).createMessage(msg);
        });
    });
};
<commit_msg>use newer leaveGuild() method for client<commit_after>/**
 * @file Guild events file.
 * @author Capuccino
 * @author Ovyerus
 */

/* eslint-env node */

module.exports = bot => {
    bot.on('guildCreate', g => {
        if (g.members.filter(m => m.bot).size / g.members.size >= 0.50) {
            logger.info(`Leaving bot collection '${g.name}' (${g.id})`);
            g.leaveGuild(g.id);
        } else {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildDelete', g => {
        if (!(g.members.filter(m => m.bot).size/g.members.size >= 0.50)) {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildMemberAdd', (g, m) => {
        bot.getGuildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.greeting.message) {
                return null;
            }
            let msg = res.greeting.message.replace(/\{\{user\}\}/g, m.mention).replace(/\{\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.greeting.channelID).createMessage(msg);
        });
    });

    bot.on('guildMemberDelete', (g, m) => {
        bot.guildSettings(g.id).then(res => {
            if (!res || !res.goodbyes || !res.goodbyes.enabled || !res.goodbyes.channelID || !res.goodbyes.message) {
                return null;
            }
            let msg = res.goodbyes.message.replace(/\{\user\}\}/g, m.mention).replace(/\{name\}\}/g, utils.formatUsername(m));
            return g.channels.get(res.goodbyes.channelID).createMessage(msg);
        });
    });
};
<|endoftext|>


<commit_before>(function(factory){
  if(typeof define==='function'&&define.amd){
    define(['jquery'],factory);
  }else if(typeof module==='object'&&module.exports){
    module.exports=factory(require('jquery'));
  }else{
    factory(window.jQuery);
  }
}
(function($){
  $.extend(true,$.summernote.lang,{
    'en-US':{
      cleaner:{
        tooltip:'Cleaner',
        not:'Text has been Cleaned!!!'
      }
    }
  });
  $.extend($.summernote.options,{
    cleaner:{
      notTime:2400, // Time to display Notifications.
      action:'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
      newline:'
', // Summernote's default is to use '

'
      notStyle:'position:absolute;top:0;left:0;right:0',
      icon:'<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14" width="14" height="14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
      keepHtml:false, //Remove all Html formats
      keepOnlyTags: [], // If keepHtml is true, remove all tags except these
      keepClasses:false, //Remove Classes
      badTags:['style','script','applet','embed','noframes','noscript','html'], //Remove full tags with contents
      badAttributes:['style','start'] //Remove attributes from remaining tags
    }
  });
  $.extend($.summernote.plugins,{
    'cleaner':function(context){
      var self=this;
      var ui=$.summernote.ui;
      var $note=context.layoutInfo.note;
      var $editor=context.layoutInfo.editor;
      var options=context.options;
      var lang=options.langInfo;
      var cleanText=function(txt,nlO){
        var out=txt;
        if(!options.cleaner.keepClasses){
          var sS=/(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
          out=txt.replace(sS,' ');
        }
        var nL=/(\n)+/g;
        out=out.replace(nL,nlO);
        if(options.cleaner.keepHtml){
          var cS=new RegExp('','gi');
          out=out.replace(cS,'');
          var tS=new RegExp('<(/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>','gi');
          out=out.replace(tS,'');
          var bT=options.cleaner.badTags;
          for(var i=0;i<bT.length;i++){
            tS=new RegExp('<'+bT[i]+'[^>]*>','gi');
            out=out.replace(tS,'');
            tS=new RegExp('</'+bT[i]+'[^>]*>','gi');
            out=out.replace(tS,'');
          }
          var allowedTags=options.cleaner.keepOnlyTags;
          if(typeof(allowedTags) == "undefined")
            allowedTags = [];
          if(allowedTags.length>0){
            allowedTags=(((allowedTags||'')+'').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
            var tags=/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
            out=out.replace(tags,function($0,$1){
              return allowedTags.indexOf('<'+$1.toLowerCase()+'>') > -1 ? $0 : ''
            });
          }
          var bA=options.cleaner.badAttributes;
          for(var ii=0;ii<bA.length;ii++){
            //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')','gi');
            var aS=new RegExp(' '+bA[ii]+'=[\'|"](.*?)[\'|"]','gi');
            out=out.replace(aS,'');
          }
        }
        return out;
      };
      if(options.cleaner.action=='both'||options.cleaner.action=='button'){
        context.memo('button.cleaner',function(){
          var button=ui.button({
            contents:options.cleaner.icon,
            tooltip:lang.cleaner.tooltip,
            click:function(){
              if($note.summernote('createRange').toString()){
//                var text=cleanText($note.summernote('createRange').toString(),options.cleaner.newline);
                var text=$note.summernote('createRange').toString();
                $note.summernote('pasteHTML',text);
              }else{
//                var text=cleanText($note.summernote().text(),options.cleaner.newline);
                var text=$($note.summernote('code')).text();
                $note.summernote('code',text);
              }
              if(options.cleaner.notTime>0){
                $editor.find('.note-editing-area').append('
'+lang.cleaner.not+'
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
              }
            }
          });
          return button.render();
        });
      }
      this.events={
        'summernote.paste':function(we,e){
          if(options.cleaner.action=='both'||options.cleaner.action=='paste'){
            var ua=window.navigator.userAgent;
            var msie=ua.indexOf("MSIE ");
            msie=msie>0||!!navigator.userAgent.match(/Trident.*rv\:11\./);
            if(msie){
              var text=window.clipboardData.getData("Text");
            }else{
              var text=e.originalEvent.clipboardData.getData((options.cleaner.keepHtml?'text/html':'text/plain'));
            }
            if(text && text!=''){
              e.preventDefault();
              var text=cleanText(text,options.cleaner.newline);
              var pasteFn=function(){
                $note.summernote('pasteHTML',text);
              }
              if(msie){
                setTimeout(pasteFn,1);
              }else{
                pasteFn();
              }
              if(options.cleaner.notTime>0){
                $editor.find('.note-resizebar').append('
'+lang.cleaner.not+'
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
              }
            }
          }
        }
      }
    }
  });
}));
<commit_msg>Fix indenting<commit_after>/* https://github.com/DiemenDesign/summernote-cleaner */
(function(factory){
  if(typeof define==='function'&&define.amd){
    define(['jquery'],factory);
  }else if(typeof module==='object'&&module.exports){
    module.exports=factory(require('jquery'));
  }else{
    factory(window.jQuery);
  }
}
(function($){
  $.extend(true,$.summernote.lang,{
    'en-US':{
      cleaner:{
        tooltip:'Cleaner',
        not:'Text has been Cleaned!!!'
      }
    }
  });
  $.extend($.summernote.options,{
    cleaner:{
      notTime:2400, // Time to display Notifications.
      action:'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
      newline:'
', // Summernote's default is to use '

'
      notStyle:'position:absolute;top:0;left:0;right:0',
      icon:'<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14" width="14" height="14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
      keepHtml:false, //Remove all Html formats
      keepOnlyTags: [], // If keepHtml is true, remove all tags except these
      keepClasses:false, //Remove Classes
      badTags:['style','script','applet','embed','noframes','noscript','html'], //Remove full tags with contents
      badAttributes:['style','start'] //Remove attributes from remaining tags
    }
  });
  $.extend($.summernote.plugins,{
    'cleaner':function(context){
      var self=this;
      var ui=$.summernote.ui;
      var $note=context.layoutInfo.note;
      var $editor=context.layoutInfo.editor;
      var options=context.options;
      var lang=options.langInfo;
      var cleanText=function(txt,nlO){
        var out=txt;
        if(!options.cleaner.keepClasses){
          var sS=/(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
          out=txt.replace(sS,' ');
        }
        var nL=/(\n)+/g;
        out=out.replace(nL,nlO);
        if(options.cleaner.keepHtml){
          var cS=new RegExp('','gi');
          out=out.replace(cS,'');
          var tS=new RegExp('<(/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>','gi');
          out=out.replace(tS,'');
          var bT=options.cleaner.badTags;
          for(var i=0;i<bT.length;i++){
            tS=new RegExp('<'+bT[i]+'[^>]*>','gi');
            out=out.replace(tS,'');
            tS=new RegExp('</'+bT[i]+'[^>]*>','gi');
            out=out.replace(tS,'');
          }
          var allowedTags=options.cleaner.keepOnlyTags;
          if(typeof(allowedTags) == "undefined")
            allowedTags = [];
          if(allowedTags.length>0){
            allowedTags=(((allowedTags||'')+'').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
            var tags=/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
            out=out.replace(tags,function($0,$1){
              return allowedTags.indexOf('<'+$1.toLowerCase()+'>') > -1 ? $0 : ''
            });
          }
          var bA=options.cleaner.badAttributes;
          for(var ii=0;ii<bA.length;ii++){
            //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')','gi');
            var aS=new RegExp(' '+bA[ii]+'=[\'|"](.*?)[\'|"]','gi');
            out=out.replace(aS,'');
          }
        }
        return out;
      };
      if(options.cleaner.action=='both'||options.cleaner.action=='button'){
        context.memo('button.cleaner',function(){
          var button=ui.button({
            contents:options.cleaner.icon,
            tooltip:lang.cleaner.tooltip,
            click:function(){
              if($note.summernote('createRange').toString()){
//                var text=cleanText($note.summernote('createRange').toString(),options.cleaner.newline);
                var text=$note.summernote('createRange').toString();
                $note.summernote('pasteHTML',text);
              }else{
//                var text=cleanText($note.summernote().text(),options.cleaner.newline);
                var text=$($note.summernote('code')).text();
                $note.summernote('code',text);
              }
              if(options.cleaner.notTime>0){
                $editor.find('.note-editing-area').append('
'+lang.cleaner.not+'
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
              }
            }
          });
          return button.render();
        });
      }
      this.events={
        'summernote.paste':function(we,e){
          if(options.cleaner.action=='both'||options.cleaner.action=='paste'){
            var ua=window.navigator.userAgent;
            var msie=ua.indexOf("MSIE ");
            msie=msie>0||!!navigator.userAgent.match(/Trident.*rv\:11\./);
            if(msie){
              var text=window.clipboardData.getData("Text");
            }else{
              var text=e.originalEvent.clipboardData.getData((options.cleaner.keepHtml?'text/html':'text/plain'));
            }
            if(text && text!=''){
              e.preventDefault();
              var text=cleanText(text,options.cleaner.newline);
              var pasteFn=function(){
                $note.summernote('pasteHTML',text);
              }
              if(msie){
                setTimeout(pasteFn,1);
              }else{
                pasteFn();
              }
              if(options.cleaner.notTime>0){
                $editor.find('.note-resizebar').append('
'+lang.cleaner.not+'
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
              }
            }
          }
        }
      }
    }
  });
}));
<|endoftext|>


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

/**
 * @fileoverview Definitions for the fullscreen API specification of HTML5.
 * @see http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
 *
 * @externs
 */

// Externs as defined by the specification.
Element.prototype.requestFullscreen = function() {};

/** @type {boolean} */
Document.prototype.fullscreenEnabled;

/** @type {Element} */
Document.prototype.fullscreenElement;

Document.prototype.exitFullscreen = function() {};

// Externs definitions of browser current implementations.
// Firefox 10 implementation.
Element.prototype.mozRequestFullScreen = function() {};

/** @type {boolean} */
Document.prototype.mozFullScreen;

Document.prototype.mozCancelFullScreen = function() {};

/** @type {Element} */
Document.prototype.mozFullScreenElement;

/** @type {boolean} */
Document.prototype.mozFullScreenEnabled;

// Chrome 18 implementation.
Element.prototype.webkitRequestFullScreen = function() {};

/** @type {boolean} */
Document.prototype.webkitIsFullScreen;

Document.prototype.webkitCancelFullScreen = function() {};

/** @type {Element} */
Document.prototype.webkitCurrentFullScreenElement;

/** @type {boolean} */
Document.prototype.webkitFullScreenKeyboardInputAllowed;

/** @type {number} */
Element.ALLOW_KEYBOARD_INPUT;
<commit_msg><commit_after>/*
 * Copyright 2012 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Definitions for the fullscreen API specification of HTML5.
 * @see http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
 *
 * @externs
 */

// Externs as defined by the specification.
Element.prototype.requestFullscreen = function() {};

/** @type {boolean} */
Document.prototype.fullscreenEnabled;

/** @type {Element} */
Document.prototype.fullscreenElement;

Document.prototype.exitFullscreen = function() {};

// Externs definitions of browser current implementations.
// Firefox 10 implementation.
Element.prototype.mozRequestFullScreen = function() {};

/** @type {boolean} */
Document.prototype.mozFullScreen;

Document.prototype.mozCancelFullScreen = function() {};

/** @type {Element} */
Document.prototype.mozFullScreenElement;

/** @type {boolean} */
Document.prototype.mozFullScreenEnabled;

// Chrome 18 implementation.
Element.prototype.webkitRequestFullScreen = function() {};

/** @type {boolean} */
Document.prototype.webkitIsFullScreen;

Document.prototype.webkitCancelFullScreen = function() {};

/** @type {Element} */
Document.prototype.webkitCurrentFullScreenElement;

/** @type {boolean} */
Document.prototype.webkitFullScreenKeyboardInputAllowed;

/** @type {number} */
Element.ALLOW_KEYBOARD_INPUT = 1;

/** @type {number} */
Element.prototype.ALLOW_KEYBOARD_INPUT = 1;
<|endoftext|>


<commit_before>(function () {
  'use strict';
  /*globals location, XMLHttpRequest, setTimeout*/
  var loc     = location;
  var host    = 'localhost';
  var timeout = setTimeout;
  var ref, check, xhr, lastModified, time;
  if (loc.host === host) {
    ref = new Date().getTime();
    check = function () {
      xhr = new XMLHttpRequest();
      xhr.onload = function () {
        lastModified = this.getResponseHeader('Last-Modified');
        time = new Date(lastModified).getTime();
        if (time > ref) {
          loc.reload();
        } else {
          timeout(check, 1000);
        }
      };
      xhr.open('HEAD', loc.href + '?t=' + new Date().getTime(), true);
      xhr.setRequestHeader('pragma', 'no-cache');
      xhr.send();
    };
    timeout(check, 1000);
  }
}());
<commit_msg>Get hostname and port from location object<commit_after>(function () {
  'use strict';
  /*globals location, XMLHttpRequest, setTimeout*/
  var loc     = location;
  var host    = loc.hostname + (loc.port ? ':' + loc.port : '');
  var timeout = setTimeout;
  var ref, check, xhr, lastModified, time;
  if (loc.host === host) {
    ref = new Date().getTime();
    check = function () {
      xhr = new XMLHttpRequest();
      xhr.onload = function () {
        lastModified = this.getResponseHeader('Last-Modified');
        time = new Date(lastModified).getTime();
        if (time > ref) {
          loc.reload();
        } else {
          timeout(check, 1000);
        }
      };
      xhr.open('HEAD', loc.href + '?t=' + new Date().getTime(), true);
      xhr.setRequestHeader('pragma', 'no-cache');
      xhr.send();
    };
    timeout(check, 1000);
  }
}());
<|endoftext|>


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

  angular.module('app.account')
    .controller('account.Verify', ['$state', '$stateParams', 'notificationService', 'userService', function ($state, $stateParams, notificationService, userService) {
      var _token = $stateParams.token;

      function verify() {
        function onSuccess() {
          notificationService.info('Successfully verified your account.');
        }

        function onFailure(response) {
          var message = 'An error occurred while verifying your account.';
          if (response && response.data && response.data.message) {
            message += ' Message: ' + response.data.message;
          }

          notificationService.error(message);
        }

        return userService.verifyEmailAddress(_token).then(onSuccess, onFailure);
      }

      verify();
      $state.go('app.account.manage');
    }]);
}());
<commit_msg>A freshly verified account still shows the click here to resend verification link until you refresh<commit_after>(function () {
  'use strict';

  angular.module('app.account')
    .controller('account.Verify', ['$state', '$stateParams', 'notificationService', 'userService', function ($state, $stateParams, notificationService, userService) {
      var _token = $stateParams.token;

      function verify() {
        function onSuccess() {
          notificationService.info('Successfully verified your account.');
        }

        function onFailure(response) {
          var message = 'An error occurred while verifying your account.';
          if (response && response.data && response.data.message) {
            message += ' Message: ' + response.data.message;
          }

          notificationService.error(message);
        }

        return userService.verifyEmailAddress(_token).then(onSuccess, onFailure);
      }

      $state.go('app.account.manage').then(verify);
    }]);
}());
<|endoftext|>


<commit_before>/* global ace, fs */
import alt from '../alt'
import * as lib from '../lib'
import fileActions from '../actions/file-actions'

var modelist = ace.require("ace/ext/modelist");

class FilesStore
{
    constructor() {
        this.files = []
        this.current = null

        this.bindListeners({
            handleFileAdded     : fileActions.OPEN_FILE,
            handleFileRemoved   : fileActions.CLOSE_FILE,
            handlePreviewFile   : fileActions.PREVIEW_FILE,
            handleSetCurrentFile: fileActions.SET_CURRENT_FILE,
            handleFileModified  : fileActions.SET_FILE_MODIFIED,
            handleFileUnmodified: fileActions.SET_FILE_UNMODIFIED,
            handleFileMoved     : fileActions.MOVE_FILE,
            handleCheckFile     : fileActions.CHECK_FILE_FOR_MODIFICATIONS
        });
    }

    isPathOpened(path) {
        return this.files.some(f => f.path == path)
    }

    findAllByPath(path) {
        return this.files.filter(f => f.path == path)
    }

    findByPath(path) {
        return this.findAllByPath(path)[0]
    }

    byId(id) {
        return this.files.filter(f => f.id === id)[0]
    }

    // handlers ------------------------------------------------------------------

    handleFileAdded(path) {

        // This path is already opened just switch to it insteat of re-opening
        if (path && this.isPathOpened(path)) {
            this.current = this.findByPath(path)
        }
        else {
            let mode = path ? modelist.getModeForPath(path).mode : 'ace/mode/text';
            let text = '';

            if (path) {
                try {
                    text = fs.readFileSync(path, 'utf8');
                } catch (err) {
                    console.error(err);
                    return;
                }
            }

            let entry = {
                id: lib.uid(),
                path,
                hash: lib.md5(text),
                session : ace.createEditSession(text, mode),
                isPreview : false,
                modified : false
            }

            entry.session.on("change", () => {
                fileActions.checkFileForModifications(entry.id);
            });

            this.files.push(entry)

            this.current = entry
        }
        return this.current
    }

    handlePreviewFile(path) {
        let entry = this.handleFileAdded(path)
        entry.isPreview = true
    }

    handleFileRemoved(id) {
        let idx = this.files.findIndex(f => f.id === id);
        if (idx > -1) {
            let meta = this.files[idx]
            this.files.splice(idx, 1);
            if (this.current == meta) {
                this.current = null;
                let len  = this.files.length;
                if (len) {
                    let next = idx - 1;
                    if (next < 0) {
                        next = this.files.length - 1;
                    }
                    if (next >= 0) {
                        next = this.files[next];
                    }

                    if (next) {
                        this.current = next;
                    }
                }
            }
        }
    }

    handleSetCurrentFile(id) {
        this.current = this.byId(id);
    }

    handleFileModified(path) {
        this.findAllByPath(path).forEach(f => {
            f.modified = true
        });
    }

    handleFileUnmodified(path) {
        this.findAllByPath(path).forEach(f => {
            f.modified = false
        });
    }

    handleFileMoved({ fromIndex, toIndex }) {
        this.files.splice(toIndex, 0, this.files.splice(fromIndex, 1))
    }

    handleCheckFile(id) {
        let entry = this.byId(id)
        if (entry.path) {
            this.findAllByPath(entry.path).forEach(f => {
                f.modified = lib.md5(f.session.getValue()) !== f.hash
            })
        }
        else {
            entry.modified = lib.md5(entry.session.getValue()) !== entry.hash
        }
    }
}

var filesStore = alt.createStore(FilesStore, 'FilesStore')

export default filesStore
<commit_msg>Destroy session on file close<commit_after>/* global ace, fs */
import alt from '../alt'
import * as lib from '../lib'
import fileActions from '../actions/file-actions'

var modelist = ace.require("ace/ext/modelist");

class FilesStore
{
    constructor() {
        this.files = []
        this.current = null

        this.bindListeners({
            handleFileAdded     : fileActions.OPEN_FILE,
            handleFileRemoved   : fileActions.CLOSE_FILE,
            handlePreviewFile   : fileActions.PREVIEW_FILE,
            handleSetCurrentFile: fileActions.SET_CURRENT_FILE,
            handleFileModified  : fileActions.SET_FILE_MODIFIED,
            handleFileUnmodified: fileActions.SET_FILE_UNMODIFIED,
            handleFileMoved     : fileActions.MOVE_FILE,
            handleCheckFile     : fileActions.CHECK_FILE_FOR_MODIFICATIONS
        });
    }

    isPathOpened(path) {
        return this.files.some(f => f.path == path)
    }

    findAllByPath(path) {
        return this.files.filter(f => f.path == path)
    }

    findByPath(path) {
        return this.findAllByPath(path)[0]
    }

    byId(id) {
        return this.files.filter(f => f.id === id)[0]
    }

    // handlers ------------------------------------------------------------------

    handleFileAdded(path) {

        // This path is already opened just switch to it insteat of re-opening
        if (path && this.isPathOpened(path)) {
            this.current = this.findByPath(path)
        }
        else {
            let mode = path ? modelist.getModeForPath(path).mode : 'ace/mode/text';
            let text = '';

            if (path) {
                try {
                    text = fs.readFileSync(path, 'utf8');
                } catch (err) {
                    console.error(err);
                    return;
                }
            }

            let entry = {
                id: lib.uid(),
                path,
                hash: lib.md5(text),
                session : ace.createEditSession(text, mode),
                isPreview : false,
                modified : false
            }

            entry.session.on("change", () => {
                fileActions.checkFileForModifications(entry.id);
            });

            // console.log(entry.session);

            this.files.push(entry)

            this.current = entry
        }
        return this.current
    }

    handlePreviewFile(path) {
        let entry = this.handleFileAdded(path)
        entry.isPreview = true
    }

    handleFileRemoved(id) {
        let idx = this.files.findIndex(f => f.id === id);
        if (idx > -1) {
            let meta = this.files[idx]
            meta.session.removeAllListeners();
            meta.session.destroy();
            this.files.splice(idx, 1);

            if (this.current == meta) {
                this.current = null;
                let len  = this.files.length;
                if (len) {
                    let next = idx - 1;
                    if (next < 0) {
                        next = this.files.length - 1;
                    }
                    if (next >= 0) {
                        next = this.files[next];
                    }

                    if (next) {
                        this.current = next;
                    }
                }
            }
        }
    }

    handleSetCurrentFile(id) {
        this.current = this.byId(id);
    }

    handleFileModified(path) {
        this.findAllByPath(path).forEach(f => {
            f.modified = true
        });
    }

    handleFileUnmodified(path) {
        this.findAllByPath(path).forEach(f => {
            f.modified = false
        });
    }

    handleFileMoved({ fromIndex, toIndex }) {
        this.files.splice(toIndex, 0, this.files.splice(fromIndex, 1))
    }

    handleCheckFile(id) {
        let entry = this.byId(id)
        if (entry.path) {
            this.findAllByPath(entry.path).forEach(f => {
                f.modified = lib.md5(f.session.getValue()) !== f.hash
            })
        }
        else {
            entry.modified = lib.md5(entry.session.getValue()) !== entry.hash
        }
    }
}

var filesStore = alt.createStore(FilesStore, 'FilesStore')

export default filesStore
<|endoftext|>


<commit_before>const Entity = require('prismarine-entity')
const path = require('path')
const requireIndex = require('../requireindex')
const plugins = requireIndex(path.join(__dirname, '..', 'plugins'))
const UserError = require('flying-squid').UserError
const UUID = require('uuid-1345')
const Vec3 = require('vec3').Vec3

module.exports.server = function (serv, options) {
  const version = options.version

  const mobsById = require('minecraft-data')(version).mobs
  const objectsById = require('minecraft-data')(version).objects

  serv.initEntity = (type, entityType, world, position) => {
    if (Object.keys(serv.entities).length > options['max-entities']) { throw new Error('Too many mobs !') }
    serv.entityMaxId++
    const entity = new Entity(serv.entityMaxId)

    Object.keys(plugins)
      .filter(pluginName => plugins[pluginName].entity !== undefined)
      .forEach(pluginName => plugins[pluginName].entity(entity, serv, options))

    entity.initEntity(type, entityType, world, position)

    serv.emit('newEntity', entity)

    return entity
  }

  serv.spawnObject = (type, world, position, { pitch = 0, yaw = 0, velocity = new Vec3(0, 0, 0), data = 1, itemId, itemDamage = 0, pickupTime = undefined, deathTime = undefined }) => {
    const object = serv.initEntity('object', type, world, position)
    object.uuid = UUID.v4()
    object.name = objectsById[type].name
    object.data = data
    object.velocity = velocity
    object.pitch = pitch
    object.yaw = yaw
    object.gravity = new Vec3(0, -20, 0)
    object.terminalvelocity = new Vec3(27, 27, 27)
    object.friction = new Vec3(15, 0, 15)
    object.size = new Vec3(0.25, 0.25, 0.25) // Hardcoded, will be dependent on type!
    object.deathTime = deathTime
    object.pickupTime = pickupTime
    object.itemId = itemId
    object.itemDamage = itemDamage

    object.updateAndSpawn()
  }

  serv.spawnMob = (type, world, position, { pitch = 0, yaw = 0, headPitch = 0, velocity = new Vec3(0, 0, 0), metadata = [] } = {}) => {
    const mob = serv.initEntity('mob', type, world, position)
    mob.uuid = UUID.v4()
    mob.name = mobsById[type].name
    mob.velocity = velocity
    mob.pitch = pitch
    mob.headPitch = headPitch
    mob.yaw = yaw
    mob.gravity = new Vec3(0, -20, 0)
    mob.terminalvelocity = new Vec3(27, 27, 27)
    mob.friction = new Vec3(15, 0, 15)
    mob.size = new Vec3(0.75, 1.75, 0.75)
    mob.health = 20
    mob.metadata = metadata

    mob.updateAndSpawn()
    return mob
  }

  serv.destroyEntity = entity => {
    entity._writeOthersNearby('entity_destroy', {
      entityIds: [entity.id]
    })
    delete serv.entities[entity.id]
  }
}

module.exports.player = function (player, serv, options) {
  const version = options.version
  const entitiesByName = require('minecraft-data')(version).entitiesByName
  const Item = require('prismarine-item')(version)

  player.commands.add({
    base: 'summon',
    info: 'Summon an entity',
    usage: '/summon <entity_name>',
    op: true,
    action (name) {
      if (Object.keys(serv.entities).length > options['max-entities']) { throw new UserError('Too many mobs !') }
      const entity = entitiesByName[name]
      if (!entity) {
        return 'No entity named ' + name
      }
      if (entity.type === 'mob') {
        serv.spawnMob(entity.id, player.world, player.position, {
          velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
        })
      } else if (entity.type === 'object') {
        serv.spawnObject(entity.id, player.world, player.position, {
          velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
        })
      }
    }
  })

  player.commands.add({
    base: 'summonMany',
    info: 'Summon many entities',
    usage: '/summonMany <number> <entity_name>',
    op: true,
    parse (str) {
      const args = str.split(' ')
      if (args.length !== 2) { return false }
      return { number: args[0], name: args[1] }
    },
    action ({ number, name }) {
      if (Object.keys(serv.entities).length > options['max-entities'] - number) { throw new UserError('Too many mobs !') }
      const entity = entitiesByName[name]
      if (!entity) {
        return 'No entity named ' + name
      }
      const s = Math.floor(Math.sqrt(number))
      for (let i = 0; i < number; i++) {
        if (entity.type === 'mob') {
          serv.spawnMob(entity.id, player.world, player.position.offset(Math.floor(i / s * 10), 0, i % s * 10), {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        } else if (entity.type === 'object') {
          serv.spawnObject(entity.id, player.world, player.position.offset(Math.floor(i / s * 10), 0, i % s * 10), {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        }
      }
    }
  })

  player.commands.add({
    base: 'pile',
    info: 'make a pile of entities',
    usage: '/pile <entities types>',
    op: true,
    parse (str) {
      const args = str.split(' ')
      if (args.length === 0) { return false }
      return args
        .map(name => entitiesByName[name])
        .filter(entity => !!entity)
    },
    action (entityTypes) {
      if (Object.keys(serv.entities).length > options['max-entities'] - entityTypes.length) { throw new UserError('Too many mobs !') }
      entityTypes.map(entity => {
        if (entity.type === 'mob') {
          return serv.spawnMob(entity.id, player.world, player.position, {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        } else if (entity.type === 'object') {
          return serv.spawnObject(entity.id, player.world, player.position, {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        }
      })
        .reduce((prec, entity) => {
          if (prec !== null) { prec.attach(entity) }
          return entity
        }, null)
    }
  })

  player.commands.add({
    base: 'attach',
    info: 'attach an entity on an other entity',
    usage: '/attach <carrier> <attached>',
    op: true,
    parse (str) {
      const args = str.split(' ')
      if (args.length !== 2) { return false }

      const carrier = player.selectorString(args[0])
      if (carrier.length === 0) throw new UserError('one carrier')
      const attached = player.selectorString(args[1])
      if (attached.length === 0) throw new UserError('one attached')

      return { carrier: carrier[0], attached: attached[0] }
    },
    action ({ carrier, attached }) {
      carrier.attach(attached)
    }
  })

  player.spawnEntity = entity => {
    player._client.write(entity.spawnPacketName, entity.getSpawnPacket())
    if (typeof entity.itemId !== 'undefined') {
      entity.sendMetadata([{
        key: 10,
        type: 5,
        value: {
          blockId: entity.itemId,
          itemDamage: entity.itemDamage,
          itemCount: 1
        }
      }])
    }
    entity.equipment.forEach((equipment, slot) => {
      if (equipment !== undefined) {
        player._client.write('entity_equipment', {
          entityId: entity.id,
          slot: slot,
          item: Item.toNotch(equipment)
        })
      }
    }
    )
  }
}

module.exports.entity = function (entity, serv) {
  entity.initEntity = (type, entityType, world, position) => {
    entity.type = type
    entity.spawnPacketName = ''
    entity.entityType = entityType
    entity.world = world
    entity.position = position
    entity.lastPositionPlayersUpdated = entity.position.clone()
    entity.nearbyEntities = []
    entity.viewDistance = 150
    entity.score = {}

    entity.bornTime = Date.now()
    serv.entities[entity.id] = entity

    if (entity.type === 'player') entity.spawnPacketName = 'named_entity_spawn'
    else if (entity.type === 'object') entity.spawnPacketName = 'spawn_entity'
    else if (entity.type === 'mob') entity.spawnPacketName = 'spawn_entity_living'
  }

  entity.getSpawnPacket = () => {
    let scaledVelocity = entity.velocity.scaled(8000 / 20) // from fixed-position/second to unit => 1/8000 blocks per tick
    if (serv.supportFeature('fixedPointPosition')) {
      scaledVelocity = scaledVelocity.scaled(1 / 32)
    }
    scaledVelocity = scaledVelocity.floored()

    let entityPosition
    if (serv.supportFeature('fixedPointPosition')) {
      entityPosition = entity.position.scaled(32).floored()
    } else if (serv.supportFeature('doublePosition')) {
      entityPosition = entity.position
    }

    if (entity.type === 'player') {
      return {
        entityId: entity.id,
        playerUUID: entity.uuid,
        x: entityPosition.x,
        y: entityPosition.y,
        z: entityPosition.z,
        yaw: entity.yaw,
        pitch: entity.pitch,
        currentItem: 0,
        metadata: entity.metadata
      }
    } else if (entity.type === 'object') {
      return {
        entityId: entity.id,
        objectUUID: entity.uuid,
        type: entity.entityType,
        x: entityPosition.x,
        y: entityPosition.y,
        z: entityPosition.z,
        pitch: entity.pitch,
        yaw: entity.yaw,
        objectData: {
          intField: entity.data,
          velocityX: scaledVelocity.x,
          velocityY: scaledVelocity.y,
          velocityZ: scaledVelocity.z
        }
      }
    } else if (entity.type === 'mob') {
      return {
        entityId: entity.id,
        entityUUID: entity.uuid,
        type: entity.entityType,
        x: entityPosition.x,
        y: entityPosition.y,
        z: entityPosition.z,
        yaw: entity.yaw,
        pitch: entity.pitch,
        headPitch: entity.headPitch,
        velocityX: scaledVelocity.x,
        velocityY: scaledVelocity.y,
        velocityZ: scaledVelocity.z,
        metadata: entity.metadata
      }
    }
  }

  entity.updateAndSpawn = () => {
    const updatedEntities = entity.getNearby()
    const entitiesToAdd = updatedEntities.filter(e => entity.nearbyEntities.indexOf(e) === -1)
    const entitiesToRemove = entity.nearbyEntities.filter(e => updatedEntities.indexOf(e) === -1)
    if (entity.type === 'player') {
      entity.despawnEntities(entitiesToRemove)
      entitiesToAdd.forEach(entity.spawnEntity)
    }
    entity.lastPositionPlayersUpdated = entity.position.clone()

    const playersToAdd = entitiesToAdd.filter(e => e.type === 'player')
    const playersToRemove = entitiesToRemove.filter(e => e.type === 'player')

    playersToRemove.forEach(p => p.despawnEntities([entity]))
    playersToRemove.forEach(p => { p.nearbyEntities = p.getNearby() })
    playersToAdd.forEach(p => p.spawnEntity(entity))
    playersToAdd.forEach(p => { p.nearbyEntities = p.getNearby() })

    entity.nearbyEntities = updatedEntities
  }

  entity.on('move', () => {
    if (entity.position.distanceTo(entity.lastPositionPlayersUpdated) > 2) { entity.updateAndSpawn() }
  })

  entity.destroy = () => {
    serv.destroyEntity(entity)
  }

  entity.attach = (attachedEntity, leash = false) => {
    if (serv.supportFeature('attachStackEntity') || (serv.supportFeature('setPassengerStackEntity') && leash)) {
      const p = {
        entityId: attachedEntity.id,
        vehicleId: entity.id,
        leash: leash
      }
      if (entity.type === 'player') { entity._client.write('attach_entity', p) }
      entity._writeOthersNearby('attach_entity', p)
    }
    if (serv.supportFeature('setPassengerStackEntity')) {
      const p = {
        entityId: entity.id,
        passengers: [attachedEntity.id]
      }
      if (entity.type === 'player') { entity._client.write('set_passengers', p) }
      entity._writeOthersNearby('set_passengers', p)
    }
  }
}
<commit_msg>fix unrelated broken code<commit_after>const Entity = require('prismarine-entity')
const path = require('path')
const requireIndex = require('../requireindex')
const plugins = requireIndex(path.join(__dirname, '..', 'plugins'))
const UserError = require('flying-squid').UserError
const UUID = require('uuid-1345')
const Vec3 = require('vec3').Vec3

module.exports.server = function (serv, options) {
  const version = options.version

  const mobsById = require('minecraft-data')(version).mobs
  const objectsById = require('minecraft-data')(version).objects

  serv.initEntity = (type, entityType, world, position) => {
    if (Object.keys(serv.entities).length > options['max-entities']) { throw new Error('Too many mobs !') }
    serv.entityMaxId++
    const entity = new Entity(serv.entityMaxId)

    Object.keys(plugins)
      .filter(pluginName => plugins[pluginName].entity !== undefined)
      .forEach(pluginName => plugins[pluginName].entity(entity, serv, options))

    entity.initEntity(type, entityType, world, position)

    serv.emit('newEntity', entity)

    return entity
  }

  serv.spawnObject = (type, world, position, { pitch = 0, yaw = 0, velocity = new Vec3(0, 0, 0), data = 1, itemId, itemDamage = 0, pickupTime = undefined, deathTime = undefined }) => {
    const object = serv.initEntity('object', type, world, position)
    object.uuid = UUID.v4()
    object.name = objectsById[type].name
    object.data = data
    object.velocity = velocity
    object.pitch = pitch
    object.yaw = yaw
    object.gravity = new Vec3(0, -20, 0)
    object.terminalvelocity = new Vec3(27, 27, 27)
    object.friction = new Vec3(15, 0, 15)
    object.size = new Vec3(0.25, 0.25, 0.25) // Hardcoded, will be dependent on type!
    object.deathTime = deathTime
    object.pickupTime = pickupTime
    object.itemId = itemId
    object.itemDamage = itemDamage

    object.updateAndSpawn()
  }

  serv.spawnMob = (type, world, position, { pitch = 0, yaw = 0, headPitch = 0, velocity = new Vec3(0, 0, 0), metadata = [] } = {}) => {
    const mob = serv.initEntity('mob', type, world, position)
    mob.uuid = UUID.v4()
    mob.name = mobsById[type].name
    mob.velocity = velocity
    mob.pitch = pitch
    mob.headPitch = headPitch
    mob.yaw = yaw
    mob.gravity = new Vec3(0, -20, 0)
    mob.terminalvelocity = new Vec3(27, 27, 27)
    mob.friction = new Vec3(15, 0, 15)
    mob.size = new Vec3(0.75, 1.75, 0.75)
    mob.health = 20
    mob.metadata = metadata

    mob.updateAndSpawn()
    return mob
  }

  serv.destroyEntity = entity => {
    entity._writeOthersNearby('entity_destroy', {
      entityIds: [entity.id]
    })
    delete serv.entities[entity.id]
  }
}

module.exports.player = function (player, serv, options) {
  const version = options.version
  const entitiesByName = require('minecraft-data')(version).entitiesByName
  const Item = require('prismarine-item')(version)

  player.commands.add({
    base: 'summon',
    info: 'Summon an entity',
    usage: '/summon <entity_name>',
    op: true,
    action (name) {
      if (Object.keys(serv.entities).length > options['max-entities']) { throw new UserError('Too many mobs !') }
      const entity = entitiesByName[name]
      if (!entity) {
        return 'No entity named ' + name
      }
      if (entity.type === 'mob') {
        serv.spawnMob(entity.id, player.world, player.position, {
          velocity: new Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
        })
      } else if (entity.type === 'object') {
        serv.spawnObject(entity.id, player.world, player.position, {
          velocity: new Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
        })
      }
    }
  })

  player.commands.add({
    base: 'summonMany',
    info: 'Summon many entities',
    usage: '/summonMany <number> <entity_name>',
    op: true,
    parse (str) {
      const args = str.split(' ')
      if (args.length !== 2) { return false }
      return { number: args[0], name: args[1] }
    },
    action ({ number, name }) {
      if (Object.keys(serv.entities).length > options['max-entities'] - number) { throw new UserError('Too many mobs !') }
      const entity = entitiesByName[name]
      if (!entity) {
        return 'No entity named ' + name
      }
      const s = Math.floor(Math.sqrt(number))
      for (let i = 0; i < number; i++) {
        if (entity.type === 'mob') {
          serv.spawnMob(entity.id, player.world, player.position.offset(Math.floor(i / s * 10), 0, i % s * 10), {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        } else if (entity.type === 'object') {
          serv.spawnObject(entity.id, player.world, player.position.offset(Math.floor(i / s * 10), 0, i % s * 10), {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        }
      }
    }
  })

  player.commands.add({
    base: 'pile',
    info: 'make a pile of entities',
    usage: '/pile <entities types>',
    op: true,
    parse (str) {
      const args = str.split(' ')
      if (args.length === 0) { return false }
      return args
        .map(name => entitiesByName[name])
        .filter(entity => !!entity)
    },
    action (entityTypes) {
      if (Object.keys(serv.entities).length > options['max-entities'] - entityTypes.length) { throw new UserError('Too many mobs !') }
      entityTypes.map(entity => {
        if (entity.type === 'mob') {
          return serv.spawnMob(entity.id, player.world, player.position, {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        } else if (entity.type === 'object') {
          return serv.spawnObject(entity.id, player.world, player.position, {
            velocity: Vec3((Math.random() - 0.5) * 10, Math.random() * 10 + 10, (Math.random() - 0.5) * 10)
          })
        }
      })
        .reduce((prec, entity) => {
          if (prec !== null) { prec.attach(entity) }
          return entity
        }, null)
    }
  })

  player.commands.add({
    base: 'attach',
    info: 'attach an entity on an other entity',
    usage: '/attach <carrier> <attached>',
    op: true,
    parse (str) {
      const args = str.split(' ')
      if (args.length !== 2) { return false }

      const carrier = player.selectorString(args[0])
      if (carrier.length === 0) throw new UserError('one carrier')
      const attached = player.selectorString(args[1])
      if (attached.length === 0) throw new UserError('one attached')

      return { carrier: carrier[0], attached: attached[0] }
    },
    action ({ carrier, attached }) {
      carrier.attach(attached)
    }
  })

  player.spawnEntity = entity => {
    player._client.write(entity.spawnPacketName, entity.getSpawnPacket())
    if (typeof entity.itemId !== 'undefined') {
      entity.sendMetadata([{
        key: 10,
        type: 5,
        value: {
          blockId: entity.itemId,
          itemDamage: entity.itemDamage,
          itemCount: 1
        }
      }])
    }
    entity.equipment.forEach((equipment, slot) => {
      if (equipment !== undefined) {
        player._client.write('entity_equipment', {
          entityId: entity.id,
          slot: slot,
          item: Item.toNotch(equipment)
        })
      }
    }
    )
  }
}

module.exports.entity = function (entity, serv) {
  entity.initEntity = (type, entityType, world, position) => {
    entity.type = type
    entity.spawnPacketName = ''
    entity.entityType = entityType
    entity.world = world
    entity.position = position
    entity.lastPositionPlayersUpdated = entity.position.clone()
    entity.nearbyEntities = []
    entity.viewDistance = 150
    entity.score = {}

    entity.bornTime = Date.now()
    serv.entities[entity.id] = entity

    if (entity.type === 'player') entity.spawnPacketName = 'named_entity_spawn'
    else if (entity.type === 'object') entity.spawnPacketName = 'spawn_entity'
    else if (entity.type === 'mob') entity.spawnPacketName = 'spawn_entity_living'
  }

  entity.getSpawnPacket = () => {
    let scaledVelocity = entity.velocity.scaled(8000 / 20) // from fixed-position/second to unit => 1/8000 blocks per tick
    if (serv.supportFeature('fixedPointPosition')) {
      scaledVelocity = scaledVelocity.scaled(1 / 32)
    }
    scaledVelocity = scaledVelocity.floored()

    let entityPosition
    if (serv.supportFeature('fixedPointPosition')) {
      entityPosition = entity.position.scaled(32).floored()
    } else if (serv.supportFeature('doublePosition')) {
      entityPosition = entity.position
    }

    if (entity.type === 'player') {
      return {
        entityId: entity.id,
        playerUUID: entity.uuid,
        x: entityPosition.x,
        y: entityPosition.y,
        z: entityPosition.z,
        yaw: entity.yaw,
        pitch: entity.pitch,
        currentItem: 0,
        metadata: entity.metadata
      }
    } else if (entity.type === 'object') {
      return {
        entityId: entity.id,
        objectUUID: entity.uuid,
        type: entity.entityType,
        x: entityPosition.x,
        y: entityPosition.y,
        z: entityPosition.z,
        pitch: entity.pitch,
        yaw: entity.yaw,
        objectData: {
          intField: entity.data,
          velocityX: scaledVelocity.x,
          velocityY: scaledVelocity.y,
          velocityZ: scaledVelocity.z
        }
      }
    } else if (entity.type === 'mob') {
      return {
        entityId: entity.id,
        entityUUID: entity.uuid,
        type: entity.entityType,
        x: entityPosition.x,
        y: entityPosition.y,
        z: entityPosition.z,
        yaw: entity.yaw,
        pitch: entity.pitch,
        headPitch: entity.headPitch,
        velocityX: scaledVelocity.x,
        velocityY: scaledVelocity.y,
        velocityZ: scaledVelocity.z,
        metadata: entity.metadata
      }
    }
  }

  entity.updateAndSpawn = () => {
    const updatedEntities = entity.getNearby()
    const entitiesToAdd = updatedEntities.filter(e => entity.nearbyEntities.indexOf(e) === -1)
    const entitiesToRemove = entity.nearbyEntities.filter(e => updatedEntities.indexOf(e) === -1)
    if (entity.type === 'player') {
      entity.despawnEntities(entitiesToRemove)
      entitiesToAdd.forEach(entity.spawnEntity)
    }
    entity.lastPositionPlayersUpdated = entity.position.clone()

    const playersToAdd = entitiesToAdd.filter(e => e.type === 'player')
    const playersToRemove = entitiesToRemove.filter(e => e.type === 'player')

    playersToRemove.forEach(p => p.despawnEntities([entity]))
    playersToRemove.forEach(p => { p.nearbyEntities = p.getNearby() })
    playersToAdd.forEach(p => p.spawnEntity(entity))
    playersToAdd.forEach(p => { p.nearbyEntities = p.getNearby() })

    entity.nearbyEntities = updatedEntities
  }

  entity.on('move', () => {
    if (entity.position.distanceTo(entity.lastPositionPlayersUpdated) > 2) { entity.updateAndSpawn() }
  })

  entity.destroy = () => {
    serv.destroyEntity(entity)
  }

  entity.attach = (attachedEntity, leash = false) => {
    if (serv.supportFeature('attachStackEntity') || (serv.supportFeature('setPassengerStackEntity') && leash)) {
      const p = {
        entityId: attachedEntity.id,
        vehicleId: entity.id,
        leash: leash
      }
      if (entity.type === 'player') { entity._client.write('attach_entity', p) }
      entity._writeOthersNearby('attach_entity', p)
    }
    if (serv.supportFeature('setPassengerStackEntity')) {
      const p = {
        entityId: entity.id,
        passengers: [attachedEntity.id]
      }
      if (entity.type === 'player') { entity._client.write('set_passengers', p) }
      entity._writeOthersNearby('set_passengers', p)
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import {
  Text,
  View,
  ListView,
  ScrollView,
  TouchableOpacity,
  Image,
  ActivityIndicator,
  Modal,
  TouchableHighlight
} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import Axios from 'axios'

import { styles, styleBasket, styleSearch, color } from '../styles'

const API = 'http://ec2-18-220-197-230.us-east-2.compute.amazonaws.com:3000/api'

export default class Basket extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
      data: [],
      id: null,
      loading: false,
      loaded: false,
      modalVisible: false,
    }
  }

  _fetchData() {
    Axios.get(API + '/baskets/getitems/2')
    .then((response) => {
      console.log(response)
      this._getData(response.data)
    })
    .catch((error) => {
      console.log(error)
    })
  }

  _getData(data) {
    const ds = this.state.dataSource.cloneWithRows(data || [])
    this.setState({'data': ds, loading: false, loaded: true})
    console.log(this.state.data.getRowCount() + ' Row Count testing')
  }

  _deleteItem(goodsId) {
    this.setState({ loading: true })

    Axios.delete(API + '/baskets/2/' + goodsId +'/removeitem', {
      basket_id: 2,
      goods_id: goodsId
    })
    .then((response) => {
      console.log(response)
      this._fetchData()
    })
    .catch((error) => {
      console.log(error)
    })
  }

  _setModalVisible(visible) {
    this.setState({modalVisible: visible});
  }

  _postCompare() {
    Axios.post(API + '/stores/nearbystore', {
      "location": {
        "lat": -6.260740, "lng": 106.782024
      },
      "items": [
        {
          "goodId": 1,
          "quantity": 1
        },
        {
          "goodId": 5,
          "quantity": 1
        }
      ]
    })
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
  }

  _renderProduct(product) {
    return (
      <View style={styleBasket.item}>
        <Image
          source={{ uri: product.Good.url_pict }}
          style={styleBasket.imgStyle}
        />
        <View style={styleBasket.textContainer}>
          <Text style={styleBasket.headingStyle}>{product.Good.name}</Text>
          <Text>Ukuran: {product.Good.goods_size}</Text>
        </View>
        <TouchableOpacity style={styleBasket.clearIcon}
          onPress = {() => {
            this.setState({ id: product.Good.id })
            this._setModalVisible(true)
          }} >
          <Icon
            name="ios-close"
            size={30}
            color='red'
          />
        </TouchableOpacity>
      </View>
    )
  }

  componentWillMount() {
    this.setState({ loading: true })
    this._fetchData()
  }

  render() {
    return (
      <ScrollView style={styleBasket.container}>
        <View style={styleBasket.headerContainer}>
          <Text style={styleBasket.headerText}>Your basket..</Text>
        </View>
        <View style={styleBasket.listContainer}>
          {  this.state.loading &&
            <ActivityIndicator
              animating={this.state.animating}
              size={60}
              color={color.lightBlue}
            />
          }
          { !this.state.loading && this.state.loaded && this.state.data.getRowCount() === 0 &&
            <View style={styles.container}>
              <Text style={styles.notFound}>Your basket is empty :(</Text>
            </View>
          }
          { !this.state.loading && this.state.loaded &&
            <ListView contentContainerStyle={styleBasket.list}
            dataSource={this.state.data}
            enableEmptySections={true}
            renderRow={this._renderProduct.bind(this)}>
            </ListView>
          }
        </View>
        { !this.state.loading && this.state.loaded && this.state.data.getRowCount() !== 0 &&
          <View style={styleBasket.buttonContainer}>
          <Icon.Button name="ios-pricetags-outline" style={styleBasket.button} onPress={() => this._postCompare()}>
            <Text style={styleBasket.headerText}>compare</Text>
          </Icon.Button>
          </View>
        }
        <Modal
          animationType={"fade"}
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => this._setModalVisible(!this.state.modalVisible)}
          >
           <View style={styleSearch.containerModal}>
            <View style={styleSearch.modalStyle}>
              <Text style={styleSearch.textModal}>Are you sure?</Text>
              <View style={styleSearch.containerButton}>
                <TouchableHighlight style={styleSearch.buttonYes} activeOpacity={0.5} underlayColor={color.lightBlue} onPress={() => {
                  console.log('yes button')
                  this._setModalVisible(!this.state.modalVisible)
                  this._deleteItem(this.state.id)
                  this.setState({ id: null })
                }}>
                  <Text style={styleSearch.textButton}>Yes</Text>
                </TouchableHighlight>
                <TouchableHighlight style={styleSearch.buttonNo} activeOpacity={0.5} underlayColor={color.orange} onPress={() => {
                  console.log('no button')
                  this._setModalVisible(!this.state.modalVisible)
                }}>
                  <Text style={styleSearch.textButton}>No</Text>
                </TouchableHighlight>
              </View>
            </View>
          </View>
        </Modal>
      </ScrollView>
    )
  }
}
<commit_msg>fetching compare done<commit_after>import React from 'react'
import {
  Text,
  View,
  ListView,
  ScrollView,
  TouchableOpacity,
  Image,
  ActivityIndicator,
  Modal,
  TouchableHighlight
} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import Axios from 'axios'

import { styles, styleBasket, styleSearch, color } from '../styles'

const API = 'http://ec2-18-220-197-230.us-east-2.compute.amazonaws.com:3000/api'

export default class Basket extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
      data: [],
      id: null,
      loading: false,
      loaded: false,
      modalVisible: false,
    }
  }

  _fetchData() {
    Axios.get(API + '/baskets/getitems/2')
    .then((response) => {
      this.setState({compareData: response.data})

      this._getData(response.data)
    })
    .catch((error) => {
      console.log(error)
    })
  }

  _getData(data) {
    const ds = this.state.dataSource.cloneWithRows(data || [])
    this.setState({'data': ds, loading: false, loaded: true})
    console.log(this.state.data.getRowCount() + ' Row Count testing')
  }

  _postCompare() {
    let data = this.state.compareData
    console.log(data, ' --------COMPARE')

    var items = data.map((dataItem) => {
      return {
        goodId: dataItem.Good.id,
        quantity: dataItem.quantity
      }
    });

    let lat, lng
    navigator.geolocation.getCurrentPosition((position) => {
      lat = parseFloat(position.coords.latitude)
      lng = parseFloat(position.coords.longitude)

      // Axios.post(API + '/stores/nearbystore', {
      //   "location": {
      //     "lat": lat, "lng": lng
      //   },
      //   "items": [
      //     {
      //       "goodId": 1,
      //       "quantity": 1
      //     },
      //     {
      //       "goodId": 5,
      //       "quantity": 1
      //     }
      //   ]
      // })
      Axios.post(API + '/stores/nearbystore', {
        location: {
          lat, lng
        },
        items,
      })
      .then((response) => {
        console.log(response)
      })
      .catch((error) => {
        console.log(error)
      })
    })
  }

  _deleteItem(goodsId) {
    this.setState({ loading: true })

    Axios.delete(API + '/baskets/2/' + goodsId +'/removeitem', {
      basket_id: 2,
      goods_id: goodsId
    })
    .then((response) => {
      console.log(response)
      this._fetchData()
    })
    .catch((error) => {
      console.log(error)
    })
  }

  _setModalVisible(visible) {
    this.setState({modalVisible: visible});
  }

  _renderProduct(product) {
    return (
      <View style={styleBasket.item}>
        <Image
          source={{ uri: product.Good.url_pict }}
          style={styleBasket.imgStyle}
        />
        <View style={styleBasket.textContainer}>
          <Text style={styleBasket.headingStyle}>{product.Good.name}</Text>
          <Text>Ukuran: {product.Good.goods_size}</Text>
        </View>
        <TouchableOpacity style={styleBasket.clearIcon}
          onPress = {() => {
            this.setState({ id: product.Good.id })
            this._setModalVisible(true)
          }} >
          <Icon
            name="ios-close"
            size={30}
            color='red'
          />
        </TouchableOpacity>
      </View>
    )
  }

  componentWillMount() {
    this.setState({ loading: true })
    this._fetchData()
  }

  render() {
    return (
      <ScrollView style={styleBasket.container}>
        <View style={styleBasket.headerContainer}>
          <Text style={styleBasket.headerText}>Your basket..</Text>
        </View>
        <View style={styleBasket.listContainer}>
          {  this.state.loading &&
            <ActivityIndicator
              animating={this.state.animating}
              size={60}
              color={color.lightBlue}
            />
          }
          { !this.state.loading && this.state.loaded && this.state.data.getRowCount() === 0 &&
            <View style={styles.container}>
              <Text style={styles.notFound}>Your basket is empty :(</Text>
            </View>
          }
          { !this.state.loading && this.state.loaded &&
            <ListView contentContainerStyle={styleBasket.list}
            dataSource={this.state.data}
            enableEmptySections={true}
            renderRow={this._renderProduct.bind(this)}>
            </ListView>
          }
        </View>
        { !this.state.loading && this.state.loaded && this.state.data.getRowCount() !== 0 &&
          <View style={styleBasket.buttonContainer}>
          <Icon.Button name="ios-pricetags-outline" style={styleBasket.button} onPress={() => this._postCompare()}>
            <Text style={styleBasket.headerText}>compare</Text>
          </Icon.Button>
          </View>
        }
        <Modal
          animationType={"fade"}
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => this._setModalVisible(!this.state.modalVisible)}
          >
           <View style={styleSearch.containerModal}>
            <View style={styleSearch.modalStyle}>
              <Text style={styleSearch.textModal}>Are you sure?</Text>
              <View style={styleSearch.containerButton}>
                <TouchableHighlight style={styleSearch.buttonYes} activeOpacity={0.5} underlayColor={color.lightBlue} onPress={() => {
                  console.log('yes button')
                  this._setModalVisible(!this.state.modalVisible)
                  this._deleteItem(this.state.id)
                  this.setState({ id: null })
                }}>
                  <Text style={styleSearch.textButton}>Yes</Text>
                </TouchableHighlight>
                <TouchableHighlight style={styleSearch.buttonNo} activeOpacity={0.5} underlayColor={color.orange} onPress={() => {
                  console.log('no button')
                  this._setModalVisible(!this.state.modalVisible)
                }}>
                  <Text style={styleSearch.textButton}>No</Text>
                </TouchableHighlight>
              </View>
            </View>
          </View>
        </Modal>
      </ScrollView>
    )
  }
}
<|endoftext|>


<commit_before>/*
 * Popcorn Time Remote control uses socket.io to manage
 * communications between the mobile app and
 * the desktop popcorn-time app running
 */

try {

	var os=require('os');
	var localname = os.hostname();
	console.log("local machine name: " +localname);

	var ifaces=os.networkInterfaces();

	for (var dev in ifaces) {
		var alias=0;
		ifaces[dev].forEach(function(details){
			if(details.family=='IPv4') {
				if(dev.match(/^en/)) {
					intra = details.address;
				}
			}
		});
	}

	var rcapp  = require('express')();
	var rchttp = require('http').Server(rcapp);

	var remotecontrol = new (function(){

		this._movie = {};

		this.showControl = function() {
			io.sockets.emit("show control");
		}

		this.setMovie = function(movie) {
			this._movie = movie;
		}

		this.showMovieDetail = function(){
			io.sockets.emit("show movie detail", this._movie);
		}

		this.showDownloading = function() {
			io.sockets.emit("show downloading", this._movie);
		}

		this.showPlaying = function() {
			io.sockets.emit("show playing", this._movie);
		}

		this.startStreaming = function() {
			$(".movie-btn.watch").trigger("click");
		}

		this.cancelStreaming = function() {
			$(".loading-cancel").trigger("click");
		}

		this.triggerKeyPress = function(key) {
			var el = document.getElementsByTagName("body");
				  el = el[0];
			if(document.createEventObject){
				var eventObj = document.createEventObject();
				eventObj.keyCode = key;
				el.fireEvent("onkeydown", eventObj);
			} else if(document.createEvent)	{
				var eventObj = document.createEvent("Events");
				eventObj.initEvent("keydown", true, true);
				eventObj.which = key;
				el.dispatchEvent(eventObj);
			}
		}

		this.moveLeft = function() {
			this.triggerKeyPress(37);
		}

		this.moveRight = function() {
			this.triggerKeyPress(39);
		}

		this.moveUp = function() {
			this.triggerKeyPress(38);
		}

		this.moveDown = function() {
			this.triggerKeyPress(40);
		}

		this.enter = function() {
			this.triggerKeyPress(13);
		}

		this.esc = function() {
			this.triggerKeyPress(27);
		}

		this.play = function() {
			try { videojs("video_player").play(); }catch(e) { console.log(e);	}
		}

		this.pause = function() {
			try { videojs("video_player").pause(); }catch(e) { console.log(e); }
		}

		this.volumeup = function() {
			try {
				var howLoudIsIt = videojs("video_player").volume();
				howLoudIsIt  = howLoudIsIt + 0.1 > 1 ? 1 : howLoudIsIt + 0.1;
				videojs("video_player").volume(howLoudIsIt);
			} catch(e) {
				console.log(e);
			}
		}

		this.volumedown = function() {
			try {
				var howLoudIsIt = videojs("video_player").volume();
				howLoudIsIt  = howLoudIsIt - 0.1 < 0 ? 0 : howLoudIsIt - 0.1;
				videojs("video_player").volume(howLoudIsIt);
			} catch(e) {
				console.log(e);
			}
		}

		this.mute = function() {
			try { videojs("video_player").muted( videojs("video_player").muted() ? false : true ); }catch(e){ console.log(e); }
		}

		this.fullscreenToggle = function() {
			try {
				var nativeWindow = require('nw.gui').Window.get();
				if(nativeWindow.isFullscreen) {
					nativeWindow.leaveFullscreen();
					nativeWindow.focus();
				}else{
					nativeWindow.enterFullscreen();
					nativeWindow.focus();
				}
			}catch(e){
				alert(e);
			}
		}
	});

	rcapp.get('', function(req, res){
		res.writeHead(200, { 'Content-Type': 'text/html' });
		res.end("It's popcorn time remote control");
	});

	rcapp.get('/', function(req, res){
		res.writeHead(200, { 'Content-Type': 'text/html' });
		res.end("It's popcorn time remote control");
	});

	var io = require('socket.io')(rchttp);
	io.on('connection', function(socket){

		socket.emit("my name is", {name:localname});

		socket.on("start streaming", function(){
			remotecontrol.startStreaming();
		});

		socket.on("cancel streaming", function(){
			remotecontrol.cancelStreaming();
		});

		socket.on("move left", function(){
			remotecontrol.moveLeft();
		});

		socket.on("move up", function(){
			remotecontrol.moveUp();
		});

		socket.on("move right", function(){
			remotecontrol.moveRight();
		});

		socket.on("move down", function(){
			remotecontrol.moveDown();
		});

		socket.on("press enter", function(){
			remotecontrol.enter();
		});

		socket.on("press esc", function() {
			remotecontrol.esc();
		});

		socket.on("play", function(){
			remotecontrol.play();
		});

		socket.on("pause", function(){
			remotecontrol.pause();
		});

		socket.on("volume up", function(){
			remotecontrol.volumeup();
		});

		socket.on("volume down", function(){
			remotecontrol.volumedown();
		});

		socket.on("fullscreen", function(){
			remotecontrol.fullscreenToggle();
		});

		socket.on("mute", function(){
			remotecontrol.mute();
		});

	});

	rchttp.listen(8006, function(){
		console.log(intra +":8006 server listening to socket.io");
	});

}catch(e){
	console.log("rm error");
	console.log(e);
}
<commit_msg>add bug fixes<commit_after>/*
 * Popcorn Time Remote control uses socket.io to manage
 * communications between the mobile app and
 * the desktop popcorn-time app running
 */

try {

	var os=require('os');
	var localname = os.hostname();
	console.log("local machine name: " +localname);

	var ifaces=os.networkInterfaces();

	for (var dev in ifaces) {
		var alias=0;
		ifaces[dev].forEach(function(details){
			if(details.family=='IPv4') {
				if(dev.match(/^en/)) {
					intra = details.address;
				}
			}
		});
	}

	var rcapp  = require('express')();
	var rchttp = require('http').Server(rcapp);

	var remotecontrol = new (function(){

		this._movie = {};
		this._uistate = "control";

		this.showControl = function() {
			this._uistate = "control";
			io.sockets.emit("show control");
		}

		this.setMovie = function(movie) {
			this._movie = movie;
		}

		this.showMovieDetail = function(){
			this._uistate = "detail";
			io.sockets.emit("show movie detail", this._movie);
		}

		this.showDownloading = function() {
			this._uistate = "downloading";
			io.sockets.emit("show downloading", this._movie);
		}

		this.showPlaying = function() {
			this._uistate = "playing";
			io.sockets.emit("show playing", this._movie);
		}

		this.startStreaming = function() {
			$(".movie-btn.watch").trigger("click");
		}

		this.cancelStreaming = function() {
			$(".loading-cancel").trigger("click");
		}

		this.triggerKeyPress = function(key) {
			var el = document.getElementsByTagName("body");
				  el = el[0];
			if(document.createEventObject){
				var eventObj = document.createEventObject();
				eventObj.keyCode = key;
				el.fireEvent("onkeydown", eventObj);
			} else if(document.createEvent)	{
				var eventObj = document.createEvent("Events");
				eventObj.initEvent("keydown", true, true);
				eventObj.which = key;
				el.dispatchEvent(eventObj);
			}
		}

		this.moveLeft = function() {
			this.triggerKeyPress(37);
		}

		this.moveRight = function() {
			this.triggerKeyPress(39);
		}

		this.moveUp = function() {
			this.triggerKeyPress(38);
		}

		this.moveDown = function() {
			this.triggerKeyPress(40);
		}

		this.enter = function() {
			this.triggerKeyPress(13);
		}

		this.esc = function() {
			this.triggerKeyPress(27);
		}

		this.play = function() {
			try { videojs("video_player").play(); }catch(e) { console.log(e);	}
		}

		this.pause = function() {
			try { videojs("video_player").pause(); }catch(e) { console.log(e); }
		}

		this.volumeup = function() {
			try {
				var howLoudIsIt = videojs("video_player").volume();
				howLoudIsIt  = howLoudIsIt + 0.1 > 1 ? 1 : howLoudIsIt + 0.1;
				videojs("video_player").volume(howLoudIsIt);
			} catch(e) {
				console.log(e);
			}
		}

		this.volumedown = function() {
			try {
				var howLoudIsIt = videojs("video_player").volume();
				howLoudIsIt  = howLoudIsIt - 0.1 < 0 ? 0 : howLoudIsIt - 0.1;
				videojs("video_player").volume(howLoudIsIt);
			} catch(e) {
				console.log(e);
			}
		}

		this.mute = function() {
			try { videojs("video_player").muted( videojs("video_player").muted() ? false : true ); }catch(e){ console.log(e); }
		}

		this.fullscreenToggle = function() {
			try {
				var nativeWindow = require('nw.gui').Window.get();
				if(nativeWindow.isFullscreen) {
					nativeWindow.leaveFullscreen();
					nativeWindow.focus();
				}else{
					nativeWindow.enterFullscreen();
					nativeWindow.focus();
				}
			}catch(e){
				alert(e);
			}
		}
	});

	rcapp.get('', function(req, res){
		res.writeHead(200, { 'Content-Type': 'text/html' });
		res.end("It's popcorn time remote control");
	});

	rcapp.get('/', function(req, res){
		res.writeHead(200, { 'Content-Type': 'text/html' });
		res.end("It's popcorn time remote control");
	});

	var io = require('socket.io')(rchttp);
	io.on('connection', function(socket){

		socket.emit("my name is", {name:localname});

		socket.on("start streaming", function(){
			remotecontrol.startStreaming();
		});

		socket.on("cancel streaming", function(){
			remotecontrol.cancelStreaming();
		});

		socket.on("move left", function(){
			remotecontrol.moveLeft();
		});

		socket.on("move up", function(){
			remotecontrol.moveUp();
		});

		socket.on("move right", function(){
			remotecontrol.moveRight();
		});

		socket.on("move down", function(){
			remotecontrol.moveDown();
		});

		socket.on("press enter", function(){
			remotecontrol.enter();
		});

		socket.on("press esc", function() {
			remotecontrol.esc();
		});

		socket.on("play", function(){
			remotecontrol.play();
		});

		socket.on("pause", function(){
			remotecontrol.pause();
		});

		socket.on("volume up", function(){
			remotecontrol.volumeup();
		});

		socket.on("volume down", function(){
			remotecontrol.volumedown();
		});

		socket.on("fullscreen", function(){
			remotecontrol.fullscreenToggle();
		});

		socket.on("mute", function(){
			remotecontrol.mute();
		});

	});

	rchttp.listen(8006, function(){
		console.log(intra +":8006 server listening to socket.io");
	});

}catch(e){
	console.log("rm error");
	console.log(e);
}
<|endoftext|>