<commit_before>import { assign, isFunction, partialRight, defaults } from "lodash";
import React, { PropTypes } from "react";
import { PropTypes as CustomPropTypes, Events } from "../victory-util/index";

export default class VictorySharedEvents extends React.Component {
  static displayName = "VictorySharedEvents";

  static role = "shared-event-wrapper";

  static propTypes = {
    children: React.PropTypes.oneOfType([
      React.PropTypes.arrayOf(React.PropTypes.node),
      React.PropTypes.node
    ]),
    container: React.PropTypes.node,
    events: PropTypes.arrayOf(PropTypes.shape({
      childName: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.array
      ]),
      target: PropTypes.string,
      eventKey: PropTypes.oneOfType([
        PropTypes.array,
        PropTypes.func,
        CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]),
        PropTypes.string
      ]),
      eventHandlers: PropTypes.object
    })),
    eventKey: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.func,
      CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]),
      PropTypes.string
    ])
  };

  constructor() {
    super();
    this.state = {};
    this.getScopedEvents = Events.getScopedEvents.bind(this);
    this.getEventState = Events.getEventState.bind(this);
  }

  componentWillMount() {
    this.setUpChildren(this.props);
  }

  componentWillReceiveProps(newProps) {
    this.setUpChildren(newProps);
  }

  setUpChildren(props) {
    this.childComponents = React.Children.toArray(props.children);
    const childBaseProps = this.getBasePropsFromChildren(this.childComponents);
    const parentBaseProps = props.container ? { parent: props.container.props } : {};
    this.baseProps = assign({}, childBaseProps, {parent: parentBaseProps});
  }

  getBasePropsFromChildren(childComponents) {
    const getBaseProps = (children) => {
      return children.reduce((memo, child, index) => {
        if (child.type && isFunction(child.type.getBaseProps)) {
          const baseChildProps = child.props && child.type.getBaseProps(child.props);
          if (baseChildProps) {
            const childKey = child.props.name || index;
            memo[childKey] = baseChildProps;
            return memo;
          }
          return memo;
        } else if (child.props && child.props.children) {
          return getBaseProps(React.Children.toArray(child.props.children));
        }
        return memo;
      }, {});
    };
    return getBaseProps(childComponents);
  }

  getNewChildren(props) {
    const {events, eventKey} = props;
    const childNames = Object.keys(this.baseProps);

    const alterChildren = (children) => {
      return children.reduce((memo, child) => {
        if (child.type && isFunction(child.type.getBaseProps)) {
          const name = child.props.name || childNames.shift();
          const childEvents = Array.isArray(events) &&
            events.filter((event) => {
              return Array.isArray(event.childName) ?
                event.childName.indexOf(name) > -1 :
                event.childName === name || event.childName === "all";
            });
          const sharedEvents = {
            events: childEvents,
            getEvents: partialRight(this.getScopedEvents, name, this.baseProps),
            getEventState: partialRight(this.getEventState, name)
          };
          return memo.concat(React.cloneElement(child, assign(
            { key: `events-${name}`, sharedEvents, eventKey },
            child.props
          )));
        } else if (child.props.children) {
          return memo.concat(React.cloneElement(
            child,
            child.props,
            alterChildren(React.Children.toArray(child.props.children))
          ));
        } else {
          return memo.concat(child);
        }
      }, []);
    };

    return alterChildren(this.childComponents);
  }

  getContainer(props, children) {
    const parents = Array.isArray(props.events) &&
      props.events.filter((event) => event.target === "parent");
    const sharedEvents = parents.length > 0 ?
      {
        events: parents,
        getEvents: partialRight(this.getScopedEvents, null, this.baseProps),
        getEventState: partialRight(this.getEventState, null)
      } : null;
    const boundGetEvents = Events.getEvents.bind(this);
    const parentEvents = boundGetEvents({sharedEvents}, "parent");
    const parentProps = defaults(
      {},
      this.getEventState("parent", "parent"),
      props.container.props,
      this.baseProps.parent
    );
    return React.cloneElement(
      props.container,
      assign(
        {}, parentProps, {events: Events.getPartialEvents(parentEvents, "parent", parentProps)}
      ),
      children
    );
  }

  render() {
    const children = this.getNewChildren(this.props);
    return this.props.container ? this.getContainer(this.props, children) : <g>{children}</g>;

  }
}
<commit_msg>group component prop<commit_after>import { assign, isFunction, partialRight, defaults } from "lodash";
import React, { PropTypes } from "react";
import { PropTypes as CustomPropTypes, Events } from "../victory-util/index";

export default class VictorySharedEvents extends React.Component {
  static displayName = "VictorySharedEvents";

  static role = "shared-event-wrapper";

  static propTypes = {
    children: React.PropTypes.oneOfType([
      React.PropTypes.arrayOf(React.PropTypes.node),
      React.PropTypes.node
    ]),
    container: React.PropTypes.node,
    groupComponent: React.PropTypes.node,
    events: PropTypes.arrayOf(PropTypes.shape({
      childName: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.array
      ]),
      target: PropTypes.string,
      eventKey: PropTypes.oneOfType([
        PropTypes.array,
        PropTypes.func,
        CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]),
        PropTypes.string
      ]),
      eventHandlers: PropTypes.object
    })),
    eventKey: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.func,
      CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]),
      PropTypes.string
    ])
  };

  static defaultProps = {
    groupComponent: <g/>
  };

  constructor() {
    super();
    this.state = {};
    this.getScopedEvents = Events.getScopedEvents.bind(this);
    this.getEventState = Events.getEventState.bind(this);
  }

  componentWillMount() {
    this.setUpChildren(this.props);
  }

  componentWillReceiveProps(newProps) {
    this.setUpChildren(newProps);
  }

  setUpChildren(props) {
    this.childComponents = React.Children.toArray(props.children);
    const childBaseProps = this.getBasePropsFromChildren(this.childComponents);
    const parentBaseProps = props.container ? { parent: props.container.props } : {};
    this.baseProps = assign({}, childBaseProps, {parent: parentBaseProps});
  }

  getBasePropsFromChildren(childComponents) {
    const getBaseProps = (children) => {
      return children.reduce((memo, child, index) => {
        if (child.type && isFunction(child.type.getBaseProps)) {
          const baseChildProps = child.props && child.type.getBaseProps(child.props);
          if (baseChildProps) {
            const childKey = child.props.name || index;
            memo[childKey] = baseChildProps;
            return memo;
          }
          return memo;
        } else if (child.props && child.props.children) {
          return getBaseProps(React.Children.toArray(child.props.children));
        }
        return memo;
      }, {});
    };
    return getBaseProps(childComponents);
  }

  getNewChildren(props) {
    const {events, eventKey} = props;
    const childNames = Object.keys(this.baseProps);

    const alterChildren = (children) => {
      return children.reduce((memo, child) => {
        if (child.type && isFunction(child.type.getBaseProps)) {
          const name = child.props.name || childNames.shift();
          const childEvents = Array.isArray(events) &&
            events.filter((event) => {
              return Array.isArray(event.childName) ?
                event.childName.indexOf(name) > -1 :
                event.childName === name || event.childName === "all";
            });
          const sharedEvents = {
            events: childEvents,
            getEvents: partialRight(this.getScopedEvents, name, this.baseProps),
            getEventState: partialRight(this.getEventState, name)
          };
          return memo.concat(React.cloneElement(child, assign(
            { key: `events-${name}`, sharedEvents, eventKey },
            child.props
          )));
        } else if (child.props.children) {
          return memo.concat(React.cloneElement(
            child,
            child.props,
            alterChildren(React.Children.toArray(child.props.children))
          ));
        } else {
          return memo.concat(child);
        }
      }, []);
    };

    return alterChildren(this.childComponents);
  }

  getContainer(props, children) {
    const parents = Array.isArray(props.events) &&
      props.events.filter((event) => event.target === "parent");
    const sharedEvents = parents.length > 0 ?
      {
        events: parents,
        getEvents: partialRight(this.getScopedEvents, null, this.baseProps),
        getEventState: partialRight(this.getEventState, null)
      } : null;
    const container = this.props.container || this.props.groupComponent;
    const boundGetEvents = Events.getEvents.bind(this);
    const parentEvents = boundGetEvents({sharedEvents}, "parent");
    const parentProps = defaults(
      {},
      this.getEventState("parent", "parent"),
      container.props,
      this.baseProps.parent
    );
    return React.cloneElement(
      container,
      assign(
        {}, parentProps, {events: Events.getPartialEvents(parentEvents, "parent", parentProps)}
      ),
      children
    );
  }

  render() {
    const children = this.getNewChildren(this.props);
    return this.getContainer(this.props, children);
  }
}
<|endoftext|>


<commit_before>/**
 * Created by chrisng on 3/15/17.
 */
import m from '../../models';

async function getOwnNews(req, res) {
  try {
    const { offset } = this.params;
    const limit = 20;
    let news = [];
    const user = await m.User.find({ where: { id: req.user.id }, include: [{ model: m.Brand }] });
    for (let i = 0; i < user.Brands.length; i++) {
      const query = {
        where: { type: 'News' },
        include: [
          { model: m.Brand, where: { id: user.Brands[i].id } },
          { model: m.Site },
        ],
        limit,
        offset,
      };
      const relevantArticles = await m.Info.findAll(query);
      news = news.concat(relevantArticles);
    }
    res.status(200).send({ success: true, news });
  } catch(err) {
    console.error(`Error retrieving news for user ${req.user.id}: ${JSON.stringify(err)}`);
    res.status(500).send({ success: false, message: JSON.stringify(err) });
  }
}

async function getOwnSales(req, res) {
  try {
    const { offset } = this.params;
    const limit = 20;
    let sales = [];
    const user = await m.User.find({ where: { id: req.user.id }, include: [{ model: m.Brand }] });
    for (let i = 0; i < user.Brands.length; i++) {
      const query = {
        where: { type: 'Sale' },
        include: [
          { model: m.Brand, where: { id: user.Brands[i].id } },
          { model: m.Site },
        ],
        limit,
        offset,
      };
      const relevantArticles = await m.Info.findAll(query);
      sales = sales.concat(relevantArticles);
    }
    res.status(200).send({ success: true, sales });
  } catch(err) {
    console.error(`Error retrieving sales for user ${req.user.id}: ${JSON.stringify(err)}`);
    res.status(500).send({ success: false, message: JSON.stringify(err) });
  }
}

module.exports = { getOwnNews, getOwnSales };
<commit_msg>refactor query for user sales/news<commit_after>/**
 * Created by chrisng on 3/15/17.
 */
import m from '../../models';

async function getOwnNews(req, res) {
  try {
    let { offset } = req.params;
    offset = parseInt(offset);
    const limit = 20;
    const user = await m.User.find({ where: { id: req.user.id }, include: [{ model: m.Brand }] });
    const brandIds = user.Brands.map(brand => brand.id);
    const query = {
      where: { type: 'News' },
      include: [
        { model: m.Brand, where: { id: { $in: brandIds } } },
        { model: m.Site },
      ],
      order: 'date DESC',
      limit,
      offset,
    };
    const news = await m.Info.findAll(query);
    res.status(200).send({ success: true, news });
  } catch(err) {
    console.error(`Error retrieving news for user ${req.user.id}: ${JSON.stringify(err)}`);
    res.status(500).send({ success: false, message: JSON.stringify(err) });
  }
}

async function getOwnSales(req, res) {
  try {
    let { offset } = req.params;
    offset = parseInt(offset);
    const limit = 20;
    const user = await m.User.find({ where: { id: req.user.id }, include: [{ model: m.Brand }] });
    const brandIds = user.Brands.map(brand => brand.id);
    const query = {
      where: { type: 'Sale' },
      include: [
        { model: m.Brand, where: { id: { $in: brandIds } } },
        { model: m.Site },
      ],
      order: 'date DESC',
      limit,
      offset,
    };
    const sales = await m.Info.findAll(query);
    res.status(200).send({ success: true, sales });
  } catch(err) {
    console.error(`Error retrieving sales for user ${req.user.id}: ${JSON.stringify(err)}`);
    res.status(500).send({ success: false, message: JSON.stringify(err) });
  }
}

module.exports = { getOwnNews, getOwnSales };
<|endoftext|>


<commit_before>//Note that Javascript does not have Liquid template syntax.
//I am actually curious to see if Javascript can even run.

//Hover over the image to start GIF animation.
$(document).ready(function(){
	//ID uses #.
	//Marble Run
	$("#project001").hover(
         //This function is mouseOver. GIF goes here.
         function(){
         	$(this).attr("src", "../assets/proj_marble_run.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_marble_run.png");
         }
 	);
 	//Pixavive Survival
 	$("#project002").hover(
         //This function is mouseOver. GIF goes here.
         function(){
         	$(this).attr("src", "../assets/proj_pixavive.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_pixavive.png");
         }
 	);
 	//Pokemon Walking
 	$("#project003").hover(
         //This function is mouseOver. GIF goes here.
         function(){
         	$(this).attr("src", "../assets/proj_walking.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_walking.png");
         }
 	);
 	//Bluetooth
 	$("#project004").hover(
         //This function is mouseOver. GIF goes here.
         //Note that due to the nature of the project, there is no GIF available.
         function(){
         	$(this).attr("src", "../assets/proj_bluetooth.png");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_bluetooth.png");
         }
 	);
   	//Rotation
   	$("#project011").hover(
         //This function is mouseOver. GIF goes here.
         //Note that due to the nature of the project, there is no GIF available.
         function(){
            $(this).attr("src", "../assets/proj_rotation.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
            $(this).attr("src", "../assets/proj_rotation.png");
         }
        $("#project012").hover(
         //This function is mouseOver. GIF goes here.
         //Note that due to the nature of the project, there is no GIF available.
         function(){
            $(this).attr("src", "../assets/proj_getdebt.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
            $(this).attr("src", "../assets/proj_getdebt.png");
         }
        );
   );
});
<commit_msg>Fixed error. Really need a JS editor.<commit_after>//Note that Javascript does not have Liquid template syntax.
//I am actually curious to see if Javascript can even run.

//Hover over the image to start GIF animation.
$(document).ready(function(){
	//ID uses #.
	//Marble Run
	$("#project001").hover(
         //This function is mouseOver. GIF goes here.
         function(){
         	$(this).attr("src", "../assets/proj_marble_run.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_marble_run.png");
         }
 	);
 	//Pixavive Survival
 	$("#project002").hover(
         //This function is mouseOver. GIF goes here.
         function(){
         	$(this).attr("src", "../assets/proj_pixavive.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_pixavive.png");
         }
 	);
 	//Pokemon Walking
 	$("#project003").hover(
         //This function is mouseOver. GIF goes here.
         function(){
         	$(this).attr("src", "../assets/proj_walking.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_walking.png");
         }
 	);
 	//Bluetooth
 	$("#project004").hover(
         //This function is mouseOver. GIF goes here.
         //Note that due to the nature of the project, there is no GIF available.
         function(){
         	$(this).attr("src", "../assets/proj_bluetooth.png");
         },
         //This function is mouseOut. Static image goes here.
         function(){
         	$(this).attr("src", "../assets/proj_bluetooth.png");
         }
 	);
   	//Rotation
   	$("#project011").hover(
         //This function is mouseOver. GIF goes here.
         //Note that due to the nature of the project, there is no GIF available.
         function(){
            $(this).attr("src", "../assets/proj_rotation.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
            $(this).attr("src", "../assets/proj_rotation.png");
         }
      );
    $("#project012").hover(
         //This function is mouseOver. GIF goes here.
         //Note that due to the nature of the project, there is no GIF available.
         function(){
            $(this).attr("src", "../assets/proj_getdebt.gif");
         },
         //This function is mouseOut. Static image goes here.
         function(){
            $(this).attr("src", "../assets/proj_getdebt.png");
         }
     );
});
<|endoftext|>


<commit_before>import React, {Component} from 'react'
require('./GridView.scss')
var ReactDataGrid = require('react-data-grid/addons')
import TagsEditor from 'components/TagsEditor'
import TagsFormatter from 'components/TagsFormatter'
var options = ['prueba1', 'prueba2', 'prueba3', 'prueba4', 'asdfasñdlk fjkñasñldkf asdfj ñ']
var tagsEditor = <TagsEditor options={options}/>

var Toolbar = ReactDataGrid.Toolbar

var _rows = []
for (var i = 1; i < 1000; i++) {
  _rows.push({
    _id: i,
    name: 'Name_en ' + i,
    tags: 'Tags_en ' + i,
    filters: 'Filter_tags_en ' + i,
    name_locale: i,
    tags_locale: 'Tags_locale ' + i,
    filters_locale: 'Filter_tags_locale ' + i
  })
}

var columns = [
  {
    key: '_id',
    name: 'ID',
    resizable: true,
    width: 1
  },
  {
    key: 'name',
    name: 'Name',
    resizable: true,
    width: 220,
    filterable: true
  },
  {
    key: 'tags',
    name: 'Tags',
    resizable: true,
    width: 220,
    filterable: true
  },
  {
    key: 'filters',
    name: 'Filters',
    resizable: true,
    width: 220,
    filterable: true
  },
  {
    key: 'name_locale',
    name: 'Name',
    resizable: true,
    width: 220,
    filterable: true,
    editable: true
  },
  {
    key: 'tags_locale',
    name: 'Tags',
    resizable: true,
    filterable: true,
    width: 400,
    editor: tagsEditor,
    formatter: TagsFormatter
  },
  {
    key: 'filters_locale',
    name: 'Filters',
    resizable: true,
    filterable: true
  }
]

class PictogramsGridView extends Component {
  constructor(props) {
    super(props)
    this.handleRowUpdated = this.handleRowUpdated.bind(this)
    this.handleFilterChange = this.handleFilterChange.bind(this)
    this.rowGetter = this.rowGetter.bind(this)

    this.state = {
      originalRows: _rows,
      rows: _rows,
      filters: {}
    }
  }

  rowGetter(rowIdx) {
    return this.state.rows[rowIdx]
  }

  handleFilterChange(filter) {
    this.setState(function(currentState) {
      if (filter.filterTerm) {
        currentState.filters[filter.columnKey] = filter.filterTerm
      } else {
        delete currentState.filters[filter.columnKey]
      }
      currentState.rows = this.filterRows(currentState.originalRows, currentState.filters)
      return currentState
    })
  }

  filterRows(originalRows, filters) {
    var rows = originalRows.filter(function(r) {
      var include = true
      for (var columnKey in filters) {
        if (filters.hasOwnProperty(columnKey)) {
          var rowValue = r[columnKey].toString().toLowerCase()
          if (rowValue.indexOf(filters[columnKey].toLowerCase()) === -1) {
            include = false
          }
        }
      }
      return include
    })
    return rows
  }

  handleRowUpdated(e) {
    // merge updated row with current row and rerender by setting state
    var rows = this.state.rows
    Object.assign(rows[e.rowIdx], e.updated)
    this.setState({rows: rows})
  }

  render() {
    return (

          <ReactDataGrid columns={columns} rowGetter={this.rowGetter} rowsCount={this.state.rows.length}
            rowHeight={100}
            toolbar={<Toolbar enableFilter={true}/>} onAddFilter={this.handleFilterChange}
            enableCellSelect={true} onRowUpdated={this.handleRowUpdated} minHeight={500} />

    )
  }
}

export default PictogramsGridView
<commit_msg>Add column for pictograms<commit_after>import React, {Component} from 'react'
require('./GridView.scss')
var ReactDataGrid = require('react-data-grid/addons')
import TagsEditor from 'components/TagsEditor'
import TagsFormatter from 'components/TagsFormatter'
var options = ['prueba1', 'prueba2', 'prueba3', 'prueba4', 'asdfasñdlk fjkñasñldkf asdfj ñ']
var tagsEditor = <TagsEditor options={options}/>

var Toolbar = ReactDataGrid.Toolbar

var _rows = []
for (var i = 1; i < 1000; i++) {
  _rows.push({
    _id: i,
    pictogram: 'Imagen',
    name: 'Name_en ' + i,
    tags: 'Tags_en ' + i,
    filters: 'Filter_tags_en ' + i,
    name_locale: i,
    tags_locale: 'Tags_locale ' + i,
    filters_locale: 'Filter_tags_locale ' + i
  })
}

var columns = [
  {
    key: '_id',
    name: 'ID',
    resizable: true,
    width: 1
  },
  {
    key: 'pictograma',
    name: 'Pictograms',
    resizable: true,
    width: 120
  },
  {
    key: 'name',
    name: 'Name',
    resizable: true,
    width: 220,
    filterable: true
  },
  {
    key: 'tags',
    name: 'Tags',
    resizable: true,
    width: 220,
    filterable: true
  },
  {
    key: 'filters',
    name: 'Filters',
    resizable: true,
    width: 220,
    filterable: true
  },
  {
    key: 'name_locale',
    name: 'Name',
    resizable: true,
    width: 220,
    filterable: true,
    editable: true
  },
  {
    key: 'tags_locale',
    name: 'Tags',
    resizable: true,
    filterable: true,
    width: 400,
    editor: tagsEditor,
    formatter: TagsFormatter
  },
  {
    key: 'filters_locale',
    name: 'Filters',
    resizable: true,
    filterable: true,
    width: 300
  }
]

class PictogramsGridView extends Component {
  constructor(props) {
    super(props)
    this.handleRowUpdated = this.handleRowUpdated.bind(this)
    this.handleFilterChange = this.handleFilterChange.bind(this)
    this.rowGetter = this.rowGetter.bind(this)

    this.state = {
      originalRows: _rows,
      rows: _rows,
      filters: {}
    }
  }

  rowGetter(rowIdx) {
    return this.state.rows[rowIdx]
  }

  handleFilterChange(filter) {
    this.setState(function(currentState) {
      if (filter.filterTerm) {
        currentState.filters[filter.columnKey] = filter.filterTerm
      } else {
        delete currentState.filters[filter.columnKey]
      }
      currentState.rows = this.filterRows(currentState.originalRows, currentState.filters)
      return currentState
    })
  }

  filterRows(originalRows, filters) {
    var rows = originalRows.filter(function(r) {
      var include = true
      for (var columnKey in filters) {
        if (filters.hasOwnProperty(columnKey)) {
          var rowValue = r[columnKey].toString().toLowerCase()
          if (rowValue.indexOf(filters[columnKey].toLowerCase()) === -1) {
            include = false
          }
        }
      }
      return include
    })
    return rows
  }

  handleRowUpdated(e) {
    // merge updated row with current row and rerender by setting state
    var rows = this.state.rows
    Object.assign(rows[e.rowIdx], e.updated)
    this.setState({rows: rows})
  }

  render() {
    return (

          <ReactDataGrid columns={columns} rowGetter={this.rowGetter} rowsCount={this.state.rows.length}
            rowHeight={100}
            toolbar={<Toolbar enableFilter={true}/>} onAddFilter={this.handleFilterChange}
            enableCellSelect={true} onRowUpdated={this.handleRowUpdated} minHeight={500} />

    )
  }
}

export default PictogramsGridView
<|endoftext|>


<commit_before>(function() {

  // --------------------------------------------------------------

  const $$ = (el) => el.indexOf('.') === 0 ?
    document.getElementsByClassName(el)[0] : document.getElementById(el);
  const onClick = (el, fn) => $$(el).addEventListener('click', e => fn(e));
  const state = {
    lang: {}
  };

  // --------------------------------------------------------------

  const doLangCheck = function() {
    const text = $$('lang-input').value;
    console.log('Checking text : ', text);

    if (!state.lang.net) {
      const config = {
        iterations: 5000,
        log: true,
        logPeriod: 100,
        layers: [7],
      };

      const data = [
        { input: 'A lot of people invest in $TSLA for the first time, because they believe in Musk.', output: '$TSLA'},
        { input: 'That was a great opening for $TGT last sunday with an up margin of 4%.', output: '$TGT'},
        { input: '$PG down 1.7% with a low cap bust on Sunday. Investors are angry af.', output: '$PG'},
        { input: 'Looks like there is no hope for the $MMM ship sailing anytime soon. Investors keep their fingers crossed anyway.', output: '$MMM'},
        { input: 'Some brave people cashed out $TSLA and $JNJ stocks today. All went home happy!', output: '$TSLA $JNJ'},
        { input: 'As usual, $GOOG are killing it in the long run.', output: '$GOOG'},
        { input: 'No more downtime for $AMZN, as they move even upper in the charts of stock success.', output: '$AMZN'},
        { input: '$NFLX with astnoishing new series, invites new subscribers and ups their game.', output: '$NFLX'},
        { input: '$SNAP out of it, if you have invested a ton of your hard earned money.', output: '$SNAP'},
        { input: 'It is gonna be a dark day for $PLUG investors, as the stock plummets even more today.', output: '$PLUG'},
        { input: 'Grab all the $GRAB you can get. Take out your wallet, drop the $GOOG and do $GRAB.', output: '$GRAB $GOOG'}
      ];

      const network = new brain.recurrent.LSTM();
      network.train(data, config);

      state.lang.net = network;
    }

    const result = state.lang.net.run(text);
    console.log('result : ', result);

    $$('lang-result').innerHTML = result;
  };

  const doXor = function() {
    // provide optional config object (or undefined). Defaults shown.
    const config = {
      hiddenLayers: [3], // array of ints for the sizes of the hidden layers in the network
      activation: 'sigmoid' // supported activation types: ['sigmoid', 'relu', 'leaky-relu', 'tanh']
    };

    // create a simple feed forward neural network with backpropagation
    const net = new brain.NeuralNetwork(config);

    net.train([{
        input: [0, 0],
        output: [0]
      },
      {
        input: [0, 1],
        output: [1]
      },
      {
        input: [1, 0],
        output: [1]
      },
      {
        input: [1, 1],
        output: [0]
      }
    ]);

    const output = net.run([1, 0]); // [0.987]

    $$('xor-result').innerHTML = output;
  };

  // --------------------------------------------------------------

  onClick('xor', doXor);
  onClick('lang-check', doLangCheck);

})();
<commit_msg>Attempt to use another detection method<commit_after>(function() {

  // --------------------------------------------------------------

  const $$ = (el) => el.indexOf('.') === 0 ?
    document.getElementsByClassName(el)[0] : document.getElementById(el);
  const onClick = (el, fn) => $$(el).addEventListener('click', e => fn(e));
  const state = {
    lang: {}
  };

  // --------------------------------------------------------------

  const doLangCheck = function() {
    const text = $$('lang-input').value;
    console.log('Checking text : ', text);

    if (!state.lang.net) {
      const config = {
        iterations: 15000,
        log: true,
        logPeriod: 100,
        layers: [10],
      };

      const data = [
        { input: 'A lot of people invest in $TSLA for the first time, because they believe in Musk.', output: '$y'},
        { input: 'That was a great opening for $TGT last sunday with an up margin of 4%.', output: 'y'},
        { input: '$PG down 1.7% with a low cap bust on Sunday. Investors are angry af.', output: 'y'},
        { input: 'Looks like there is no hope for the $MMM ship sailing anytime soon. Investors keep their fingers crossed anyway.', output: 'y'},
        { input: 'Some brave people cashed out $TSLA and $JNJ stocks today. All went home happy!', output: 'y'},
        { input: 'As usual, $GOOG are killing it in the long run.', output: 'y'},
        { input: 'No more downtime for $AMZN, as they move even upper in the charts of stock success.', output: 'y'},
        { input: '$NFLX with astnoishing new series, invites new subscribers and ups their game.', output: 'y'},
        { input: '$SNAP out of it, if you have invested a ton of your hard earned money.', output: 'y'},
        { input: 'It is gonna be a dark day for $PLUG investors, as the stock plummets even more today.', output: 'y'},
        { input: 'Grab all the $GRAB you can get. Take out your wallet, drop the $GOOG and do $GRAB.', output: 'y'},

        { input: 'Grab all the stocks, no matter the price.', output: 'n'},
        { input: 'We are definitely making winnings this year. Just wait and see.', output: 'n'},
        { input: 'There are more open money slots and stocks to invest in, in the USA than any other place in the world.', output: 'n'},
        { input: 'No more downtime for Amazon, as they move even upper in the charts of stock success.', output: 'n'},
      ];

      const network = new brain.recurrent.LSTM();
      network.train(data, config);

      state.lang.net = network;
    }

    const result = state.lang.net.run(text);
    console.log('result : ', result);

    $$('lang-result').innerHTML = result === 'yes' ? 'YES' : 'NO';
  };

  const doXor = function() {
    // provide optional config object (or undefined). Defaults shown.
    const config = {
      hiddenLayers: [3], // array of ints for the sizes of the hidden layers in the network
      activation: 'sigmoid' // supported activation types: ['sigmoid', 'relu', 'leaky-relu', 'tanh']
    };

    // create a simple feed forward neural network with backpropagation
    const net = new brain.NeuralNetwork(config);

    net.train([{
        input: [0, 0],
        output: [0]
      },
      {
        input: [0, 1],
        output: [1]
      },
      {
        input: [1, 0],
        output: [1]
      },
      {
        input: [1, 1],
        output: [0]
      }
    ]);

    const output = net.run([1, 0]); // [0.987]

    $$('xor-result').innerHTML = output;
  };

  // --------------------------------------------------------------

  onClick('xor', doXor);
  onClick('lang-check', doLangCheck);

})();
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import {keyStringDetector} from '../registories/registory'

export default class Editor extends Component {

    const TWEET_LIMIT_LENGTH = 140;

    constructor(props) {
        super(props);
        this.state = {text: ''};
    }

    getRestTextLength() {
        return this.TWEET_LIMIT_LENGTH - this.state.text.length;
    }

    onTextareaChanged(event) {
        this.setState({text: event.target.value});
    }

    onTextareaKeyDown(event) {
        if (keyStringDetector.detect(event) === 'Return') {
            event.preventDefault();
            this.onTweetSubmitted();
        }
    }

    //TODO: 140字を超えたらviewを変更して伝える
    render() {
        return (

                <textarea
                    name="name"
                    rows="2"
                    cols="40"
                    className="editor-textarea"
                    onChange={this.onTextareaChanged.bind(this)}
                    onKeyDown={this.onTextareaKeyDown.bind(this)}
                    placeholder="What's happening?"
                    value={this.state.text}>
                </textarea>

                    {this.getRestTextLength()}

        );
    }

    onTweetSubmitted() {
    }
}
<commit_msg>[bugfix] disable member variable<commit_after>import React, {Component} from 'react'
import {keyStringDetector} from '../registories/registory'

export default class Editor extends Component {

    constructor(props) {
        super(props);
        this.state = {text: ''};
    }

    getRestTextLength() {
        return 140 - this.state.text.length;
    }

    onTextareaChanged(event) {
        this.setState({text: event.target.value});
    }

    onTextareaKeyDown(event) {
        if (keyStringDetector.detect(event) === 'Return') {
            event.preventDefault();
            this.onTweetSubmitted();
        }
    }

    //TODO: 140字を超えたらviewを変更して伝える
    render() {
        return (

                <textarea
                    name="name"
                    rows="2"
                    cols="40"
                    className="editor-textarea"
                    onChange={this.onTextareaChanged.bind(this)}
                    onKeyDown={this.onTextareaKeyDown.bind(this)}
                    placeholder="What's happening?"
                    value={this.state.text}>
                </textarea>

                    {this.getRestTextLength()}

        );
    }

    onTweetSubmitted() {
    }
}
<|endoftext|>


<commit_before>const fs = require('fs')

const sass = require('node-sass')

const input = process.argv[2]
const output = process.argv[3]

if (!input || !output) {
  throw new Error('Input/Output arguments not given.')
}

const scssResult = sass.renderSync({
  file: input,
  sourceMap: true,
  outputStyle: 'nested',
  outFile: output
})

fs.writeFileSync(output, scssResult.css)
fs.writeFileSync(`${output}.map`, scssResult.map)
<commit_msg>delete old file<commit_after><|endoftext|>


<commit_before>// Copyright 2013-2015, University of Colorado Boulder

/**
 * Button with an arrow that points up, down, left or right.
 * Press and release immediately and the button fires on 'up'.
 * Press and hold for M milliseconds and the button will fire repeatedly every N milliseconds until released.
 *
 * @author Chris Malley (PixelZoom, Inc)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Path = require( 'SCENERY/nodes/Path' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var Shape = require( 'KITE/Shape' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );

  // constants
  var DEFAULT_ARROW_HEIGHT = 20;

  /**
   * @param {string} direction 'up'|'down'|'left'|'right'
   * @param {function} callback
   * @param {Object} [options]
   * @constructor
   */
  function ArrowButton( direction, callback, options ) {

    var thisButton = this;

    options = _.extend( {

      // options for the button
      cursor: 'pointer',
      baseColor: 'white',
      stroke: 'black',
      lineWidth: 1,
      cornerRadius: 4,
      xMargin: 7,
      yMargin: 5,
      xTouchExpansion: 7,
      yTouchExpansion: 7,

      // options for the arrow
      arrowHeight: DEFAULT_ARROW_HEIGHT, // from tip to base
      arrowWidth: DEFAULT_ARROW_HEIGHT * Math.sqrt( 3 ) / 2, // width of base
      arrowFill: 'black',
      arrowStroke: null,
      arrowLineWidth: 1,

      // options related to fire-on-hold feature
      fireOnHold: true,
      fireOnHoldDelay: 400, // start to fire continuously after pressing for this long (milliseconds)
      fireOnHoldInterval: 100, // fire continuously at this interval (milliseconds)

      // callbacks
      startCallback: function() {}, // called when the pointer is pressed
      endCallback: function( over ) {} // called when the pointer is released, {boolean} over indicates whether the pointer was over when released

    }, options );
    options.listener = callback;

    // arrow node
    var arrowShape;
    if ( direction === 'up' ) {
      arrowShape = new Shape().moveTo( options.arrowHeight / 2, 0 ).lineTo( options.arrowHeight, options.arrowWidth ).lineTo( 0, options.arrowWidth ).close();
    }
    else if ( direction === 'down' ) {
      arrowShape = new Shape().moveTo( 0, 0 ).lineTo( options.arrowHeight, 0 ).lineTo( options.arrowHeight / 2, options.arrowWidth ).close();
    }
    else if ( direction === 'left' ) {
      arrowShape = new Shape().moveTo( 0, options.arrowHeight / 2 ).lineTo( options.arrowWidth, 0 ).lineTo( options.arrowWidth, options.arrowHeight ).close();
    }
    else if ( direction === 'right' ) {
      arrowShape = new Shape().moveTo( 0, 0 ).lineTo( options.arrowWidth, options.arrowHeight / 2 ).lineTo( 0, options.arrowHeight ).close();
    }
    else {
      throw new Error( 'unsupported direction: ' + direction );
    }
    options.content = new Path( arrowShape, {
      fill: options.arrowFill,
      stroke: options.arrowStroke,
      lineWidth: options.arrowLineWidth,
      pickable: false
    } );

    RectangularPushButton.call( thisButton, options );
  }

  sceneryPhet.register( 'ArrowButton', ArrowButton );

  return inherit( RectangularPushButton, ArrowButton );
} );
<commit_msg>https://github.com/phetsims/sun/issues/204 xTouchExpansion -> touchAreaXDilation yTouchExpansion -> touchAreaYDilation xMouseExpansion -> mouseAreaXExpansion yMouseExpansion -> mouseAreaYExpansion<commit_after>// Copyright 2013-2015, University of Colorado Boulder

/**
 * Button with an arrow that points up, down, left or right.
 * Press and release immediately and the button fires on 'up'.
 * Press and hold for M milliseconds and the button will fire repeatedly every N milliseconds until released.
 *
 * @author Chris Malley (PixelZoom, Inc)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Path = require( 'SCENERY/nodes/Path' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var Shape = require( 'KITE/Shape' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );

  // constants
  var DEFAULT_ARROW_HEIGHT = 20;

  /**
   * @param {string} direction 'up'|'down'|'left'|'right'
   * @param {function} callback
   * @param {Object} [options]
   * @constructor
   */
  function ArrowButton( direction, callback, options ) {

    var thisButton = this;

    options = _.extend( {

      // options for the button
      cursor: 'pointer',
      baseColor: 'white',
      stroke: 'black',
      lineWidth: 1,
      cornerRadius: 4,
      xMargin: 7,
      yMargin: 5,
      touchAreaXDilation: 7,
      touchAreaYDilation: 7,

      // options for the arrow
      arrowHeight: DEFAULT_ARROW_HEIGHT, // from tip to base
      arrowWidth: DEFAULT_ARROW_HEIGHT * Math.sqrt( 3 ) / 2, // width of base
      arrowFill: 'black',
      arrowStroke: null,
      arrowLineWidth: 1,

      // options related to fire-on-hold feature
      fireOnHold: true,
      fireOnHoldDelay: 400, // start to fire continuously after pressing for this long (milliseconds)
      fireOnHoldInterval: 100, // fire continuously at this interval (milliseconds)

      // callbacks
      startCallback: function() {}, // called when the pointer is pressed
      endCallback: function( over ) {} // called when the pointer is released, {boolean} over indicates whether the pointer was over when released

    }, options );
    options.listener = callback;

    // arrow node
    var arrowShape;
    if ( direction === 'up' ) {
      arrowShape = new Shape().moveTo( options.arrowHeight / 2, 0 ).lineTo( options.arrowHeight, options.arrowWidth ).lineTo( 0, options.arrowWidth ).close();
    }
    else if ( direction === 'down' ) {
      arrowShape = new Shape().moveTo( 0, 0 ).lineTo( options.arrowHeight, 0 ).lineTo( options.arrowHeight / 2, options.arrowWidth ).close();
    }
    else if ( direction === 'left' ) {
      arrowShape = new Shape().moveTo( 0, options.arrowHeight / 2 ).lineTo( options.arrowWidth, 0 ).lineTo( options.arrowWidth, options.arrowHeight ).close();
    }
    else if ( direction === 'right' ) {
      arrowShape = new Shape().moveTo( 0, 0 ).lineTo( options.arrowWidth, options.arrowHeight / 2 ).lineTo( 0, options.arrowHeight ).close();
    }
    else {
      throw new Error( 'unsupported direction: ' + direction );
    }
    options.content = new Path( arrowShape, {
      fill: options.arrowFill,
      stroke: options.arrowStroke,
      lineWidth: options.arrowLineWidth,
      pickable: false
    } );

    RectangularPushButton.call( thisButton, options );
  }

  sceneryPhet.register( 'ArrowButton', ArrowButton );

  return inherit( RectangularPushButton, ArrowButton );
} );
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */

define("joynr/capabilities/CapabilitiesRegistrar", [
    "global/Promise",
    "joynr/util/UtilInternal",
    "joynr/types/DiscoveryEntry",
    "joynr/types/ProviderScope",
    "joynr/capabilities/ParticipantIdStorage",
    "joynr/types/Version"
], function(Promise, Util, DiscoveryEntry, ProviderScope, ParticipantIdStorage, Version) {
    var ONE_DAY_MS = 24 * 60 * 60 * 1000;
    /**
     * The Capabilities Registrar
     *
     * @constructor
     * @name CapabilitiesRegistrar
     *
     * @param {Object}
     *            dependencies
     * @param {CapabilityDiscovery}
     *            dependencies.discoveryStub connects the inProcessStub to its skeleton
     * @param {MessageRouter}
     *            dependencies.messageRouter used to register nextHop for registered provider
     * @param {ParticipantIdStorage}
     *            dependencies.participantIdStorage connects the inProcessStub to its skeleton
     * @param {Address}
     *            dependencies.libjoynrMessagingAddress address to be used by the cluster controller to send incoming requests to this
     *            libjoynr's providers
     * @param {RequestReplyManager}
     *            dependencies.requestReplyManager passed on to providerAttribute, providerOperation and providerEvent
     * @param {PublicationManager}
     *            dependencies.publicationManager passed on to providerAttribute
     *
     */
    function CapabilitiesRegistrar(dependencies) {
        var discoveryStub = dependencies.discoveryStub;
        var messageRouter = dependencies.messageRouter;
        var participantIdStorage = dependencies.participantIdStorage;
        var libjoynrMessagingAddress = dependencies.libjoynrMessagingAddress;
        var requestReplyManager = dependencies.requestReplyManager;
        var publicationManager = dependencies.publicationManager;
        var loggingManager = dependencies.loggingManager;
        var started = true;

        /**
         * @param provider
         *            to scan for a ProviderOperation
         * @returns {Boolean} true if provider contains a ProviderOperation
         */
        function hasOperation(provider) {
            var property;
            for (property in provider) {
                if (provider.hasOwnProperty(property)) {
                    if (provider[property].constructor.name === "ProviderOperation") {
                        return true;
                    }
                }
            }
            return false;
        }

        /*
         * Internal function used to throw exception in case of CapabilitiesRegistrar
         * is not used properly
         */
        function checkIfReady() {
            if (!started) {
                throw new Error("CapabilitiesRegistrar is already shut down");
            }
        }

        /**
         * Registers a provider so that it is publicly available
         *
         * @function
         * @name CapabilitiesRegistrar#registerProvider
         *
         * @param {Object} settings the arguments object for this function call
         * @param {String}
         *            settings.domain
         * @param {Object}
         *            settings.provider
         * @param {String}
         *            settings.provider.interfaceName
         * @param {ProviderQos}
         *            settings.providerQos the Quality of Service parameters for provider registration
         * @param {Number}
         *            [settings.expiryDateMs] date in millis since epoch after which the discovery entry can be purged from all directories.
         *            Default value is one day.
         * @param {Object}
         *            [settings.loggingContext] optional logging context will be appended to logging messages created in the name of this proxy
         * @param {String}
         *            [settings.participantId] optional. If not set, a globally unique UUID participantId will be generated, and persisted to
         *            localStorage. If set, the participantId must be unique in the context of the provider's scope, as set in the ProviderQos;
         *            The application setting the participantId is responsible for guaranteeing uniqueness.
         *
         * @returns {Object} an A+ promise
         */
        this.register =
                function register(settings) {
                    return this.registerProvider(
                            settings.domain,
                            settings.provider,
                            settings.providerQos,
                            settings.expiryDateMs,
                            settings.loggingContext,
                            settings.participantId);
                };

        /**
         * Registers a provider so that it is publicly available
         *
         * @deprecated Use register instead
         * @function
         * @name CapabilitiesRegistrar#registerProvider
         *
         * @param {String}
         *            domain
         * @param {Object}
         *            provider
         * @param {String}
         *            provider.interfaceName
         * @param {ProviderQos}
         *            providerQos the Quality of Service parameters for provider registration
         * @param {Number}
         *            [expiryDateMs] date in millis since epoch after which the discovery entry can be purged from all directories.
         *            Default value is one day.
         * @param {Object}
         *            [loggingContext] optional logging context will be appended to logging messages created in the name of this proxy
         * @param {String}
         *            [participantId] optional. If not set, a globally unique UUID participantId will be generated, and persisted to localStorage.
         *
         * @returns {Object} an A+ promise
         */
        this.registerProvider =
                function registerProvider(
                        domain,
                        provider,
                        providerQos,
                        expiryDateMs,
                        loggingContext,
                        participantId) {
                    checkIfReady();

                    var missingImplementations = provider.checkImplementation();

                    if (missingImplementations.length > 0) {
                        throw new Error("provider: "
                            + domain
                            + "/"
                            + provider.interfaceName
                            + " is missing: "
                            + missingImplementations.toString());
                    }

                    // retrieve participantId if not passed in
                    if ( participantId === undefined || participantId === null ) {
                        participantId = participantIdStorage.getParticipantId(domain, provider);
                    }

                    if (loggingContext !== undefined) {
                        loggingManager.setLoggingContext(participantId, loggingContext);
                    }

                    // register provider at RequestReplyManager
                    requestReplyManager.addRequestCaller(participantId, provider);

                    // register routing address at routingTable
                    var isGloballyVisible = (providerQos.scope === ProviderScope.GLOBAL);
                    var messageRouterPromise =
                            messageRouter.addNextHop(
                                    participantId,
                                    libjoynrMessagingAddress,
                                    isGloballyVisible);

                    // if provider has at least one attribute, add it as publication provider
                    publicationManager.addPublicationProvider(participantId, provider);

                    // TODO: Must be later provided by the user or retrieved from somewhere
                    var defaultPublicKeyId = "";

                    var discoveryStubPromise = discoveryStub.add(new DiscoveryEntry({
                        providerVersion : new Version({
                            majorVersion : provider.constructor.MAJOR_VERSION,
                            minorVersion : provider.constructor.MINOR_VERSION
                        }),
                        domain : domain,
                        interfaceName : provider.interfaceName,
                        participantId : participantId,
                        qos : providerQos,
                        publicKeyId : defaultPublicKeyId,
                        expiryDateMs : expiryDateMs || Date.now() + ONE_DAY_MS,
                        lastSeenDateMs : Date.now()
                    }));

                    return Promise.all([
                        messageRouterPromise,
                        discoveryStubPromise
                    ]).then(function() {
                        return participantId;
                    });
                };

        /**
         * Unregisters a provider so that it is not publicly available anymore
         *
         * @function
         * @name CapabilitiesRegistrar#unregisterProvider
         * @param {String}
         *            domain
         * @param {Object}
         *            provider
         * @param {String}
         *            provider.interfaceName
         * @returns {Object} an A+ promise
         */
        this.unregisterProvider = function unregisterProvider(domain, provider) {
            checkIfReady();
            // retrieve participantId
            var participantId = participantIdStorage.getParticipantId(domain, provider);

            var discoveryStubPromise = discoveryStub.remove(participantId);

            // if provider has at least one attribute, remove it as publication
            // provider
            publicationManager.removePublicationProvider(participantId, provider);

            // unregister routing address at routingTable
            var messageRouterPromise = messageRouter.removeNextHop(participantId);

            // unregister provider at RequestReplyManager
            requestReplyManager.removeRequestCaller(participantId);

            return Promise.all([
                discoveryStubPromise,
                messageRouterPromise
            ]);
        };

        /**
         * Shutdown the capabilities registrar
         *
         * @function
         * @name CapabilitiesRegistrar#shutdown
         */
        this.shutdown = function shutdown() {
            started = false;
        };
    }

    return CapabilitiesRegistrar;

});
<commit_msg>[JS] Format CapabilitiesRegistrar<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */

define("joynr/capabilities/CapabilitiesRegistrar", [
    "global/Promise",
    "joynr/util/UtilInternal",
    "joynr/types/DiscoveryEntry",
    "joynr/types/ProviderScope",
    "joynr/capabilities/ParticipantIdStorage",
    "joynr/types/Version"
], function(Promise, Util, DiscoveryEntry, ProviderScope, ParticipantIdStorage, Version) {
    var ONE_DAY_MS = 24 * 60 * 60 * 1000;
    /**
     * The Capabilities Registrar
     *
     * @constructor
     * @name CapabilitiesRegistrar
     *
     * @param {Object}
     *            dependencies
     * @param {CapabilityDiscovery}
     *            dependencies.discoveryStub connects the inProcessStub to its skeleton
     * @param {MessageRouter}
     *            dependencies.messageRouter used to register nextHop for registered provider
     * @param {ParticipantIdStorage}
     *            dependencies.participantIdStorage connects the inProcessStub to its skeleton
     * @param {Address}
     *            dependencies.libjoynrMessagingAddress address to be used by the cluster controller to send incoming requests to this
     *            libjoynr's providers
     * @param {RequestReplyManager}
     *            dependencies.requestReplyManager passed on to providerAttribute, providerOperation and providerEvent
     * @param {PublicationManager}
     *            dependencies.publicationManager passed on to providerAttribute
     *
     */
    function CapabilitiesRegistrar(dependencies) {
        var discoveryStub = dependencies.discoveryStub;
        var messageRouter = dependencies.messageRouter;
        var participantIdStorage = dependencies.participantIdStorage;
        var libjoynrMessagingAddress = dependencies.libjoynrMessagingAddress;
        var requestReplyManager = dependencies.requestReplyManager;
        var publicationManager = dependencies.publicationManager;
        var loggingManager = dependencies.loggingManager;
        var started = true;

        /**
         * @param provider
         *            to scan for a ProviderOperation
         * @returns {Boolean} true if provider contains a ProviderOperation
         */
        function hasOperation(provider) {
            var property;
            for (property in provider) {
                if (provider.hasOwnProperty(property)) {
                    if (provider[property].constructor.name === "ProviderOperation") {
                        return true;
                    }
                }
            }
            return false;
        }

        /*
         * Internal function used to throw exception in case of CapabilitiesRegistrar
         * is not used properly
         */
        function checkIfReady() {
            if (!started) {
                throw new Error("CapabilitiesRegistrar is already shut down");
            }
        }

        /**
         * Registers a provider so that it is publicly available
         *
         * @function
         * @name CapabilitiesRegistrar#registerProvider
         *
         * @param {Object} settings the arguments object for this function call
         * @param {String}
         *            settings.domain
         * @param {Object}
         *            settings.provider
         * @param {String}
         *            settings.provider.interfaceName
         * @param {ProviderQos}
         *            settings.providerQos the Quality of Service parameters for provider registration
         * @param {Number}
         *            [settings.expiryDateMs] date in millis since epoch after which the discovery entry can be purged from all directories.
         *            Default value is one day.
         * @param {Object}
         *            [settings.loggingContext] optional logging context will be appended to logging messages created in the name of this proxy
         * @param {String}
         *            [settings.participantId] optional. If not set, a globally unique UUID participantId will be generated, and persisted to
         *            localStorage. If set, the participantId must be unique in the context of the provider's scope, as set in the ProviderQos;
         *            The application setting the participantId is responsible for guaranteeing uniqueness.
         *
         * @returns {Object} an A+ promise
         */
        this.register =
                function register(settings) {
                    return this.registerProvider(
                            settings.domain,
                            settings.provider,
                            settings.providerQos,
                            settings.expiryDateMs,
                            settings.loggingContext,
                            settings.participantId);
                };

        /**
         * Registers a provider so that it is publicly available
         *
         * @deprecated Use register instead
         * @function
         * @name CapabilitiesRegistrar#registerProvider
         *
         * @param {String}
         *            domain
         * @param {Object}
         *            provider
         * @param {String}
         *            provider.interfaceName
         * @param {ProviderQos}
         *            providerQos the Quality of Service parameters for provider registration
         * @param {Number}
         *            [expiryDateMs] date in millis since epoch after which the discovery entry can be purged from all directories.
         *            Default value is one day.
         * @param {Object}
         *            [loggingContext] optional logging context will be appended to logging messages created in the name of this proxy
         * @param {String}
         *            [participantId] optional. If not set, a globally unique UUID participantId will be generated, and persisted to localStorage.
         *
         * @returns {Object} an A+ promise
         */
        this.registerProvider =
                function registerProvider(
                        domain,
                        provider,
                        providerQos,
                        expiryDateMs,
                        loggingContext,
                        participantId) {
                    checkIfReady();

                    var missingImplementations = provider.checkImplementation();

                    if (missingImplementations.length > 0) {
                        throw new Error("provider: "
                            + domain
                            + "/"
                            + provider.interfaceName
                            + " is missing: "
                            + missingImplementations.toString());
                    }

                    // retrieve participantId if not passed in
                    if (participantId === undefined || participantId === null) {
                        participantId = participantIdStorage.getParticipantId(domain, provider);
                    }

                    if (loggingContext !== undefined) {
                        loggingManager.setLoggingContext(participantId, loggingContext);
                    }

                    // register provider at RequestReplyManager
                    requestReplyManager.addRequestCaller(participantId, provider);

                    // register routing address at routingTable
                    var isGloballyVisible = (providerQos.scope === ProviderScope.GLOBAL);
                    var messageRouterPromise =
                            messageRouter.addNextHop(
                                    participantId,
                                    libjoynrMessagingAddress,
                                    isGloballyVisible);

                    // if provider has at least one attribute, add it as publication provider
                    publicationManager.addPublicationProvider(participantId, provider);

                    // TODO: Must be later provided by the user or retrieved from somewhere
                    var defaultPublicKeyId = "";

                    var discoveryStubPromise = discoveryStub.add(new DiscoveryEntry({
                        providerVersion : new Version({
                            majorVersion : provider.constructor.MAJOR_VERSION,
                            minorVersion : provider.constructor.MINOR_VERSION
                        }),
                        domain : domain,
                        interfaceName : provider.interfaceName,
                        participantId : participantId,
                        qos : providerQos,
                        publicKeyId : defaultPublicKeyId,
                        expiryDateMs : expiryDateMs || Date.now() + ONE_DAY_MS,
                        lastSeenDateMs : Date.now()
                    }));

                    return Promise.all([
                        messageRouterPromise,
                        discoveryStubPromise
                    ]).then(function() {
                        return participantId;
                    });
                };

        /**
         * Unregisters a provider so that it is not publicly available anymore
         *
         * @function
         * @name CapabilitiesRegistrar#unregisterProvider
         * @param {String}
         *            domain
         * @param {Object}
         *            provider
         * @param {String}
         *            provider.interfaceName
         * @returns {Object} an A+ promise
         */
        this.unregisterProvider = function unregisterProvider(domain, provider) {
            checkIfReady();
            // retrieve participantId
            var participantId = participantIdStorage.getParticipantId(domain, provider);

            var discoveryStubPromise = discoveryStub.remove(participantId);

            // if provider has at least one attribute, remove it as publication
            // provider
            publicationManager.removePublicationProvider(participantId, provider);

            // unregister routing address at routingTable
            var messageRouterPromise = messageRouter.removeNextHop(participantId);

            // unregister provider at RequestReplyManager
            requestReplyManager.removeRequestCaller(participantId);

            return Promise.all([
                discoveryStubPromise,
                messageRouterPromise
            ]);
        };

        /**
         * Shutdown the capabilities registrar
         *
         * @function
         * @name CapabilitiesRegistrar#shutdown
         */
        this.shutdown = function shutdown() {
            started = false;
        };
    }

    return CapabilitiesRegistrar;

});
<|endoftext|>


<commit_before>// input value must be in common base units (g, L, mol)
function fromSI (value, units) {
    debugger;
	switch (units) {
	// mass (base: g)
	case 'kg':
		return value / 1000;
	case 'mg':
		return value * 1000;
	case 'µg':
		return value * 1000000;
	case 'ng':
		return value * 1000000000;
	// amount (base: mol)
	case 'mmol':
		return value * 1000;
	case 'µmol':
		return value * 1000000;
	case 'nmol':
		return value * 1000000000;
	// mol weight (base: g/mol)
	case 'kg/mol':
		return value / 1000;
	case 'mg/mol':
		return value * 1000;
	// Volume (base: L)
	case 'm3':
		return value / 1000;
	case 'dL':
		return value * 10;
	case 'mL':
		return value * 1000;
	case 'µL':
		return value * 1000000;
	case 'nL':
		return value * 1000000000;
	// Concentration (SI: mol/L or M)
	case 'mol/m3':
		return value * 1000;
	case 'mM':
		return value * 1000;
	case 'µM':
		return value * 1000000;
	case 'nM':
		return value * 1000000000;
	// Density (SI: g/L)
	case 'kg/L':
		return value / 1000;
	case 'g/mL':
		return value / 1000;
	default:
		return value; // in SI unit
	}
}

function toSI (value, units) {
	switch (units) {
	// mass (base: g)
	case 'kg':
		return value * 1000;
	case 'mg':
		return value / 1000;
	case 'µg':
		return value / 1000000;
	case 'ng':
		return value / 1000000000;
	// mol weight (base: g/mol)
	case 'kg/mol':
		return value * 1000;
	case 'mg/mol':
		return value / 1000;
	// amount (base: mol)
	case 'mmol':
		return value / 1000;
	case 'µmol':
		return value / 1000000;
	case 'nmol':
		return value / 1000000000;
	// Volume (base: L)
	case 'm3':
		return value * 1000;
	case 'dL':
		return value / 10;
	case 'mL':
		return value / 1000;
	case 'µL':
		return value / 1000000;
	case 'nL':
		return value / 1000000000;
	// Concentration (SI: mol/L or M)
	case 'mol/m3':
		return value / 1000;
	case 'mM':
		return value / 1000;
	case 'µM':
		return value / 1000000;
	case 'nM':
		return value / 1000000000;
	// Density (SI: g/L)
	case 'kg/L':
		return value * 1000;
	case 'g/mL':
		return value * 1000;
	default:
		return value; // in SI unit
	}
}

function getMassUnits(value) {
	// We want to determine optimal units (kg, g, mg, ug, ng) for a given value in g.
	var order = Math.log(value) / Math.LN10;
	if(order >= 3) {
		return 'kg';
	} else if (order >= 0) {
		return 'g';
	} else if (order >= -3) {
		return 'mg';
	} else if (order >= -6) {
		return 'µg';
	} else if (order >= -9) {
		return 'ng';
	} else {
		return 'g';
	}
}

function getMolUnits(value) {
	// We want to determine optimal units (mol, mmol, umol, nmol) for a given value in mol.
	var order = Math.log(value) / Math.LN10;
	if (order >= 0) {
		return 'mol';
	} else if (order >= -3) {
		return 'mmol';
	} else if (order >= -6) {
		return 'µmol';
	} else if (order >= -9) {
		return 'nmol';
	} else {
		return 'mol';
	}
}

function getVolUnits(value) {
	// We want to determine optimal units (L, mL, uL, nL) for a given value in L (never return dL, because it's unconventional)
	var order = Math.log(value) / Math.LN10;
	if (order >= 0) {
		return 'L';
	} else if (order >= -3) {
		return 'mL';
	} else if (order >= -6) {
		return 'µL';
	} else if (order >= -9) {
		return 'nL';
	} else {
		return 'L';
	}
}

function getConcUnits(value) {
	// We want to determine optimal units (M, mM, uM, nM) for a given value in M (never return mol/m3, because it's unconventional)
	var order = Math.log(value) / Math.LN10;
	if (order >= 0) {
		return 'M';
	} else if (order >= -3) {
		return 'mM';
	} else if (order >= -6) {
		return 'µM';
	} else if (order >= -9) {
		return 'nM';
	} else {
		return 'M';
	}
}

<commit_msg>rm debug<commit_after>// input value must be in common base units (g, L, mol)
function fromSI (value, units) {
	switch (units) {
	// mass (base: g)
	case 'kg':
		return value / 1000;
	case 'mg':
		return value * 1000;
	case 'µg':
		return value * 1000000;
	case 'ng':
		return value * 1000000000;
	// amount (base: mol)
	case 'mmol':
		return value * 1000;
	case 'µmol':
		return value * 1000000;
	case 'nmol':
		return value * 1000000000;
	// mol weight (base: g/mol)
	case 'kg/mol':
		return value / 1000;
	case 'mg/mol':
		return value * 1000;
	// Volume (base: L)
	case 'm3':
		return value / 1000;
	case 'dL':
		return value * 10;
	case 'mL':
		return value * 1000;
	case 'µL':
		return value * 1000000;
	case 'nL':
		return value * 1000000000;
	// Concentration (SI: mol/L or M)
	case 'mol/m3':
		return value * 1000;
	case 'mM':
		return value * 1000;
	case 'µM':
		return value * 1000000;
	case 'nM':
		return value * 1000000000;
	// Density (SI: g/L)
	case 'kg/L':
		return value / 1000;
	case 'g/mL':
		return value / 1000;
	default:
		return value; // in SI unit
	}
}

function toSI (value, units) {
	switch (units) {
	// mass (base: g)
	case 'kg':
		return value * 1000;
	case 'mg':
		return value / 1000;
	case 'µg':
		return value / 1000000;
	case 'ng':
		return value / 1000000000;
	// mol weight (base: g/mol)
	case 'kg/mol':
		return value * 1000;
	case 'mg/mol':
		return value / 1000;
	// amount (base: mol)
	case 'mmol':
		return value / 1000;
	case 'µmol':
		return value / 1000000;
	case 'nmol':
		return value / 1000000000;
	// Volume (base: L)
	case 'm3':
		return value * 1000;
	case 'dL':
		return value / 10;
	case 'mL':
		return value / 1000;
	case 'µL':
		return value / 1000000;
	case 'nL':
		return value / 1000000000;
	// Concentration (SI: mol/L or M)
	case 'mol/m3':
		return value / 1000;
	case 'mM':
		return value / 1000;
	case 'µM':
		return value / 1000000;
	case 'nM':
		return value / 1000000000;
	// Density (SI: g/L)
	case 'kg/L':
		return value * 1000;
	case 'g/mL':
		return value * 1000;
	default:
		return value; // in SI unit
	}
}

function getMassUnits(value) {
	// We want to determine optimal units (kg, g, mg, ug, ng) for a given value in g.
	var order = Math.log(value) / Math.LN10;
	if(order >= 3) {
		return 'kg';
	} else if (order >= 0) {
		return 'g';
	} else if (order >= -3) {
		return 'mg';
	} else if (order >= -6) {
		return 'µg';
	} else if (order >= -9) {
		return 'ng';
	} else {
		return 'g';
	}
}

function getMolUnits(value) {
	// We want to determine optimal units (mol, mmol, umol, nmol) for a given value in mol.
	var order = Math.log(value) / Math.LN10;
	if (order >= 0) {
		return 'mol';
	} else if (order >= -3) {
		return 'mmol';
	} else if (order >= -6) {
		return 'µmol';
	} else if (order >= -9) {
		return 'nmol';
	} else {
		return 'mol';
	}
}

function getVolUnits(value) {
	// We want to determine optimal units (L, mL, uL, nL) for a given value in L (never return dL, because it's unconventional)
	var order = Math.log(value) / Math.LN10;
	if (order >= 0) {
		return 'L';
	} else if (order >= -3) {
		return 'mL';
	} else if (order >= -6) {
		return 'µL';
	} else if (order >= -9) {
		return 'nL';
	} else {
		return 'L';
	}
}

function getConcUnits(value) {
	// We want to determine optimal units (M, mM, uM, nM) for a given value in M (never return mol/m3, because it's unconventional)
	var order = Math.log(value) / Math.LN10;
	if (order >= 0) {
		return 'M';
	} else if (order >= -3) {
		return 'mM';
	} else if (order >= -6) {
		return 'µM';
	} else if (order >= -9) {
		return 'nM';
	} else {
		return 'M';
	}
}

<|endoftext|>


<commit_before>function AttackData(approximateDamage, isCritical, stunLength, animals, crops, knockback) {
    this.damage = Math.ceil(approximateDamage);
    if(this.damage < 1) { this.damage = 1; }
    this.crit = isCritical;
    this.cropPowerLower = Math.ceil(this.damage / 4);
    this.stunLength = stunLength || 0;
    this.animals = animals || [];
    this.crops = crops || [];
    this.numCrops = this.crops.length;
    this.knockback = Math.ceil(knockback || 0);
}
const dmgCalcs = {
    GetPlayerCombatDefense: function() {
        let d = player.def;
        for(let x = 0; x < player.gridWidth; x++) {
            for(let y = 0; y < player.gridHeight; y++) {
                const tile = combat.grid[x][y]
                if(tile === null || tile.x !== undefined) { continue; }
                d += tile.power / 5;
            }
        }
        return Math.min(Math.round(d), player.def * 3);
    },
    GetNerfs: function() {
        if(combat.enemies[0].id !== "beckett") { return []; }
        let nerfs = [];
        const right = combat.enemywidth - 1, bottom = combat.enemyheight - 1;
        for(let x = right - 1; x <= right; x++) {
            for(let y = bottom - 1; y <= bottom; y++) {
                const nerf = combat.enemyGrid[x][y];
                if(nerf === null) { continue; }
                switch(nerf.id) {
                    case "mushNerf": nerfs.push("mush"); break;
                    case "riceNerf": nerfs.push("rice"); break;
                    case "treeNerf": nerfs.push("tree"); break;
                    case "vegNerf": nerfs.push("veg"); break;
                    case "fishNerf": nerfs.push("spear"); nerfs.push("rod"); nerfs.push("water"); break;
                    case "beeNerf": nerfs.push("bee"); break;
                    case "eggNerf": nerfs.push("egg"); break;
                    case "reNerf": nerfs.push("RE"); break;
                }
            }
        }
        return nerfs;
    },
    GetNerfMultiplier: function(crop, nerfs) {
        if(combat.enemies[0].id !== "beckett") { return 1; }
        if(nerfs.length === 0) { return 1; }
        let nerfMult = 1;
        for(let i = 0; i < nerfs.length; i++) {
            if(nerfs[i] === "RE") { if(crop.respawn > 0) { nerfMult *= 0.25; } }
            else if(nerfs[i] === crop.type) { nerfMult *= 0.25; }
        }
        return nerfMult;
    },
    CropToDef: function(crop, season, attackElements) {
        let cropDef = crop.defense;
        switch(crop.seasons[season]) {
            case 2: cropDef *= 2; break;
            case 0: cropDef /= 3; break;
        }
        for(let i = 0; i < attackElements; i++) {
            const attackElement = attackElements[i];
            switch(attackElement) { // 0 = water, 1 = fire, salt = 2, -1 = general
                case 0: cropDef *= 1.5 * (crop.waterResist || 0); break;
                case 1: cropDef *= 1.5 * (crop.fireResist || 0); break;
                case 2: cropDef *= 1.5 * (crop.saltResist || 0); break;
            }
        }
        return cropDef;
    },

    MeleeAttack: function(isPlayer, season, myAtk, targets, attackElements) {
        if(attackElements === undefined) { attackElement = [-1]; }
        var formattedDefs = [];
        for(var i = 0; i < targets.length; i++) {
            if(targets[i].name === undefined) { // enemy; value is just an integer for their defense
                formattedDefs.push(targets[i]);
            } else { // crop; value is a crop object
                formattedDefs.push(dmgCalcs.CropToDef(targets[i], season, attackElements));
            }
        }
        return dmgCalcs.MeleeInner(isPlayer, season, myAtk, formattedDefs);
    },
    MeleeInner: function(isPlayer, season, myAtk, theirDef) {
        var isCritical = (Math.random() < (player.luck - 0.69));
        var atkVal = myAtk;
        var hasWeapon = isPlayer && player.equipment.weapon !== null;
        if(hasWeapon) {
            var weapon = GetEquipment(player.equipment.weapon);
            var bonus = weapon.power;
            if(season === 0 && weapon.sp) { bonus += weapon.sp; }
            else if(season === 1 && weapon.su) { bonus += weapon.su; }
            else if(season === 2 && weapon.au) { bonus += weapon.au; }
            else if(season === 3 && weapon.wi) { bonus += weapon.wi; }
            atkVal += bonus / 1.1;
        }
        var attacksArr = [];
        for(var i = 0; i < theirDef.length; i++) {
            var finalDamage = atkVal - (isCritical ? 0 : (theirDef[i] / 2.2));
            if(hasWeapon) { finalDamage -= (isCritical ? 0 : (theirDef[i] / 4)); }
            attacksArr.push(new AttackData(finalDamage, isCritical));
        }
        console.log(attacksArr);

        if(isPlayer) { return { isCritical: isCritical, attackDatas: attacksArr, animData: null, recoilInfo: null }; }
        else { return attacksArr; }
    },

    CropAttack: function(isPlayer, season, myAtk, myCrops, targets, attackElements) {
        if(attackElements === undefined) { attackElement = [-1]; }
        let formattedDefs = [];
        for(let i = 0; i < targets.length; i++) {
            if(targets[i].name === undefined) { // enemy; value is just an integer for their defense
                formattedDefs.push(targets[i]);
            } else { // crop; value is a crop object
                formattedDefs.push(dmgCalcs.CropToDef(targets[i], season, attackElements));
            }
        }
        return dmgCalcs.CropInner(isPlayer, season, myAtk, myCrops, formattedDefs);
    },
    CropInner: function(isPlayer, season, myAtk, myCrops, theirDef) {
        const isCritical = isPlayer && (Math.random() < (player.luck - 0.69));
        const hasShockGloves = isPlayer && player.equipment.gloves !== null && GetEquipment(player.equipment.gloves).tech;
        const nerfs = dmgCalcs.GetNerfs(), modAtk = Math.log10(5 + myAtk * myAtk);
        let totalDamage = 0, stunLength = 0, damageToAttacker = 0, animals = [];
        let recoilInfos = [], animInfos = [];

        for(let i = 0; i < myCrops.length; i++) {
            const crop = myCrops[i].crop;
            let seasonVal = crop.seasons[season];
            if(seasonVal === 0) { seasonVal = 0.2; } else if(isPlayer) { player.miscdata.seasonsPlanted[season]++; }

            let pow = crop.power + 1;
            if(isPlayer) {
                if(crop.stickChance !== undefined && stunLength === 0) { // Stickiness
                    switch(crop.stickChance) { // TODO: add enemy resistance to stickiness
                        case 1: stunLength = ((player.luck * Math.random()) > 0.6 ? InclusiveRange(1, 2) : 0); break;
                        case 2: stunLength = ((player.luck * Math.random()) > 0.5 ? InclusiveRange(1, 3) : 0); break;
                        case 3: stunLength = ((player.luck * Math.random()) > 0.45 ? InclusiveRange(2, 5) : 0); break;
                    }
                }
                if(player.equipment.soil !== null) { // Watering Cans
                    const soil = GetEquipment(player.equipment.soil);
                    if(soil.boost !== undefined) {
                        switch(crop.seasons[season]) {
                            case 0: seasonVal += soil.boost; break;
                            case 1: seasonVal += soil.boost / 2; break;
                        }
                    } else if(soil.amp !== undefined) {
                        switch(crop.seasons[season]) { // currently values are 0, 1 and 2
                            case 0: seasonVal -= soil.amp * 0.1; break; // brings from 0.2 to 0.1 or 0 respectively
                            case 2: seasonVal *= soil.amp * 2; break; // brings from 2 to 4 or 8 respectively
                        }
                    }
                }
                if(hasShockGloves && ["water", "rice", "spear", "rod"].indexOf(crop.type) >= 0) { // Shock from Harvesting Water-based Crops
                    damageToAttacker += crop.power * 1.5;
                }
            } else if(crop.type === "tech") { pow -= 1; }

            let dmg = (modAtk * pow * pow * seasonVal * dmgCalcs.GetNerfMultiplier(crop, nerfs)) / 5;
            if(crop.type === "rice") { dmg *= 1.5; }
            else if(crop.type === "tech") { dmg *= 2; }
            if(crop.name === "app") { dmg *= 2 / (crop.activeTime + 1); }
            if(crop.animal !== undefined && ((1 - player.luck) * Math.random()) < (crop.animalChance / 8)) {
                animals.push({ crop: crop.name, animal: crop.animal });
                dmg *= crop.animalDamageMult;
            }
            let recoilInfo = null;
            if(isPlayer && ["rice", "veg", "tree", "mush", "bee", "egg", "tech"].indexOf(crop.type) >= 0) {
                if(crop.type === "rice" || (myCrops.length > 3 && combat.enemies.length > 1)) {
                    var power = crop.type === "rice" ? 1 : 0;
                    var numCrops = myCrops.length;
                    while((Math.random() * player.luck * numCrops--) > 0.9) {
                        power++;
                    }
                    if(power > 0) { recoilInfo = power * Math.max(3, dmg / 6 / combat.enemies.length); }
                }
            }
            totalDamage += dmg;
            animInfos.push({ x: myCrops[i].x, y: myCrops[i].y, recoil: recoilInfo });
            recoilInfos.push(recoilInfo);
        }
        if(isPlayer) {
            totalDamage *= 1 + (Math.floor(myCrops.length / 3) / 10); // boost by number of crops (launch 10 crops to get 1.3x boost, 20 for 1.6x, 30 for 2x)
        } else {
            totalDamage *= 1 + Math.floor(myCrops.length / 6) / 10; // boost by number of crops (launch 10 crops to get 1.1x boost, 20 for 1.3x, 30 for 1.5x)
        }
        if(isPlayer) { totalDamage += myAtk + 1; }
        var attacksArr = [];
        for(var i = 0; i < theirDef.length; i++) {
            var finalDamage = totalDamage;
            if(isPlayer) {
                finalDamage = this.GetDefendedPlayerDamage(finalDamage, isCritical, theirDef[i]);
            } else {
                finalDamage -= theirDef[i] / 1.5;
            }
            attacksArr.push(new AttackData(finalDamage, isCritical, stunLength, animals, myCrops, damageToAttacker));
        }
        if(isPlayer) { return { isCritical: isCritical, attackDatas: attacksArr, animData: animInfos, recoilInfo: recoilInfos }; }
        else { return attacksArr; }
    },
    GetDefendedPlayerDamage: function(initDamage, isCritical, theirDefense) {
        if(isCritical) { return initDamage; }
        return Math.ceil(initDamage - (theirDefense / 4));
    },

    CompostFunc: function(isPlayer, season, myAtk, myCrops, isAttack, noAction) { // isAttack: true = attack, false = heal
        var cowMult = isAttack ? 0.01 : 3, coffeeMult = isAttack ? 0.5 : 3.5, beeMult = isAttack ? 0.5 : 3;
        var baseMult = isAttack ? 0.5 : 1.25, modAtk = Math.log2(myAtk * myAtk * 0.15); // min atk is 3; log2(n) <= 0 where n <= 1; 3 * 3 * 0.15 = 1.35
        noAction = noAction || false;

        var outputAmount = 0, thereAreCows = false, thereAreBees = false, thereIsCoffee = false;
        var nerfs = dmgCalcs.GetNerfs();
        for(var i = 0; i < myCrops.length; i++) {
            var croppos = myCrops[i];
            if(croppos.cow !== undefined) {
                outputAmount += cowMult * combat.happyCows[croppos.cow].feed;
                combat.happyCows[croppos.cow].removeMe = true;
                thereAreCows = true;
                croppos = combat.happyCows[croppos.cow];
                if(!noAction) {
                    combat.animHelper.AddAnim(new SheetAnim(combat.dx + croppos.x + 0.25, combat.dy + croppos.y + 1, 250, "puff", 5));
                    combat.animHelper.AddAnim(new MoveAnim(combat.dx + croppos.x + 0.25, combat.dy + croppos.y + 1, combat.compost.binx, combat.compost.biny, 1000, "milk"));
                }
            } else {
                var crop = noAction ? combat.grid[croppos.x][croppos.y] : combat.ClearAndReturnCrop(croppos);
                var seasonVal = crop.seasons[season];
                if(seasonVal === 0) { seasonVal = 0.2; } else if(isPlayer) { player.miscdata.seasonsPlanted[season]++; }
                var cropPowVal = (modAtk * (crop.power + 1) * (crop.power + 1) * (seasonVal + 1)) / 20;
                if(crop.type === "bee") {
                    thereAreBees = true;
                    outputAmount += beeMult * cropPowVal;
                } else if(crop.name === "coffee") {
                    thereIsCoffee = true;
                    outputAmount += coffeeMult * cropPowVal;
                } else {
                    outputAmount += baseMult * cropPowVal;
                }
                outputAmount *= dmgCalcs.GetNerfMultiplier(crop, nerfs);
                if(!noAction) {
                    var cropSprite = crop.rotten ? "weed" : crop.name; // TODO: replace (i.e. fish don't become weeds) (but we can't compost fish anyway so that doesn't matter probably)
                    combat.animHelper.AddAnim(new SheetAnim(combat.dx + croppos.x, combat.dy + croppos.y, 250, "puff", 5));
                    combat.animHelper.AddAnim(new MoveAnim(combat.dx + croppos.x, combat.dy + croppos.y, combat.compost.binx, combat.compost.biny, 1000, cropSprite));
                }
            }
        }
        outputAmount *= 1 + (myCrops.length / 4);
        return { total: Math.max(1, outputAmount), cows: thereAreCows, bees: thereAreBees, coffee: thereIsCoffee };
    }
};<commit_msg>made it so eating poisonous mushrooms kills you<commit_after>function AttackData(approximateDamage, isCritical, stunLength, animals, crops, knockback) {
    this.damage = Math.ceil(approximateDamage);
    if(this.damage < 1) { this.damage = 1; }
    this.crit = isCritical;
    this.cropPowerLower = Math.ceil(this.damage / 4);
    this.stunLength = stunLength || 0;
    this.animals = animals || [];
    this.crops = crops || [];
    this.numCrops = this.crops.length;
    this.knockback = Math.ceil(knockback || 0);
}
const dmgCalcs = {
    GetPlayerCombatDefense: function() {
        let d = player.def;
        for(let x = 0; x < player.gridWidth; x++) {
            for(let y = 0; y < player.gridHeight; y++) {
                const tile = combat.grid[x][y]
                if(tile === null || tile.x !== undefined) { continue; }
                d += tile.power / 5;
            }
        }
        return Math.min(Math.round(d), player.def * 3);
    },
    GetNerfs: function() {
        if(combat.enemies[0].id !== "beckett") { return []; }
        let nerfs = [];
        const right = combat.enemywidth - 1, bottom = combat.enemyheight - 1;
        for(let x = right - 1; x <= right; x++) {
            for(let y = bottom - 1; y <= bottom; y++) {
                const nerf = combat.enemyGrid[x][y];
                if(nerf === null) { continue; }
                switch(nerf.id) {
                    case "mushNerf": nerfs.push("mush"); break;
                    case "riceNerf": nerfs.push("rice"); break;
                    case "treeNerf": nerfs.push("tree"); break;
                    case "vegNerf": nerfs.push("veg"); break;
                    case "fishNerf": nerfs.push("spear"); nerfs.push("rod"); nerfs.push("water"); break;
                    case "beeNerf": nerfs.push("bee"); break;
                    case "eggNerf": nerfs.push("egg"); break;
                    case "reNerf": nerfs.push("RE"); break;
                }
            }
        }
        return nerfs;
    },
    GetNerfMultiplier: function(crop, nerfs) {
        if(combat.enemies[0].id !== "beckett") { return 1; }
        if(nerfs.length === 0) { return 1; }
        let nerfMult = 1;
        for(let i = 0; i < nerfs.length; i++) {
            if(nerfs[i] === "RE") { if(crop.respawn > 0) { nerfMult *= 0.25; } }
            else if(nerfs[i] === crop.type) { nerfMult *= 0.25; }
        }
        return nerfMult;
    },
    CropToDef: function(crop, season, attackElements) {
        let cropDef = crop.defense;
        switch(crop.seasons[season]) {
            case 2: cropDef *= 2; break;
            case 0: cropDef /= 3; break;
        }
        for(let i = 0; i < attackElements; i++) {
            const attackElement = attackElements[i];
            switch(attackElement) { // 0 = water, 1 = fire, salt = 2, -1 = general
                case 0: cropDef *= 1.5 * (crop.waterResist || 0); break;
                case 1: cropDef *= 1.5 * (crop.fireResist || 0); break;
                case 2: cropDef *= 1.5 * (crop.saltResist || 0); break;
            }
        }
        return cropDef;
    },

    MeleeAttack: function(isPlayer, season, myAtk, targets, attackElements) {
        if(attackElements === undefined) { attackElement = [-1]; }
        var formattedDefs = [];
        for(var i = 0; i < targets.length; i++) {
            if(targets[i].name === undefined) { // enemy; value is just an integer for their defense
                formattedDefs.push(targets[i]);
            } else { // crop; value is a crop object
                formattedDefs.push(dmgCalcs.CropToDef(targets[i], season, attackElements));
            }
        }
        return dmgCalcs.MeleeInner(isPlayer, season, myAtk, formattedDefs);
    },
    MeleeInner: function(isPlayer, season, myAtk, theirDef) {
        var isCritical = (Math.random() < (player.luck - 0.69));
        var atkVal = myAtk;
        var hasWeapon = isPlayer && player.equipment.weapon !== null;
        if(hasWeapon) {
            var weapon = GetEquipment(player.equipment.weapon);
            var bonus = weapon.power;
            if(season === 0 && weapon.sp) { bonus += weapon.sp; }
            else if(season === 1 && weapon.su) { bonus += weapon.su; }
            else if(season === 2 && weapon.au) { bonus += weapon.au; }
            else if(season === 3 && weapon.wi) { bonus += weapon.wi; }
            atkVal += bonus / 1.1;
        }
        var attacksArr = [];
        for(var i = 0; i < theirDef.length; i++) {
            var finalDamage = atkVal - (isCritical ? 0 : (theirDef[i] / 2.2));
            if(hasWeapon) { finalDamage -= (isCritical ? 0 : (theirDef[i] / 4)); }
            attacksArr.push(new AttackData(finalDamage, isCritical));
        }
        console.log(attacksArr);

        if(isPlayer) { return { isCritical: isCritical, attackDatas: attacksArr, animData: null, recoilInfo: null }; }
        else { return attacksArr; }
    },

    CropAttack: function(isPlayer, season, myAtk, myCrops, targets, attackElements) {
        if(attackElements === undefined) { attackElement = [-1]; }
        let formattedDefs = [];
        for(let i = 0; i < targets.length; i++) {
            if(targets[i].name === undefined) { // enemy; value is just an integer for their defense
                formattedDefs.push(targets[i]);
            } else { // crop; value is a crop object
                formattedDefs.push(dmgCalcs.CropToDef(targets[i], season, attackElements));
            }
        }
        return dmgCalcs.CropInner(isPlayer, season, myAtk, myCrops, formattedDefs);
    },
    CropInner: function(isPlayer, season, myAtk, myCrops, theirDef) {
        const isCritical = isPlayer && (Math.random() < (player.luck - 0.69));
        const hasShockGloves = isPlayer && player.equipment.gloves !== null && GetEquipment(player.equipment.gloves).tech;
        const nerfs = dmgCalcs.GetNerfs(), modAtk = Math.log10(5 + myAtk * myAtk);
        let totalDamage = 0, stunLength = 0, damageToAttacker = 0, animals = [];
        let recoilInfos = [], animInfos = [];

        for(let i = 0; i < myCrops.length; i++) {
            const crop = myCrops[i].crop;
            let seasonVal = crop.seasons[season];
            if(seasonVal === 0) { seasonVal = 0.2; } else if(isPlayer) { player.miscdata.seasonsPlanted[season]++; }

            let pow = crop.power + 1;
            if(isPlayer) {
                if(crop.stickChance !== undefined && stunLength === 0) { // Stickiness
                    switch(crop.stickChance) { // TODO: add enemy resistance to stickiness
                        case 1: stunLength = ((player.luck * Math.random()) > 0.6 ? InclusiveRange(1, 2) : 0); break;
                        case 2: stunLength = ((player.luck * Math.random()) > 0.5 ? InclusiveRange(1, 3) : 0); break;
                        case 3: stunLength = ((player.luck * Math.random()) > 0.45 ? InclusiveRange(2, 5) : 0); break;
                    }
                }
                if(player.equipment.soil !== null) { // Watering Cans
                    const soil = GetEquipment(player.equipment.soil);
                    if(soil.boost !== undefined) {
                        switch(crop.seasons[season]) {
                            case 0: seasonVal += soil.boost; break;
                            case 1: seasonVal += soil.boost / 2; break;
                        }
                    } else if(soil.amp !== undefined) {
                        switch(crop.seasons[season]) { // currently values are 0, 1 and 2
                            case 0: seasonVal -= soil.amp * 0.1; break; // brings from 0.2 to 0.1 or 0 respectively
                            case 2: seasonVal *= soil.amp * 2; break; // brings from 2 to 4 or 8 respectively
                        }
                    }
                }
                if(hasShockGloves && ["water", "rice", "spear", "rod"].indexOf(crop.type) >= 0) { // Shock from Harvesting Water-based Crops
                    damageToAttacker += crop.power * 1.5;
                }
            } else if(crop.type === "tech") { pow -= 1; }

            let dmg = (modAtk * pow * pow * seasonVal * dmgCalcs.GetNerfMultiplier(crop, nerfs)) / 5;
            if(crop.type === "rice") { dmg *= 1.5; }
            else if(crop.type === "tech") { dmg *= 2; }
            if(crop.name === "app") { dmg *= 2 / (crop.activeTime + 1); }
            if(crop.animal !== undefined && ((1 - player.luck) * Math.random()) < (crop.animalChance / 8)) {
                animals.push({ crop: crop.name, animal: crop.animal });
                dmg *= crop.animalDamageMult;
            }
            let recoilInfo = null;
            if(isPlayer && ["rice", "veg", "tree", "mush", "bee", "egg", "tech"].indexOf(crop.type) >= 0) {
                if(crop.type === "rice" || (myCrops.length > 3 && combat.enemies.length > 1)) {
                    var power = crop.type === "rice" ? 1 : 0;
                    var numCrops = myCrops.length;
                    while((Math.random() * player.luck * numCrops--) > 0.9) {
                        power++;
                    }
                    if(power > 0) { recoilInfo = power * Math.max(3, dmg / 6 / combat.enemies.length); }
                }
            }
            totalDamage += dmg;
            animInfos.push({ x: myCrops[i].x, y: myCrops[i].y, recoil: recoilInfo });
            recoilInfos.push(recoilInfo);
        }
        if(isPlayer) {
            totalDamage *= 1 + (Math.floor(myCrops.length / 3) / 10); // boost by number of crops (launch 10 crops to get 1.3x boost, 20 for 1.6x, 30 for 2x)
        } else {
            totalDamage *= 1 + Math.floor(myCrops.length / 6) / 10; // boost by number of crops (launch 10 crops to get 1.1x boost, 20 for 1.3x, 30 for 1.5x)
        }
        if(isPlayer) { totalDamage += myAtk + 1; }
        var attacksArr = [];
        for(var i = 0; i < theirDef.length; i++) {
            var finalDamage = totalDamage;
            if(isPlayer) {
                finalDamage = this.GetDefendedPlayerDamage(finalDamage, isCritical, theirDef[i]);
            } else {
                finalDamage -= theirDef[i] / 1.5;
            }
            attacksArr.push(new AttackData(finalDamage, isCritical, stunLength, animals, myCrops, damageToAttacker));
        }
        if(isPlayer) { return { isCritical: isCritical, attackDatas: attacksArr, animData: animInfos, recoilInfo: recoilInfos }; }
        else { return attacksArr; }
    },
    GetDefendedPlayerDamage: function(initDamage, isCritical, theirDefense) {
        if(isCritical) { return initDamage; }
        return Math.ceil(initDamage - (theirDefense / 4));
    },

    CompostFunc: function(isPlayer, season, myAtk, myCrops, isAttack, noAction) { // isAttack: true = attack, false = heal
        const cowMult = isAttack ? 0.01 : 3, coffeeMult = isAttack ? 0.5 : 3.5, beeMult = isAttack ? 0.5 : 3;
        const baseMult = isAttack ? 0.5 : 1.25, modAtk = Math.log2(myAtk * myAtk * 0.15); // min atk is 3; log2(n) <= 0 where n <= 1; 3 * 3 * 0.15 = 1.35
        noAction = noAction || false;

        let outputAmount = 0, thereAreCows = false, thereAreBees = false, thereIsCoffee = false, negativeAmount = 0;
        const nerfs = dmgCalcs.GetNerfs();
        for(let i = 0; i < myCrops.length; i++) {
            let croppos = myCrops[i];
            if(croppos.cow !== undefined) {
                outputAmount += cowMult * combat.happyCows[croppos.cow].feed;
                combat.happyCows[croppos.cow].removeMe = true;
                thereAreCows = true;
                croppos = combat.happyCows[croppos.cow];
                if(!noAction) {
                    combat.animHelper.AddAnim(new SheetAnim(combat.dx + croppos.x + 0.25, combat.dy + croppos.y + 1, 250, "puff", 5));
                    combat.animHelper.AddAnim(new MoveAnim(combat.dx + croppos.x + 0.25, combat.dy + croppos.y + 1, combat.compost.binx, combat.compost.biny, 1000, "milk"));
                }
            } else {
                const crop = noAction ? combat.grid[croppos.x][croppos.y] : combat.ClearAndReturnCrop(croppos);
                let seasonVal = crop.seasons[season];
                if(seasonVal === 0) { seasonVal = 0.2; } else if(isPlayer) { player.miscdata.seasonsPlanted[season]++; }
                const cropPowVal = (modAtk * (crop.power + 1) * (crop.power + 1) * (seasonVal + 1)) / 20;
                if(crop.name === "poisnshroom") {
                    if(isAttack) {
                        outputAmount += 2 * baseMult * cropPowVal;
                    } else {
                        negativeAmount += 2 * baseMult * cropPowVal;
                    }
                } else if(crop.type === "bee") {
                    thereAreBees = true;
                    outputAmount += beeMult * cropPowVal;
                } else if(crop.name === "coffee") {
                    thereIsCoffee = true;
                    outputAmount += coffeeMult * cropPowVal;
                } else {
                    outputAmount += baseMult * cropPowVal;
                }
                outputAmount *= dmgCalcs.GetNerfMultiplier(crop, nerfs);
                if(!noAction) {
                    const cropSprite = crop.rotten ? "weed" : crop.name;
                    combat.animHelper.AddAnim(new SheetAnim(combat.dx + croppos.x, combat.dy + croppos.y, 250, "puff", 5));
                    combat.animHelper.AddAnim(new MoveAnim(combat.dx + croppos.x, combat.dy + croppos.y, combat.compost.binx, combat.compost.biny, 1000, cropSprite));
                }
            }
        }
        outputAmount *= 1 + (myCrops.length / 4);
        return { total: Math.max(1, outputAmount) - negativeAmount, cows: thereAreCows, bees: thereAreBees, coffee: thereIsCoffee };
    }
};<|endoftext|>