<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';

import {
	addComponent,
	removeComponent,
	watchComponent,
	updateQuery,
} from '@appbaseio/reactivecore/lib/actions';
import {
	isEqual,
	checkValueChange,
	checkPropChange,
	getClassName,
} from '@appbaseio/reactivecore/lib/utils/helper';
import types from '@appbaseio/reactivecore/lib/utils/types';

import Title from '../../styles/Title';
import Button, { toggleButtons } from '../../styles/Button';

class ToggleButton extends Component {
	constructor(props) {
		super(props);

		this.state = {
			currentValue: [],
		};
		this.locked = false;
	}

	componentWillMount() {
		this.props.addComponent(this.props.componentId);
		this.setReact(this.props);

		if (this.props.selectedValue) {
			this.handleToggle(this.props.selectedValue, true);
		} else if (this.props.defaultSelected) {
			this.handleToggle(this.props.defaultSelected, true);
		}
	}

	componentWillReceiveProps(nextProps) {
		checkPropChange(this.props.react, nextProps.react, () => {
			this.setReact(nextProps);
		});

		checkPropChange(this.props.dataField, nextProps.dataField, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});

		if (!isEqual(this.props.defaultSelected, nextProps.defaultSelected)) {
			this.handleToggle(nextProps.defaultSelected, true, nextProps);
		} else if (!isEqual(this.state.currentValue, nextProps.selectedValue)) {
			this.handleToggle(nextProps.selectedValue || [], true, nextProps);
		}
	}

	componentWillUnmount() {
		this.props.removeComponent(this.props.componentId);
	}

	defaultQuery = (value, props) => {
		let query = null;
		if (value && value.length) {
			query = {
				bool: {
					boost: 1.0,
					minimum_should_match: 1,
					should: value.map(item => ({
						term: {
							[props.dataField]: item.value,
						},
					})),
				},
			};
		}
		return query;
	};

	handleToggle = (value, isDefaultValue = false, props = this.props) => {
		const { currentValue } = this.state;
		let toggleValue = value;
		let finalValue = [];
		if (isDefaultValue) {
			if (!Array.isArray(toggleValue)) {
				toggleValue = [toggleValue];
			}
			finalValue = toggleValue.reduce((fin, next) => {
				const match = props.data.find(item => item.label === next);
				return match ? fin.concat(match) : fin;
			}, []);
		} else if (this.props.multiSelect) {
			finalValue = currentValue.some(item => item.label === toggleValue.label)
				? currentValue.filter(item => item.label !== toggleValue.label)
				: currentValue.concat(toggleValue);
		} else {
			finalValue = currentValue.some(item => item.label === toggleValue.label)
				? [] : [toggleValue];
		}
		this.setValue(finalValue);
	}

	setReact(props) {
		if (props.react) {
			props.watchComponent(props.componentId, props.react);
		}
	}

	setValue = (value, props = this.props) => {
		// ignore state updates when component is locked
		if (props.beforeValueChange && this.locked) {
			return;
		}

		this.locked = true;
		const performUpdate = () => {
			this.setState({
				currentValue: value,
			}, () => {
				this.updateQuery(value, props);
				this.locked = false;
			});
		};
		checkValueChange(
			props.componentId,
			props.multiSelect ? value : value[0],
			props.beforeValueChange,
			props.onValueChange,
			performUpdate,
		);
	};

	updateQuery = (value, props) => {
		const query = props.customQuery || this.defaultQuery;
		let onQueryChange = null;
		if (props.onQueryChange) {
			onQueryChange = props.onQueryChange;
		}
		let filterValue = value;
		if (!props.multiSelect) {
			filterValue = value[0] ? value[0].label : null;
		}
		props.updateQuery({
			componentId: props.componentId,
			query: query(value, props),
			value: filterValue,	// sets a string in URL not array
			label: props.filterLabel,
			showFilter: props.showFilter,
			onQueryChange,
			URLParams: props.URLParams,
		});
	};

	render() {
		return (
			<div style={this.props.style} className={`${toggleButtons} ${this.props.className || ''}`}>
				{
					this.props.title
					&& <Title className={getClassName(this.props.innerClass, 'title') || null}>{this.props.title}</Title>
				}
				{this.props.data.map((item) => {
					const isSelected = this.state.currentValue.some(value => value.label === item.label);
					return (
						<Button
							className={`${getClassName(this.props.innerClass, 'button')} ${isSelected ? 'active' : ''}`}
							onClick={() => this.handleToggle(item)}
							key={item.label}
							primary={isSelected}
							large
						>
							{item.label}
						</Button>
					);
				})}

		);
	}
}

ToggleButton.propTypes = {
	addComponent: types.funcRequired,
	componentId: types.stringRequired,
	data: types.data,
	dataField: types.stringRequired,
	selectedValue: types.selectedValue,
	defaultSelected: types.stringArray,
	multiSelect: types.bool,
	react: types.react,
	removeComponent: types.funcRequired,
	title: types.title,
	updateQuery: types.funcRequired,
	showFilter: types.bool,
	filterLabel: types.string,
	style: types.style,
	className: types.string,
	innerClass: types.style,
	URLParams: types.bool,
};

ToggleButton.defaultProps = {
	multiSelect: true,
	URLParams: false,
	showFilter: true,
	style: {},
	className: null,
};

const mapStateToProps = (state, props) => ({
	selectedValue:
		(state.selectedValues[props.componentId]
			&& state.selectedValues[props.componentId].value)
		|| null,
});

const mapDispatchtoProps = dispatch => ({
	addComponent: component => dispatch(addComponent(component)),
	removeComponent: component => dispatch(removeComponent(component)),
	watchComponent: (component, react) =>
		dispatch(watchComponent(component, react)),
	updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject)),
});

export default connect(mapStateToProps, mapDispatchtoProps)(ToggleButton);
<commit_msg>web: ToggleButton - Fix onQueryChange prop-type<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';

import {
	addComponent,
	removeComponent,
	watchComponent,
	updateQuery,
} from '@appbaseio/reactivecore/lib/actions';
import {
	isEqual,
	checkValueChange,
	checkPropChange,
	getClassName,
} from '@appbaseio/reactivecore/lib/utils/helper';
import types from '@appbaseio/reactivecore/lib/utils/types';

import Title from '../../styles/Title';
import Button, { toggleButtons } from '../../styles/Button';

class ToggleButton extends Component {
	constructor(props) {
		super(props);

		this.state = {
			currentValue: [],
		};
		this.locked = false;
	}

	componentWillMount() {
		this.props.addComponent(this.props.componentId);
		this.setReact(this.props);

		if (this.props.selectedValue) {
			this.handleToggle(this.props.selectedValue, true);
		} else if (this.props.defaultSelected) {
			this.handleToggle(this.props.defaultSelected, true);
		}
	}

	componentWillReceiveProps(nextProps) {
		checkPropChange(this.props.react, nextProps.react, () => {
			this.setReact(nextProps);
		});

		checkPropChange(this.props.dataField, nextProps.dataField, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});

		if (!isEqual(this.props.defaultSelected, nextProps.defaultSelected)) {
			this.handleToggle(nextProps.defaultSelected, true, nextProps);
		} else if (!isEqual(this.state.currentValue, nextProps.selectedValue)) {
			this.handleToggle(nextProps.selectedValue || [], true, nextProps);
		}
	}

	componentWillUnmount() {
		this.props.removeComponent(this.props.componentId);
	}

	defaultQuery = (value, props) => {
		let query = null;
		if (value && value.length) {
			query = {
				bool: {
					boost: 1.0,
					minimum_should_match: 1,
					should: value.map(item => ({
						term: {
							[props.dataField]: item.value,
						},
					})),
				},
			};
		}
		return query;
	};

	handleToggle = (value, isDefaultValue = false, props = this.props) => {
		const { currentValue } = this.state;
		let toggleValue = value;
		let finalValue = [];
		if (isDefaultValue) {
			if (!Array.isArray(toggleValue)) {
				toggleValue = [toggleValue];
			}
			finalValue = toggleValue.reduce((fin, next) => {
				const match = props.data.find(item => item.label === next);
				return match ? fin.concat(match) : fin;
			}, []);
		} else if (this.props.multiSelect) {
			finalValue = currentValue.some(item => item.label === toggleValue.label)
				? currentValue.filter(item => item.label !== toggleValue.label)
				: currentValue.concat(toggleValue);
		} else {
			finalValue = currentValue.some(item => item.label === toggleValue.label)
				? [] : [toggleValue];
		}
		this.setValue(finalValue);
	}

	setReact(props) {
		if (props.react) {
			props.watchComponent(props.componentId, props.react);
		}
	}

	setValue = (value, props = this.props) => {
		// ignore state updates when component is locked
		if (props.beforeValueChange && this.locked) {
			return;
		}

		this.locked = true;
		const performUpdate = () => {
			this.setState({
				currentValue: value,
			}, () => {
				this.updateQuery(value, props);
				this.locked = false;
			});
		};
		checkValueChange(
			props.componentId,
			props.multiSelect ? value : value[0],
			props.beforeValueChange,
			props.onValueChange,
			performUpdate,
		);
	};

	updateQuery = (value, props) => {
		const query = props.customQuery || this.defaultQuery;
		let onQueryChange = null;
		if (props.onQueryChange) {
			onQueryChange = props.onQueryChange;
		}
		let filterValue = value;
		if (!props.multiSelect) {
			filterValue = value[0] ? value[0].label : null;
		}
		props.updateQuery({
			componentId: props.componentId,
			query: query(value, props),
			value: filterValue,	// sets a string in URL not array
			label: props.filterLabel,
			showFilter: props.showFilter,
			onQueryChange,
			URLParams: props.URLParams,
		});
	};

	render() {
		return (
			<div style={this.props.style} className={`${toggleButtons} ${this.props.className || ''}`}>
				{
					this.props.title
					&& <Title className={getClassName(this.props.innerClass, 'title') || null}>{this.props.title}</Title>
				}
				{this.props.data.map((item) => {
					const isSelected = this.state.currentValue.some(value => value.label === item.label);
					return (
						<Button
							className={`${getClassName(this.props.innerClass, 'button')} ${isSelected ? 'active' : ''}`}
							onClick={() => this.handleToggle(item)}
							key={item.label}
							primary={isSelected}
							large
						>
							{item.label}
						</Button>
					);
				})}

		);
	}
}

ToggleButton.propTypes = {
	addComponent: types.funcRequired,
	componentId: types.stringRequired,
	data: types.data,
	dataField: types.stringRequired,
	selectedValue: types.selectedValue,
	defaultSelected: types.stringArray,
	multiSelect: types.bool,
	react: types.react,
	removeComponent: types.funcRequired,
	title: types.title,
	updateQuery: types.funcRequired,
	showFilter: types.bool,
	filterLabel: types.string,
	style: types.style,
	className: types.string,
	innerClass: types.style,
	URLParams: types.bool,
	onQueryChange: types.func,
};

ToggleButton.defaultProps = {
	multiSelect: true,
	URLParams: false,
	showFilter: true,
	style: {},
	className: null,
};

const mapStateToProps = (state, props) => ({
	selectedValue:
		(state.selectedValues[props.componentId]
			&& state.selectedValues[props.componentId].value)
		|| null,
});

const mapDispatchtoProps = dispatch => ({
	addComponent: component => dispatch(addComponent(component)),
	removeComponent: component => dispatch(removeComponent(component)),
	watchComponent: (component, react) =>
		dispatch(watchComponent(component, react)),
	updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject)),
});

export default connect(mapStateToProps, mapDispatchtoProps)(ToggleButton);
<|endoftext|>


<commit_before>/*
*
*  ??2016-2017 EdgeVerve Systems Limited (a fully owned Infosys subsidiary),
*  Bangalore, India. All Rights Reserved.
*
*/

const XLSX = require('xlsx');
const _ = require('lodash');
const tree = require('./decision-tree.js');

const rootMap = {};
const delimiter = '&SP';

const parseXLS = (path) => {
  const workbook = XLSX.readFile(path);
  const csv = [];
  workbook.SheetNames.forEach((sheetName) => {
 /* iterate through sheets */
    const worksheet = workbook.Sheets[sheetName];
    csv.push(XLSX.utils.sheet_to_csv(worksheet, { FS: delimiter }));
  });

  return csv;
};

const getFormattedValue = str => str.replace(/\"{2,}/g, '\"').replace(/^\"|\"$/g, '');

const parseContext = (csv) => {
  let context = {};
  let i = 1;

  for (; i < csv.length; i += 1) {
    const arr = csv[i].split(delimiter).filter(String);
    if (arr.length > 0 && arr[0] === 'RuleTable') {
      break;
    } else if (arr.length > 0) {
      const count = arr[1].split('"').length - 1;
      if (count > 0) {
        arr[1] = getFormattedValue(arr[1]);
      }
      context[arr[0]] = arr[1];
    }
  }
  context = Object.keys(context).length > 0 ? JSON.stringify(context).replace(/"/g, '').replace(/\\/g, '"') : '';
  return context.length > 0 ? context : null;
};

const preparePriorityList = (priorityClass, priorityValues) => {
  const priority = {};
  priorityClass.forEach((pClass, index) => {
    priority[pClass] = priority[pClass] || {};
    let p = 1;
    priorityValues[index].forEach((value) => {
      priority[pClass][value] = p;
      p += 1;
    });
  });
  return priority;
};

const calculatePriority = (priorityMat, outputs) => {
  const sortedPriority = _.sortBy(priorityMat, outputs);
  const rulePriority = {};
  sortedPriority.forEach((priority, index) => {
    const key = `Rule${priority.Rule}`;
    rulePriority[key] = index + 1;
  });
  return rulePriority;
};

const createDecisionTable = (commaSeparatedValue) => {
  const decisionTable = {};
  decisionTable.inputExpressionList = [];
  decisionTable.inputValuesList = [];
  decisionTable.outputs = [];
  decisionTable.outputValues = [];
  decisionTable.ruleList = [];

  const inputExpressionList = [];
  let outputs = [];
  const inputValuesSet = {};
  const outputValuesList = [];
  let outputLabel = false;
  let priority = {};
  const priorityMat = [];

  const csv = commaSeparatedValue.split('\n');

  let numOfConditions = 0;
  let numOfActions = 0;
  let i = 0;
  const conditionActionFilter = (elem) => {
    if (elem === 'Condition') {
      numOfConditions += 1;
    } else if (elem === 'Action') {
      numOfActions += 1;
    }
  };

  for (;i < csv.length; i += 1) {
    const arr = csv[i].split(delimiter);
    if (arr[0] === 'RuleTable') {
      arr.forEach(conditionActionFilter);
      break;
    }
  }

  i += 1;
  const classArr = csv[i].split(delimiter);
  decisionTable.hitPolicy = classArr[0];

    // input and output classes
  classArr.slice(1).every((classValue, index) => {
    if (index < numOfConditions) {
      inputExpressionList.push(classValue);
    } else {
      if (classValue === '') {
        outputLabel = true;
        return false;
      }
      outputs.push(classValue);
    }
    return true;
  });
  i += 1;
  let values = csv[i].split(/&SP(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);
    // if there is a output label which contains the output component names
  if (outputLabel) {
    outputs = [];
    numOfActions = 0;
    values = values.filter(String);// removes all blank strings from array
    values.forEach((action) => {
      numOfActions += 1;
      outputs.push(action);
    });
    i += 1;
    values = csv[i].split(/&SP(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);
  }
    // "Collect" Hit Policy Check
  if (decisionTable.hitPolicy && decisionTable.hitPolicy.charAt(0) === 'C' && decisionTable.hitPolicy.charAt(1) !== '' && numOfActions > 1) {
    throw new Error({
      hitPolicy: decisionTable.hitPolicy,
      actionItems: numOfActions,
      message: 'Hit policy violation, collect operator is undefined over multiple outputs',
    });
  }

    // input and output values
  if (values[0] === '') {
    values.slice(1).forEach((classValue, index) => {
      let value = classValue;
      value = value.replace(/(^")|("$)/g, '');
      if (index < numOfConditions) {
        inputValuesSet[inputExpressionList[index]] = value.split(',').filter(String).map((inVal) => {
          let val = inVal;
          if (val.split('"').length - 1 > 0) {
            val = val.replace(/""/g, '\"');
          }
          return val;
        });
      } else {
        outputValuesList[index - numOfConditions] = [];
        outputValuesList[index - numOfConditions] = value.split(',').filter(String).map((outVal) => {
          let val = outVal;
          if (val.split('"').length - 1 > 0) {
            val = val.replace(/""/g, '\"');
          }
          return val;
        });
      }
    });
    if (decisionTable.hitPolicy === 'P' || decisionTable.hitPolicy === 'O') {
      priority = preparePriorityList(outputs, outputValuesList);
    }
    i += 1;
  } else {
    inputExpressionList.forEach((condition) => {
      inputValuesSet[condition] = [];
    });
    outputs.forEach((action, i) => {
      outputValuesList[i] = [];
    });
  }

// rulelist
  let prevRuleRow = [];

  const processCellValue = (value, index) => {
    let cellValue = value;
    if (cellValue === '') {
      cellValue = prevRuleRow[index];
    } else {
      const count = cellValue.split('"').length - 1;
      if (count > 0) {
        cellValue = cellValue.replace(/""/g, '\"').replace(/^\"|\"$/g, '');
      }
      if ((decisionTable.hitPolicy === 'P' || decisionTable.hitPolicy === 'O') && (index >= numOfConditions)) {
        priorityMat[decisionTable.ruleList.length] = priorityMat[decisionTable.ruleList.length] || {};
        priorityMat[decisionTable.ruleList.length].Rule = decisionTable.ruleList.length + 1;
        priorityMat[decisionTable.ruleList.length][outputs[index - numOfConditions]] = priority[outputs[index - numOfConditions]][cellValue] || 0;
      }
      if (index < numOfConditions && inputValuesSet[inputExpressionList[index]].indexOf(cellValue) === -1) {
        inputValuesSet[inputExpressionList[index]].push(cellValue);
      } else if (index >= numOfConditions && outputValuesList[index - numOfConditions].indexOf(cellValue) === -1) {
        outputValuesList[index - numOfConditions].push(cellValue);
                // problem in xls 0.10 is treated as 0.1 but string treats 0.10 as 0.10
      }
    }
    return cellValue;
  };

  for (; i < csv.length; i += 1) {
    let currentRuleRow = csv[i].split(delimiter).slice(1);
    currentRuleRow = currentRuleRow.map(processCellValue);
    if (currentRuleRow.length > 0) {
      decisionTable.ruleList.push(currentRuleRow);
      prevRuleRow = currentRuleRow;
    }
  }

  if (priorityMat.length > 0) {
    decisionTable.priorityList = calculatePriority(priorityMat, outputs);
  }

  Object.keys(inputValuesSet).forEach((classKey) => {
    decisionTable.inputValuesList.push(inputValuesSet[classKey].toString());
  });
  decisionTable.inputExpressionList = inputExpressionList;
  decisionTable.outputs = outputs;
  decisionTable.outputValues = outputValuesList;
  decisionTable.context = parseContext(csv);

  return decisionTable;
};

// function updateDecisionTable(id, csv) {
//   let table = {};

//   table = createDecisionTable(csv);
//   rootMap[id] = tree.createTree(table);

//   return table;
// }

const executeDecisionTable = (id, table, payload, cb) => {
  const graphName = payload.graphName;
  let rootMapId = id;
  if (graphName) {
    rootMapId = `${graphName}${id}`;
  }
  if (rootMap[rootMapId] == null || rootMap[rootMapId] === 'undefined') {
    rootMap[rootMapId] = tree.createTree(table);
  }
  tree.traverseTree(rootMap[rootMapId], payload)
      .then(result => cb(null, result))
      .catch(err => cb(err));
};

module.exports = {
  csv_to_decision_table: createDecisionTable,
  xls_to_csv: parseXLS,
  execute_decision_table: executeDecisionTable,
};
<commit_msg>added error handling while creating decision tree<commit_after>/*
*
*  ??2016-2017 EdgeVerve Systems Limited (a fully owned Infosys subsidiary),
*  Bangalore, India. All Rights Reserved.
*
*/

const XLSX = require('xlsx');
const _ = require('lodash');
const tree = require('./decision-tree.js');

const rootMap = {};
const delimiter = '&SP';

const parseXLS = (path) => {
  const workbook = XLSX.readFile(path);
  const csv = [];
  workbook.SheetNames.forEach((sheetName) => {
 /* iterate through sheets */
    const worksheet = workbook.Sheets[sheetName];
    csv.push(XLSX.utils.sheet_to_csv(worksheet, { FS: delimiter }));
  });

  return csv;
};

const getFormattedValue = str => str.replace(/\"{2,}/g, '\"').replace(/^\"|\"$/g, '');

const parseContext = (csv) => {
  let context = {};
  let i = 1;

  for (; i < csv.length; i += 1) {
    const arr = csv[i].split(delimiter).filter(String);
    if (arr.length > 0 && arr[0] === 'RuleTable') {
      break;
    } else if (arr.length > 0) {
      const count = arr[1].split('"').length - 1;
      if (count > 0) {
        arr[1] = getFormattedValue(arr[1]);
      }
      context[arr[0]] = arr[1];
    }
  }
  context = Object.keys(context).length > 0 ? JSON.stringify(context).replace(/"/g, '').replace(/\\/g, '"') : '';
  return context.length > 0 ? context : null;
};

const preparePriorityList = (priorityClass, priorityValues) => {
  const priority = {};
  priorityClass.forEach((pClass, index) => {
    priority[pClass] = priority[pClass] || {};
    let p = 1;
    priorityValues[index].forEach((value) => {
      priority[pClass][value] = p;
      p += 1;
    });
  });
  return priority;
};

const calculatePriority = (priorityMat, outputs) => {
  const sortedPriority = _.sortBy(priorityMat, outputs);
  const rulePriority = {};
  sortedPriority.forEach((priority, index) => {
    const key = `Rule${priority.Rule}`;
    rulePriority[key] = index + 1;
  });
  return rulePriority;
};

const createDecisionTable = (commaSeparatedValue) => {
  const decisionTable = {};
  decisionTable.inputExpressionList = [];
  decisionTable.inputValuesList = [];
  decisionTable.outputs = [];
  decisionTable.outputValues = [];
  decisionTable.ruleList = [];

  const inputExpressionList = [];
  let outputs = [];
  const inputValuesSet = {};
  const outputValuesList = [];
  let outputLabel = false;
  let priority = {};
  const priorityMat = [];

  const csv = commaSeparatedValue.split('\n');

  let numOfConditions = 0;
  let numOfActions = 0;
  let i = 0;
  const conditionActionFilter = (elem) => {
    if (elem === 'Condition') {
      numOfConditions += 1;
    } else if (elem === 'Action') {
      numOfActions += 1;
    }
  };

  for (;i < csv.length; i += 1) {
    const arr = csv[i].split(delimiter);
    if (arr[0] === 'RuleTable') {
      arr.forEach(conditionActionFilter);
      break;
    }
  }

  i += 1;
  const classArr = csv[i].split(delimiter);
  decisionTable.hitPolicy = classArr[0];

    // input and output classes
  classArr.slice(1).every((classValue, index) => {
    if (index < numOfConditions) {
      inputExpressionList.push(classValue);
    } else {
      if (classValue === '') {
        outputLabel = true;
        return false;
      }
      outputs.push(classValue);
    }
    return true;
  });
  i += 1;
  let values = csv[i].split(/&SP(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);
    // if there is a output label which contains the output component names
  if (outputLabel) {
    outputs = [];
    numOfActions = 0;
    values = values.filter(String);// removes all blank strings from array
    values.forEach((action) => {
      numOfActions += 1;
      outputs.push(action);
    });
    i += 1;
    values = csv[i].split(/&SP(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);
  }
    // "Collect" Hit Policy Check
  if (decisionTable.hitPolicy && decisionTable.hitPolicy.charAt(0) === 'C' && decisionTable.hitPolicy.charAt(1) !== '' && numOfActions > 1) {
    throw new Error({
      hitPolicy: decisionTable.hitPolicy,
      actionItems: numOfActions,
      message: 'Hit policy violation, collect operator is undefined over multiple outputs',
    });
  }

    // input and output values
  if (values[0] === '') {
    values.slice(1).forEach((classValue, index) => {
      let value = classValue;
      value = value.replace(/(^")|("$)/g, '');
      if (index < numOfConditions) {
        inputValuesSet[inputExpressionList[index]] = value.split(',').filter(String).map((inVal) => {
          let val = inVal;
          if (val.split('"').length - 1 > 0) {
            val = val.replace(/""/g, '\"');
          }
          return val;
        });
      } else {
        outputValuesList[index - numOfConditions] = [];
        outputValuesList[index - numOfConditions] = value.split(',').filter(String).map((outVal) => {
          let val = outVal;
          if (val.split('"').length - 1 > 0) {
            val = val.replace(/""/g, '\"');
          }
          return val;
        });
      }
    });
    if (decisionTable.hitPolicy === 'P' || decisionTable.hitPolicy === 'O') {
      priority = preparePriorityList(outputs, outputValuesList);
    }
    i += 1;
  } else {
    inputExpressionList.forEach((condition) => {
      inputValuesSet[condition] = [];
    });
    outputs.forEach((action, i) => {
      outputValuesList[i] = [];
    });
  }

// rulelist
  let prevRuleRow = [];

  const processCellValue = (value, index) => {
    let cellValue = value;
    if (cellValue === '') {
      cellValue = prevRuleRow[index];
    } else {
      const count = cellValue.split('"').length - 1;
      if (count > 0) {
        cellValue = cellValue.replace(/""/g, '\"').replace(/^\"|\"$/g, '');
      }
      if ((decisionTable.hitPolicy === 'P' || decisionTable.hitPolicy === 'O') && (index >= numOfConditions)) {
        priorityMat[decisionTable.ruleList.length] = priorityMat[decisionTable.ruleList.length] || {};
        priorityMat[decisionTable.ruleList.length].Rule = decisionTable.ruleList.length + 1;
        priorityMat[decisionTable.ruleList.length][outputs[index - numOfConditions]] = priority[outputs[index - numOfConditions]][cellValue] || 0;
      }
      if (index < numOfConditions && inputValuesSet[inputExpressionList[index]].indexOf(cellValue) === -1) {
        inputValuesSet[inputExpressionList[index]].push(cellValue);
      } else if (index >= numOfConditions && outputValuesList[index - numOfConditions].indexOf(cellValue) === -1) {
        outputValuesList[index - numOfConditions].push(cellValue);
                // problem in xls 0.10 is treated as 0.1 but string treats 0.10 as 0.10
      }
    }
    return cellValue;
  };

  for (; i < csv.length; i += 1) {
    let currentRuleRow = csv[i].split(delimiter).slice(1);
    currentRuleRow = currentRuleRow.map(processCellValue);
    if (currentRuleRow.length > 0) {
      decisionTable.ruleList.push(currentRuleRow);
      prevRuleRow = currentRuleRow;
    }
  }

  if (priorityMat.length > 0) {
    decisionTable.priorityList = calculatePriority(priorityMat, outputs);
  }

  Object.keys(inputValuesSet).forEach((classKey) => {
    decisionTable.inputValuesList.push(inputValuesSet[classKey].toString());
  });
  decisionTable.inputExpressionList = inputExpressionList;
  decisionTable.outputs = outputs;
  decisionTable.outputValues = outputValuesList;
  decisionTable.context = parseContext(csv);

  return decisionTable;
};

// function updateDecisionTable(id, csv) {
//   let table = {};

//   table = createDecisionTable(csv);
//   rootMap[id] = tree.createTree(table);

//   return table;
// }

const executeDecisionTable = (id, table, payload, cb) => {
  const graphName = payload.graphName;
  let rootMapId = id;
  if (graphName) {
    rootMapId = `${graphName}${id}`;
  }
  if (rootMap[rootMapId] == null || rootMap[rootMapId] === 'undefined') {
    try {
      rootMap[rootMapId] = tree.createTree(table);
    } catch (e) {
      cb(e);
      return;
    }
  }
  tree.traverseTree(rootMap[rootMapId], payload)
      .then(result => cb(null, result))
      .catch(err => cb(err));
};

module.exports = {
  csv_to_decision_table: createDecisionTable,
  xls_to_csv: parseXLS,
  execute_decision_table: executeDecisionTable,
};
<|endoftext|>


<commit_before>Template.authentication.rendered = function(){
  $('.pane').css('transform', 'translate3d(0, 0, 0)');
  document.querySelector('body').classList.remove('snapjs-left');

  Meteor.setTimeout(function () {
    document.querySelector('.auth-box').classList.remove('auth-hide');
  }, 2000);

}

// Ao sair
Template.authentication.destroyed = function(){
  document.querySelector('body').classList.remove('authentication-page');
};

Template.authentication.events({
    // executa o login da rede social facebook
    'touchstart .bg-facebook, click .bg-facebook': function (event, tmp) {
      event.preventDefault();

        // acessa o methodo das configuracoes para efetuar o login de uma determinada rede social
        Meteor.loginApp(event);

        // atributos montados a partir do methodo loginApp, como as opcoes e qual servidor de login é para executar
        Meteor.loginAppService(Meteor.loginAppOptions, function(err){
          if (err){
            toastr.info(
              "Estranho, mas ocorreu um problema.. tente novamente mais tarde",
              '',
              {
                "positionClass": "toast-top-center",
                "tapToDismiss": true,
                "timeOut": 3000
              }
            );
          }else{
            var usersSearch = Meteor.users.findOne({_id:Meteor.userId()});
            var userId = User.findOne(
                {
                  facebook_id:usersSearch.services.facebook.id,
                  email:usersSearch.services.facebook.email
                }
            );

            if(userId !== undefined){
              if(userId.status === 0){
                toastr.info(
                  "Você não tem autorização, precisa de um login",
                  '',
                  {
                    "positionClass": "toast-top-center",
                    "tapToDismiss": true,
                    "timeOut": 3000
                  }
                );
              }else{
                localStorage.setItem('Meteor.facebookId', usersSearch.services.facebook.id);
                localStorage.setItem('Meteor.emailId', usersSearch.services.facebook.email);
                localStorage.setItem('Meteor.userServerId', userId._id);
                localStorage.setItem('Meteor.userId', userId._id);
                Router.go('index');
              }
            }else{
              Meteor.remote.call(
                  'insertUser',
                  [
                    111,
                    '0',
                    usersSearch.services.facebook.name,
                    'http://graph.facebook.com/' + usersSearch.services.facebook.id + '/picture/?type=large',
                    usersSearch.services.facebook.email,
                    null,
                    usersSearch.services.facebook.id,
                    null,
                    null,
                    1,
                    1
                  ],
                  function(result){
                      var userId = User.findOne(
                        {
                          facebook_id:usersSearch.services.facebook.id,
                          email:usersSearch.services.facebook.email
                        }
                      );
                      localStorage.setItem('Meteor.facebookId', usersSearch.services.facebook.id);
                      localStorage.setItem('Meteor.emailId', usersSearch.services.facebook.email);
                      localStorage.setItem('Meteor.userServerId', userId._id);
                      localStorage.setItem('Meteor.userId', userId._id);
                      Router.go('index');

                  }
              );
            }
          }
        });
    }/*,
    'touchstart .bg-google, click .bg-google': function (event, tmp) {
      event.preventDefault();

        // acessa o methodo das configuracoes para efetuar o login de uma determinada rede social
        Meteor.loginApp(event);

        // atributos montados a partir do methodo loginApp, como as opcoes e qual servidor de login é para executar
        Meteor.loginAppService(Meteor.loginAppOptions, function(err){
          if (err){
            toastr.info(
              "Estranho, mas ocorreu um problema.. tente novamente mais tarde",
              '',
              {
                "positionClass": "toast-top-center",
                "tapToDismiss": true,
                "timeOut": 3000
              }
            );
          }else{
            var usersSearch = Meteor.users.findOne({_id:Meteor.userId()});
            var userId = User.findOne(
                {
                  google_id:usersSearch.services.google.id,
                  email:usersSearch.services.google.email
                }
            );

            if(userId !== undefined){
              if(userId.status === 0){
                toastr.info(
                  "Você não tem autorização, precisa de um login",
                  '',
                  {
                    "positionClass": "toast-top-center",
                    "tapToDismiss": true,
                    "timeOut": 3000
                  }
                );
              }else{

                localStorage.setItem('Meteor.googleId', usersSearch.services.google.id);
                localStorage.setItem('Meteor.emailId', usersSearch.services.google.email);
                localStorage.setItem('Meteor.userServerId', userId._id);
                localStorage.setItem('Meteor.userId', userId._id);
                Router.go('index');
              }
            }else{
              Meteor.remote.call(
                  'insertUser',
                  [
                    111,
                    '0',
                    usersSearch.services.google.name,
                    usersSearch.services.google.picture,
                    usersSearch.services.google.email,
                    null,
                    null,
                    usersSearch.services.google.id,
                    null,
                    1,
                    1
                  ],
                  function(error, result){
                      var userId = User.findOne(
                        {
                          google_id:usersSearch.services.google.id,
                          email:usersSearch.services.google.email
                        }
                      );

                      localStorage.setItem('Meteor.googleId', usersSearch.services.google.id);
                      localStorage.setItem('Meteor.emailId', usersSearch.services.google.email);
                      localStorage.setItem('Meteor.userServerId', userId._id);
                      localStorage.setItem('Meteor.userId', userId._id);
                      Router.go('index');
                  }
              );
            }
          }
        });
    }*/
});
<commit_msg>login<commit_after>Template.authentication.rendered = function(){
  $('.pane').css('transform', 'translate3d(0, 0, 0)');
  document.querySelector('body').classList.remove('snapjs-left');

  Meteor.setTimeout(function () {
    document.querySelector('.auth-box').classList.remove('auth-hide');
  }, 2000);

}

// Ao sair
Template.authentication.destroyed = function(){
  document.querySelector('body').classList.remove('authentication-page');
};

Template.authentication.events({
    // executa o login da rede social facebook
    'touchstart .bg-facebook, click .bg-facebook': function (event, tmp) {
      IonLoading.show({
        customTemplate: 'Aguarde...'
      });

      event.preventDefault();

      Session.set('getupRemoveLoading', false);

        // acessa o methodo das configuracoes para efetuar o login de uma determinada rede social
        Meteor.loginApp(event);

        // atributos montados a partir do methodo loginApp, como as opcoes e qual servidor de login é para executar
        Meteor.loginAppService(Meteor.loginAppOptions, function(err){
          if (err){
            IonLoading.hide();
            toastr.info(
              "Estranho, mas ocorreu um problema.. tente novamente mais tarde",
              '',
              {
                "positionClass": "toast-top-center",
                "tapToDismiss": true,
                "timeOut": 3000
              }
            );
          }else{
            var usersSearch = Meteor.users.findOne({_id:Meteor.userId()});
            var userId = User.findOne(
                {
                  facebook_id:usersSearch.services.facebook.id,
                  email:usersSearch.services.facebook.email
                }
            );

            if(userId !== undefined){
              if(userId.status === 0){
                IonLoading.hide();
                toastr.info(
                  "Você não tem autorização, precisa de um login",
                  '',
                  {
                    "positionClass": "toast-top-center",
                    "tapToDismiss": true,
                    "timeOut": 3000
                  }
                );
              }else{
                localStorage.setItem('Meteor.facebookId', usersSearch.services.facebook.id);
                localStorage.setItem('Meteor.emailId', usersSearch.services.facebook.email);
                localStorage.setItem('Meteor.userServerId', userId._id);
                localStorage.setItem('Meteor.userId', userId._id);

                IonLoading.hide();
                Router.go('index');
              }
            }else{
              Meteor.remote.call(
                  'insertUser',
                  [
                    111,
                    '0',
                    usersSearch.services.facebook.name,
                    'http://graph.facebook.com/' + usersSearch.services.facebook.id + '/picture/?type=small',
                    usersSearch.services.facebook.email,
                    null,
                    usersSearch.services.facebook.id,
                    null,
                    null,
                    1,
                    1
                  ],
                  function(result){
                      var userId = User.findOne(
                        {
                          facebook_id:usersSearch.services.facebook.id,
                          email:usersSearch.services.facebook.email
                        }
                      );
                      localStorage.setItem('Meteor.facebookId', usersSearch.services.facebook.id);
                      localStorage.setItem('Meteor.emailId', usersSearch.services.facebook.email);
                      localStorage.setItem('Meteor.userServerId', userId._id);
                      localStorage.setItem('Meteor.userId', userId._id);

                      IonLoading.hide();
                      Router.go('index');
                  }
              );
            }
          }
        });
    }/*,
    'touchstart .bg-google, click .bg-google': function (event, tmp) {
      event.preventDefault();

        // acessa o methodo das configuracoes para efetuar o login de uma determinada rede social
        Meteor.loginApp(event);

        // atributos montados a partir do methodo loginApp, como as opcoes e qual servidor de login é para executar
        Meteor.loginAppService(Meteor.loginAppOptions, function(err){
          if (err){
            toastr.info(
              "Estranho, mas ocorreu um problema.. tente novamente mais tarde",
              '',
              {
                "positionClass": "toast-top-center",
                "tapToDismiss": true,
                "timeOut": 3000
              }
            );
          }else{
            var usersSearch = Meteor.users.findOne({_id:Meteor.userId()});
            var userId = User.findOne(
                {
                  google_id:usersSearch.services.google.id,
                  email:usersSearch.services.google.email
                }
            );

            if(userId !== undefined){
              if(userId.status === 0){
                toastr.info(
                  "Você não tem autorização, precisa de um login",
                  '',
                  {
                    "positionClass": "toast-top-center",
                    "tapToDismiss": true,
                    "timeOut": 3000
                  }
                );
              }else{

                localStorage.setItem('Meteor.googleId', usersSearch.services.google.id);
                localStorage.setItem('Meteor.emailId', usersSearch.services.google.email);
                localStorage.setItem('Meteor.userServerId', userId._id);
                localStorage.setItem('Meteor.userId', userId._id);
                Router.go('index');
              }
            }else{
              Meteor.remote.call(
                  'insertUser',
                  [
                    111,
                    '0',
                    usersSearch.services.google.name,
                    usersSearch.services.google.picture,
                    usersSearch.services.google.email,
                    null,
                    null,
                    usersSearch.services.google.id,
                    null,
                    1,
                    1
                  ],
                  function(error, result){
                      var userId = User.findOne(
                        {
                          google_id:usersSearch.services.google.id,
                          email:usersSearch.services.google.email
                        }
                      );

                      localStorage.setItem('Meteor.googleId', usersSearch.services.google.id);
                      localStorage.setItem('Meteor.emailId', usersSearch.services.google.email);
                      localStorage.setItem('Meteor.userServerId', userId._id);
                      localStorage.setItem('Meteor.userId', userId._id);
                      Router.go('index');
                  }
              );
            }
          }
        });
    }*/
});
<|endoftext|>


<commit_before>var path = require('path');
var fse = require('fs-extra');
var expect = require('chai').expect;
var mv = require('mv');
var depDoc = require('../lib/fileProcessor');

describe('Original Files', function() {

	describe('References', function() {
		var files;
		var config = {
			workingDir: 'test/fixtures/original'
		};
		beforeEach(function(done) {
			depDoc.getReferences(config).then(function(result) {
				files = result;
				done();
			})
		});
		it('Should get correct number of files', function() {
			expect(Object.keys(files.existingFiles)).to.have.length(13);
		});
		it('Should get correct file paths', function() {
			expect(files.existingFiles).to.have.property(path.join(process.cwd(), config.workingDir, 'root/file1.json'));
			expect(files.existingFiles).to.have.property(path.join(process.cwd(), config.workingDir, 'root/level1a/file1.jsx'));
			expect(files.existingFiles).to.have.property(path.join(process.cwd(), config.workingDir, 'root/level1a/level2a/level3a/file8.js'));
		});
		it('Should get correct number of references within files', function() {
			expect(Object.keys(files.referencedFiles)).to.have.length(8);
		})
	});

	describe('Broken References', function() {
		var brokenReferences;
		var config = {
			workingDir: 'test/fixtures/original'
		};
		beforeEach(function(done) {
			depDoc.getBrokenReferences(config).then(function(result) {
				brokenReferences = result;
				done();
			})
		});
		it('Should find no broken references', function() {
			expect(Object.keys(brokenReferences)).to.have.length(0);
		});
	});

});

describe('Moved Files', function() {
	before(function() {

	});
});<commit_msg>more tests<commit_after>var path = require('path');
var fse = require('fs-extra');
var Q = require('q');
var expect = require('chai').expect;
var mv = require('mv');
var depDoc = require('../lib/fileProcessor');

describe('Original Files', function() {

	describe('References', function() {
		var files;
		var config = {
			workingDir: 'test/fixtures/original'
		};
		beforeEach(function(done) {
			depDoc.getReferences(config).then(function(result) {
				files = result;
				done();
			})
		});
		it('Should get correct number of files', function() {
			expect(Object.keys(files.existingFiles)).to.have.length(13);
		});
		it('Should get correct file paths', function() {
			expect(files.existingFiles).to.have.property(path.join(process.cwd(), config.workingDir, 'root/file1.json'));
			expect(files.existingFiles).to.have.property(path.join(process.cwd(), config.workingDir, 'root/level1a/file1.jsx'));
			expect(files.existingFiles).to.have.property(path.join(process.cwd(), config.workingDir, 'root/level1a/level2a/level3a/file8.js'));
		});
		it('Should get correct number of references within files', function() {
			expect(Object.keys(files.referencedFiles)).to.have.length(8);
		})
	});

	describe('Broken References', function() {
		var brokenReferences;
		var config = {
			workingDir: 'test/fixtures/original'
		};
		beforeEach(function(done) {
			depDoc.getBrokenReferences(config).then(function(result) {
				brokenReferences = result;
				done();
			})
		});
		it('Should find no broken references', function() {
			expect(Object.keys(brokenReferences)).to.have.length(0);
		});
	});

});

describe('Moved Files', function() {
	var config = {
		workingDir: 'test/fixtures/moved'
	};
	var baseDir = path.join(process.cwd(), config.workingDir) + '/';
	var rootDir = path.join(baseDir, 'root') + '/';
	before(function(done) {
		Q.nfcall(fse.emptyDir, 'test/fixtures/moved')
			.then(function() {
				return Q.nfcall(fse.copy,
					'test/fixtures/original',
					baseDir
				);
			})
			.then(function() {
				return Q.nfcall(fse.mkdirs,
					rootDir + 'level1c/level2c/level3c'
				)
			})
			.then(function() {
				console.log('Test files copied');
				return Q.all([
					Q.nfcall(fse.move,
						rootDir + 'file1.js',
						rootDir + 'level2c/level3c/file1.js'
					)
				]);
			})
			.then(function() {
				console.log('File structure prepared for tests');
				done();
			})
			.catch(function(err) {
				console.error(err);
				done(err);
			});
	});
	after(function() {
		fse
	});
	describe('References', function() {
		var files;
		beforeEach(function(done) {
			depDoc.getReferences(config).then(function(result) {
				files = result;
				done();
			})
		});
		it('Should get correct number of files', function() {
			expect(Object.keys(files.existingFiles)).to.have.length(13);
		});
	});

	describe('Broken References', function() {
		var brokenReferences;
		var config = {
			workingDir: 'test/fixtures/moved'
		};
		beforeEach(function(done) {
			depDoc.getBrokenReferences(config)
				.then(function(result) {
					brokenReferences = result;
					done();
				})
		});
		it('Should find correct number of broken references', function() {
			expect(Object.keys(brokenReferences)).to.have.length(8);
		});
		it('Should correctly identify broken references', function() {
			expect(brokenReferences[0].referencedFile).to.equal(rootDir + 'level2c/level3c/level1a/file1.jsx');
			expect(brokenReferences[0].referencingFiles[0]).to.equal(rootDir + 'level2c/level3c/file1.js')
		});
	});

});<|endoftext|>


<commit_before>var builderRequest = angular.module('builder-request', ['builder-utils']);

/* Produce an angular JSON request object
   for requesting data from WMS/WFS servers */
builderRequest.service("geoRequest", function() {
  return function (params) {
    window.bbox = params.bbox;
    var data = {
      service: params.serviceType,
      request: params.requestType,
      outputFormat: params.format,
      format: params.format,
    };

    if (!$.isEmptyObject(params.bbox) && data.request != "GetCapabilities") {
      if (data.service == "WMS")
        data.bbox = [params.bbox.minx, params.bbox.miny, params.bbox.maxx, params.bbox.maxy].join();
      if (data.service == "WFS")
        data.bbox = [params.bbox.miny, params.bbox.minx, params.bbox.maxy, params.bbox.maxx].join();
    }

    if (data.service == "WMS" && data.request != "GetCapabilities") {
      data.layers = params.features ? params.features.join() : undefined;
      data.width = params.width;
      data.height = params.height;
    }
    if (data.service == "WFS" && data.request != "GetCapabilities") {
      data.typeName = params.feature;
      data.maxFeatures = params.featureLimit;
    }

    var request = {
      method: "GET",
      headers: {},
      url: params.host + "/ows",
      params: data,
    };

    return request;
  };
});

/* Produce a URI for the source of an image
   This image is produced from a WMS request */
builderRequest.service('geoImage', ['geoRequest', 'imageWidth', function(request, getImageWidth) {
  return function(host, features, bbox, height) {
    // Only map if there are features to map
    if (features) {
      $("#preview-image img").attr("src", "images/loading.gif");

      var imageParams = {
        host: host,
        serviceType: "WMS",
        requestType: "GetMap",
        outputFormat: "image/png",
        format: "image/png",
        width: getImageWidth(bbox, height),
        height: height,
        features: features,
        bbox: bbox,
      };

      var req = request(imageParams);
      var src = req.url + "?" + $.param(req.params);
      $("#preview-image img").attr("src", src);
    } else {
      return "";
    }
  };
}]);
<commit_msg>Fixed WFS image request.<commit_after>var builderRequest = angular.module('builder-request', ['builder-utils']);

/* Produce an angular JSON request object
   for requesting data from WMS/WFS servers */
builderRequest.service("geoRequest", function() {
  return function (params) {
    window.bbox = params.bbox;
    var data = {
      service: params.serviceType,
      request: params.requestType,
      outputFormat: params.format,
      format: params.format,
    };

    if (!$.isEmptyObject(params.bbox) && data.request != "GetCapabilities") {
      if (data.service == "WMS")
        data.bbox = [params.bbox.minx, params.bbox.miny, params.bbox.maxx, params.bbox.maxy].join();
      if (data.service == "WFS")
        data.bbox = [params.bbox.miny, params.bbox.minx, params.bbox.maxy, params.bbox.maxx].join();
    }

    if (data.service == "WMS" && data.request != "GetCapabilities") {
      data.layers = params.features ? params.features.join() : undefined;
      data.width = params.width;
      data.height = params.height;
    }
    if (data.service == "WFS" && data.request != "GetCapabilities") {
      data.typeName = params.feature;
      data.maxFeatures = params.featureLimit;
    }

    var request = {
      method: "GET",
      headers: {},
      url: params.host + "/ows",
      params: data,
    };

    return request;
  };
});

/* Produce a URI for the source of an image
   This image is produced from a WMS request */
builderRequest.service('geoImage', ['geoRequest', 'imageWidth', function(request, getImageWidth) {
  return function(host, features, bbox, height) {
    // Only map if there are features to map
    if (features) {
      $("#preview-image img").attr("src", "images/loading.gif");

      var imageParams = {
        host: host,
        serviceType: "WMS",
        requestType: "GetMap",
        outputFormat: "image/png",
        format: "image/png",
        width: getImageWidth(bbox, height),
        height: height,
        features: (typeof(features) == typeof([]))? features : [features],
        bbox: bbox,
      };

      var req = request(imageParams);
      var src = req.url + "?" + $.param(req.params);
      $("#preview-image img").attr("src", src);
    } else {
      return "";
    }
  };
}]);
<|endoftext|>


<commit_before>import THREE from 'three';

import OrbitControls from './OrbitControls';

class ModelScene {
  // Renderer of the Scene
  renderer = undefined;
  // The Scene
  scene = undefined;
  // The Main Camera in the scene
  camera = undefined;
  // The main front light
  frontLight = undefined;
  // Background scene and camera
  backgroundScene = undefined;
  backgroundCamera = undefined;
  // The Model
  model = undefined;
  // Stores currently displayed objects (meshes/models)
  displayObjects = [];
  // Orbit Controls
  controls = undefined;
  // Current Rendering State
  renderingState = {
    wireframe: false,
    shadingMode: 0,
    shading: THREE.SmoothShading
  };
  // Camera State
  cameraState = {
    autoRotate: false,
    resetView: false
  };

  /**
   * Constructor function of the scene
   * @param  {DOMElement} sceneCanvas [the dom element for the canvas containing the scene]
   * @param  {Object} dimensions  [dimensions data of the canvas]
   */
  constructor(sceneCanvas, dimensions) {
    this._init(sceneCanvas, dimensions);
  }

  _init(sceneCanvas, dimensions) {
    this._initRenderer(sceneCanvas, dimensions);
    this._initScene();
    this._initCamera(dimensions);
    this._initBackground();
    this._initLight();
    this._initControls(dimensions);

    this._animate();
  }

  _initRenderer(sceneCanvas, dimensions) {
    this.renderer = new THREE.WebGLRenderer({ canvas: sceneCanvas, antialias: true });
    this.renderer.setSize(dimensions.width, dimensions.height);
    this.renderer.setClearColor(0x212121, 0); // Alpha value set to 0 for transparancy
    this.renderer.autoClear = false;
  }

  _initScene() {
    this.scene = new THREE.Scene();
  }

  _initCamera(dimensions) {
    this.camera = new THREE.PerspectiveCamera(45, dimensions.aspectRatio, 0.1, 10000);
    this.scene.add(this.camera);
    this.camera.position.set(0, 450, 500);
    this.camera.lookAt(this.scene.position);
  }

  _initBackground() {
    // Load background texture
    const texture = THREE.ImageUtils.loadTexture('/models/doge.jpeg');
    //const texture = THREE.ImageUtils.loadTexture('/home/ben/Documents/cubist/models/doge.jpeg');
    const backgroundMesh = new THREE.Mesh(
      new THREE.PlaneGeometry(2, 2, 0),
      new THREE.MeshBasicMaterial({
        map: texture
      }));
    // Turn off any depth checking
    backgroundMesh.material.depthTest = false;
    backgroundMesh.material.depthWrite = false;
    // Create the background scene
    this.backgroundScene = new THREE.Scene();
    this.backgroundCamera = new THREE.Camera();
    this.backgroundScene.add(this.backgroundCamera);
    this.backgroundScene.add(backgroundMesh);
  }

  _initLight() {
    // Main front light
    this.frontLight = new THREE.PointLight(0xdddddd);
    this.frontLight.castShadow = true;
    this.camera.add(this.frontLight);
    /*
    // Main front light
    const light = new THREE.PointLight(0xdddddd);
    light.position.set(-100, 250, 200);
    light.castShadow = true;
    this.scene.add(light);

    // Fill light
    const light2 = new THREE.PointLight(0x777777);
    light2.position.set(100, 100, 200);
    this.scene.add(light2);

    // Back light
    const light3 = new THREE.PointLight(0x777777);
    light3.position.set(0, 100, -200);
    this.scene.add(light3);
    */

    // Ambient light
    const ambientLight = new THREE.AmbientLight(0x444444);
    this.scene.add(ambientLight);
  }

  _initControls(dimensions) {
    this.controls = new OrbitControls(this.camera, dimensions);
  }

  /**
   * Frame updater function
   */
  _animate() {
    requestAnimationFrame(this._animate.bind(this));
    this.controls.update();
    this._render();
  }

  /**
   * Render function which will be called for every fame
   */
  _render() {
    this.renderer.clear();
    // Render background first so that the model appears in front
    this.renderer.render(this.backgroundScene, this.backgroundCamera);
    this.renderer.render(this.scene, this.camera);
  }

  /**
   * Update the objects (meshes/models) displayed in the scene
   */
  updateSceneObjects() {
    this.removeSceneObjects();
    this.displayObjects = this._getDisplayObjects();
    for (let i = 0; i < this.displayObjects.length; i++) {
      this.displayObjects[i].scale.set(40, 40, 40);
      this.displayObjects[i].position.y = -20;
      this.scene.add(this.displayObjects[i]);
    }
  }

  /**
   * Update the model variable of this class
   * @param  {Object} model [the new model to be displayed]
   */
  updateModel(model) {
    this.model = model;
    this.updateSceneObjects();
  }

  /**
   * Update the rendering state of the model
   * @param  {Object} state [the new state which will be merged with the existing state]
   */
  updateRenderingState(state) {
    Object.assign(this.renderingState, state);
    this.updateSceneObjects();
  }

  updateCameraState(state) {
    Object.assign(this.cameraState, state);
    this.controls.resetView = this.cameraState.resetView;
    this.controls.autoRotate = this.cameraState.autoRotate;
  }

  /**
   * Remove objects (models/meshes) currently displayed in the scene
   */
  removeSceneObjects() {
    for (let i = 0; i < this.displayObjects.length; i++) {
      this.scene.remove(this.displayObjects[i]);
    }
  }

  /**
   * Get the objects to display based on this.model and rendering state
   */
  _getDisplayObjects() {
    const objects = [];
    const { wireframe, shadingMode } = this.renderingState;
    // Default Shading Mode
    if (shadingMode === 0 || 1) {
      objects.push(this.model);
    }
    // Shadeless Mode - turn lights off in shadeless mode
    if (shadingMode === 1) {
      this.frontLight.visible = false;
    } else {
      this.frontLight.visible = true;
    }
    // Smooth Shading mode
    if (shadingMode === 2) {
      this.model.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
          const newMesh = new THREE.Mesh(child.geometry, new THREE.MeshPhongMaterial({
            color: 0xc0c0c0,
            shading: THREE.SmoothShading,
            wireframe: false,
            transparent: true
          }));
          objects.push(newMesh);
        }
      });
    }
    // Flat Shading mode
    if (shadingMode === 3) {
      this.model.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
          const newMesh = new THREE.Mesh(child.geometry, new THREE.MeshPhongMaterial({
            color: 0xc0c0c0,
            shading: THREE.FlatShading,
            wireframe: false,
            transparent: true
          }));
          objects.push(newMesh);
        }
      });
    }

    if (wireframe) {
      this.model.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
          const newMesh = new THREE.Mesh(child.geometry, new THREE.MeshPhongMaterial({
            color: 0x00e0c0,
            shading: THREE.FlatShading,
            wireframe: true,
            transparent: true
          }));
          objects.push(newMesh);
        }
      });
    }
    return objects;
  }

  /**
   * Handler function for the scene when the scene dimensions are modified
   * @param  {Object} dimensions [data of the scene dimensions]
   */
  onResize(dimensions) {
    this.camera.aspect = dimensions.aspectRatio;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(dimensions.width, dimensions.height);
    this.controls.setDimensions(dimensions.width, dimensions.height);
  }

  onMouseDown(event, callback) {
    this.controls.onMouseDown(event);
    callback(this.getCameraOrbit());
  }

  onMouseMove(event, callback) {
    this.controls.onMouseMove(event);
    callback(this.getCameraOrbit());
  }

  onMouseUp(event, callback) {
    this.controls.onMouseUp(event);
    callback(this.getCameraOrbit());
  }

  onWheel(event, callback) {
    this.controls.onMouseWheel(event);
    callback(this.getCameraOrbit());
  }

  getCameraOrbit() {
    const lookAt = new THREE.Vector3(0, 0, -1);
    lookAt.applyMatrix4(this.camera.matrixWorld);
    return {
      position: this.camera.position,
      up: this.camera.up,
      lookAt,
      zoom: this.camera.zoom
    };
  }

  /**
   * Dispose all entities in scene
   */
  dispose() {

  }
}

export default ModelScene;
<commit_msg>[update] Code cleanup<commit_after>import THREE from 'three';

import OrbitControls from './OrbitControls';

class ModelScene {
  // Renderer of the Scene
  renderer = undefined;
  // The Scene
  scene = undefined;
  // The Main Camera in the scene
  camera = undefined;
  // The main front light
  frontLight = undefined;
  // Background scene and camera
  backgroundScene = undefined;
  backgroundCamera = undefined;
  // The Model
  model = undefined;
  // Stores currently displayed objects (meshes/models)
  displayObjects = [];
  // Orbit Controls
  controls = undefined;
  // Current Rendering State
  renderingState = {
    wireframe: false,
    shadingMode: 0,
    shading: THREE.SmoothShading
  };
  // Camera State
  cameraState = {
    autoRotate: false,
    resetView: false
  };

  /**
   * Constructor function of the scene
   * @param  {DOMElement} sceneCanvas [the dom element for the canvas containing the scene]
   * @param  {Object} dimensions  [dimensions data of the canvas]
   */
  constructor(sceneCanvas, dimensions) {
    this._init(sceneCanvas, dimensions);
  }

  _init(sceneCanvas, dimensions) {
    this._initRenderer(sceneCanvas, dimensions);
    this._initScene();
    this._initCamera(dimensions);
    this._initBackground();
    this._initLight();
    this._initControls(dimensions);

    this._animate();
  }

  _initRenderer(sceneCanvas, dimensions) {
    this.renderer = new THREE.WebGLRenderer({ canvas: sceneCanvas, antialias: true });
    this.renderer.setSize(dimensions.width, dimensions.height);
    this.renderer.setClearColor(0x212121, 0); // Alpha value set to 0 for transparancy
    this.renderer.autoClear = false;
  }

  _initScene() {
    this.scene = new THREE.Scene();
  }

  _initCamera(dimensions) {
    this.camera = new THREE.PerspectiveCamera(45, dimensions.aspectRatio, 0.1, 10000);
    this.scene.add(this.camera);
    this.camera.position.set(0, 450, 500);
    this.camera.lookAt(this.scene.position);
  }

  _initBackground() {
    // Load background texture
    const texture = THREE.ImageUtils.loadTexture('/models/doge.jpeg');
    const backgroundMesh = new THREE.Mesh(
      new THREE.PlaneGeometry(2, 2, 0),
      new THREE.MeshBasicMaterial({
        map: texture
      }));
    // Turn off any depth checking
    backgroundMesh.material.depthTest = false;
    backgroundMesh.material.depthWrite = false;
    // Create the background scene
    this.backgroundScene = new THREE.Scene();
    this.backgroundCamera = new THREE.Camera();
    this.backgroundScene.add(this.backgroundCamera);
    this.backgroundScene.add(backgroundMesh);
  }

  _initLight() {
    // Main front light
    this.frontLight = new THREE.PointLight(0xdddddd);
    this.frontLight.castShadow = true;
    this.camera.add(this.frontLight);

    // Ambient light
    const ambientLight = new THREE.AmbientLight(0x444444);
    this.scene.add(ambientLight);
  }

  _initControls(dimensions) {
    this.controls = new OrbitControls(this.camera, dimensions);
  }

  /**
   * Frame updater function
   */
  _animate() {
    requestAnimationFrame(this._animate.bind(this));
    this.controls.update();
    this._render();
  }

  /**
   * Render function which will be called for every fame
   */
  _render() {
    this.renderer.clear();
    // Render background first so that the model appears in front
    this.renderer.render(this.backgroundScene, this.backgroundCamera);
    this.renderer.render(this.scene, this.camera);
  }

  /**
   * Update the objects (meshes/models) displayed in the scene
   */
  updateSceneObjects() {
    this.removeSceneObjects();
    this.displayObjects = this._getDisplayObjects();
    for (let i = 0; i < this.displayObjects.length; i++) {
      this.displayObjects[i].scale.set(40, 40, 40);
      this.displayObjects[i].position.y = -20;
      this.scene.add(this.displayObjects[i]);
    }
  }

  /**
   * Update the model variable of this class
   * @param  {Object} model [the new model to be displayed]
   */
  updateModel(model) {
    this.model = model;
    this.updateSceneObjects();
  }

  /**
   * Update the rendering state of the model
   * @param  {Object} state [the new state which will be merged with the existing state]
   */
  updateRenderingState(state) {
    Object.assign(this.renderingState, state);
    this.updateSceneObjects();
  }

  updateCameraState(state) {
    Object.assign(this.cameraState, state);
    this.controls.resetView = this.cameraState.resetView;
    this.controls.autoRotate = this.cameraState.autoRotate;
  }

  /**
   * Remove objects (models/meshes) currently displayed in the scene
   */
  removeSceneObjects() {
    for (let i = 0; i < this.displayObjects.length; i++) {
      this.scene.remove(this.displayObjects[i]);
    }
  }

  /**
   * Get the objects to display based on this.model and rendering state
   */
  _getDisplayObjects() {
    const objects = [];
    const { wireframe, shadingMode } = this.renderingState;
    // Default Shading Mode
    if (shadingMode === 0 || 1) {
      objects.push(this.model);
    }
    // Shadeless Mode - turn lights off in shadeless mode
    if (shadingMode === 1) {
      this.frontLight.visible = false;
    } else {
      this.frontLight.visible = true;
    }
    // Smooth Shading mode
    if (shadingMode === 2) {
      this.model.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
          const newMesh = new THREE.Mesh(child.geometry, new THREE.MeshPhongMaterial({
            color: 0xc0c0c0,
            shading: THREE.SmoothShading,
            wireframe: false,
            transparent: true
          }));
          objects.push(newMesh);
        }
      });
    }
    // Flat Shading mode
    if (shadingMode === 3) {
      this.model.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
          const newMesh = new THREE.Mesh(child.geometry, new THREE.MeshPhongMaterial({
            color: 0xc0c0c0,
            shading: THREE.FlatShading,
            wireframe: false,
            transparent: true
          }));
          objects.push(newMesh);
        }
      });
    }

    if (wireframe) {
      this.model.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
          const newMesh = new THREE.Mesh(child.geometry, new THREE.MeshPhongMaterial({
            color: 0x00e0c0,
            shading: THREE.FlatShading,
            wireframe: true,
            transparent: true
          }));
          objects.push(newMesh);
        }
      });
    }
    return objects;
  }

  /**
   * Handler function for the scene when the scene dimensions are modified
   * @param  {Object} dimensions [data of the scene dimensions]
   */
  onResize(dimensions) {
    this.camera.aspect = dimensions.aspectRatio;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(dimensions.width, dimensions.height);
    this.controls.setDimensions(dimensions.width, dimensions.height);
  }

  onMouseDown(event, callback) {
    this.controls.onMouseDown(event);
    callback(this.getCameraOrbit());
  }

  onMouseMove(event, callback) {
    this.controls.onMouseMove(event);
    callback(this.getCameraOrbit());
  }

  onMouseUp(event, callback) {
    this.controls.onMouseUp(event);
    callback(this.getCameraOrbit());
  }

  onWheel(event, callback) {
    this.controls.onMouseWheel(event);
    callback(this.getCameraOrbit());
  }

  getCameraOrbit() {
    const lookAt = new THREE.Vector3(0, 0, -1);
    lookAt.applyMatrix4(this.camera.matrixWorld);
    return {
      position: this.camera.position,
      up: this.camera.up,
      lookAt,
      zoom: this.camera.zoom
    };
  }

  /**
   * Dispose all entities in scene
   */
  dispose() {

  }
}

export default ModelScene;
<|endoftext|>


<commit_before>import {dissoc} from 'ramda'
import React from 'react'
import ReactDOM from 'react-dom'
import createVirtualAudioGraph from 'virtual-audio-graph'

const graphs = new WeakMap()
const outputs = new WeakMap()
const virtualAudioGraphs = new WeakMap()
const osc1Settings = new WeakMap()
const osc2Settings = new WeakMap()

export default class {
  constructor ({audioContext}) {
    const output = audioContext.createGain()
    outputs.set(this, output)
    graphs.set(this, {})
    osc1Settings.set(this, {detune: 0, type: 'sine'})
    osc2Settings.set(this, {detune: 10, type: 'sine'})
    const virtualAudioGraph = createVirtualAudioGraph({audioContext, output})
    virtualAudioGraph.defineNodes({
      oscBank: ({gain, frequency, startTime, stopTime}) => ({
        0: ['gain', 'output', {gain}],
        1: ['oscillator', 0, {
          ...osc1Settings.get(this),
          frequency,
          startTime,
          stopTime
        }],
        2: ['oscillator', 0, {
          ...osc2Settings.get(this),
          frequency,
          startTime,
          stopTime
        }]
      })
    })
    virtualAudioGraphs.set(this, virtualAudioGraph)
  }
  connect (destination) {
    outputs.get(this).connect(destination)
  }
  disconnect (destination) {
    outputs.get(this).disconnect(destination)
  }
  inputNoteStart ({frequency, gain, id, startTime, stopTime}) {
    const newNodes = {
      ...graphs.get(this),
      0: ['gain', 'output', {gain}],
      [id]: ['oscBank', 0, {
        gain,
        frequency,
        startTime,
        stopTime
      }]
    }
    graphs.set(this, newNodes)
    virtualAudioGraphs.get(this).update(newNodes)
  }
  inputNoteStop (id) {
    const newGraph = dissoc(id, graphs.get(this))
    graphs.set(this, newGraph)
    virtualAudioGraphs.get(this).update(newGraph)
  }
  render (containerEl) {
    ReactDOM.render(

Prometheus

Osc 1

            Type
            <select
              defaultValue={osc1Settings.get(this).type}
              onChange={e => osc1Settings.set(
                this,
                {...osc1Settings.get(this), type: e.target.value}
              )}
            >
              <option value='sawtooth'>Sawtooth</option>
              <option value='sine'>Sine</option>
              <option value='square'>Square</option>
              <option value='triangle'>Triangle</option>
            </select>

            Detune
            <input
              defaultValue={osc1Settings.get(this).detune}
              max='50'
              min='-50'
              onInput={e => osc1Settings.set(
                this,
                {...osc1Settings.get(this), detune: Number(e.target.value)}
              )}
              type='range'
            />

Osc 2

            Type
            <select
              defaultValue={osc2Settings.get(this).type}
              onChange={e => osc2Settings.set(
                this,
                {...osc1Settings.get(this), type: e.target.value}
              )}
            >
              <option value='sawtooth'>Sawtooth</option>
              <option value='sine'>Sine</option>
              <option value='square'>Square</option>
              <option value='triangle'>Triangle</option>
            </select>

            Detune
            <input
              defaultValue={osc2Settings.get(this).detune}
              max='50'
              min='-50'
              onInput={e => osc2Settings.set(
                this,
                {...osc2Settings.get(this), detune: Number(e.target.value)}
              )}
              type='range'
            />

,
      containerEl
    )
  }
}
<commit_msg>feat(prometheus) user can now update params while playing notes yay<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import createVirtualAudioGraph from 'virtual-audio-graph'

const graphs = new WeakMap()
const notes = new WeakMap()
const osc1Settings = new WeakMap()
const osc2Settings = new WeakMap()
const outputs = new WeakMap()
const virtualAudioGraphs = new WeakMap()

const notesToGraph = notes => notes.reduce((acc, {
  frequency, gain, id, startTime, stopTime
}) => ({
  ...acc,
  0: ['gain', 'output', {gain}],
  [id]: ['oscBank', 0, {
    gain,
    frequency,
    startTime,
    stopTime
  }],
}), {})

const updateAudio = function () {
  virtualAudioGraphs.get(this).update(notesToGraph(notes.get(this)))
}

const ControlContainer = ({children}) =>

    {children}

export default class {
  constructor ({audioContext}) {
    const output = audioContext.createGain()
    outputs.set(this, output)
    graphs.set(this, {})
    notes.set(this, [])
    osc1Settings.set(this, {detune: 0, type: 'sine'})
    osc2Settings.set(this, {detune: 10, type: 'sine'})
    const virtualAudioGraph = createVirtualAudioGraph({audioContext, output})
    virtualAudioGraph.defineNodes({
      oscBank: ({gain, frequency, startTime, stopTime}) => ({
        0: ['gain', 'output', {gain}],
        1: ['oscillator', 0, {
          ...osc1Settings.get(this),
          frequency,
          startTime,
          stopTime
        }],
        2: ['oscillator', 0, {
          ...osc2Settings.get(this),
          frequency,
          startTime,
          stopTime
        }]
      })
    })
    virtualAudioGraphs.set(this, virtualAudioGraph)
  }
  connect (destination) {
    outputs.get(this).connect(destination)
  }
  disconnect (destination) {
    outputs.get(this).disconnect(destination)
  }
  inputNoteStart (note) {
    const newNotes = [...notes.get(this), note]
    notes.set(this, newNotes)
    updateAudio.call(this)
  }
  inputNoteStop (id) {
    const newNotes = notes.get(this).filter(note => note.id !== id)
    notes.set(this, newNotes)
    updateAudio.call(this)
  }
  render (containerEl) {
    ReactDOM.render(

Prometheus

Osc 1

        <ControlContainer>
          Type
          <select
            defaultValue={osc1Settings.get(this).type}
            onChange={({target: {value}}) => {
              osc1Settings.set(this, {
                ...osc1Settings.get(this),
                type: value
              })
              updateAudio.call(this)
            }}
          >
            <option value='sawtooth'>Sawtooth</option>
            <option value='sine'>Sine</option>
            <option value='square'>Square</option>
            <option value='triangle'>Triangle</option>
          </select>
        </ControlContainer>
        <ControlContainer>
          Detune
          <input
            defaultValue={osc1Settings.get(this).detune}
            max='50'
            min='-50'
            onInput={e => {
              osc1Settings.set(this, {
                ...osc1Settings.get(this),
                detune: Number(e.target.value)
              })
              updateAudio.call(this)
            }}
            type='range'
          />
        </ControlContainer>

Osc 2

        <ControlContainer>
          Type
          <select
            defaultValue={osc2Settings.get(this).type}
            onChange={e => {
              osc2Settings.set(this, {
                ...osc1Settings.get(this),
                type: e.target.value
              })
              updateAudio.call(this)
            }}
          >
            <option value='sawtooth'>Sawtooth</option>
            <option value='sine'>Sine</option>
            <option value='square'>Square</option>
            <option value='triangle'>Triangle</option>
          </select>
        </ControlContainer>
        <ControlContainer>
          Detune
          <input
            defaultValue={osc2Settings.get(this).detune}
            max='50'
            min='-50'
            onInput={e => {
              osc2Settings.set(this, {
                ...osc2Settings.get(this),
                detune: Number(e.target.value)
              })
              updateAudio.call(this)
            }}
            type='range'
          />
        </ControlContainer>

,
      containerEl
    )
  }
}
<|endoftext|>


<commit_before>define(['chai', 'mocha', 'Adhocracy', 'Adhocracy/Frames/ProposalWorkbench'], function(chai, mocha, Adhocracy, ProposalWorkbench) {

    mocha.setup('bdd');

    var expect = chai.expect;

    // console.log(expect(18).to.equal(18));
    // console.log(expect(18).to.equal(19));

    describe('something pure yet lame', function() {
        it('should half its input', function() {
            expect(ProposalWorkbench.something_pure(18)).to.equal(9);
        });
    });

    return {
        run: function() {
            mocha.run();
        }
    }
});
<commit_msg>frontend: more trivial test cases.<commit_after>define(['jquery', 'chai', 'mocha', 'Adhocracy', 'Adhocracy/Frames/ProposalWorkbench'], function($, chai, mocha, Adhocracy, ProposalWorkbench) {

    mocha.setup('bdd');

    var expect = chai.expect;

    describe('something pure yet lame', function() {
        it('should half its input', function() {
            expect(ProposalWorkbench.something_pure(18)).to.equal(9);
        });
    });

    describe('some trivial DOM invariants', function() {
        it('must have three divs named appropriately', function() {
            expect($('#___probably_not_a_valid_dom_elem_id___')).to.have.length(0);
            expect($('#proposal_workbench_detail')).to.not.have.length(0);
            expect($('#proposal_workbench_directory')).to.not.have.length(0);
            expect($('#proposal_workbench_discussion')).to.not.have.length(0);
        });

        it('detail div must contain "..."', function() {
            expect($('#proposal_workbench_detail')[0].innerText).to.equal('...');
        });
    });

    return {
        run: function() {
            mocha.run();
        }
    }
});
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import t from 't-component'
import config from 'lib/config'
import userConnector from 'lib/site/connectors/user'
import CommentReplies from './replies/component'
import CommentHeader from './header/component'
import CommentFooter from './footer/component'

export class Comment extends Component {
  constructor (props) {
    super(props)
    this.state = {
      repliesVisibility: false,
      showOptionsMenu: false,
      commentDeletingPending: false,
      isSpam: false,
      overlayActive: '',
      overlayVisibility: false
    }
  }

  componentWillReceiveProps (props) {
    if (props.commentDeleting) {
      if (
        props.commentDeleting.rejected &&
        props.commentDeleting.reason.error.code === 'HAS_REPLIES' &&
        this.state.commentDeletingPending
      ) {
        this.setState({
          overlayActive: 'HAS_REPLIES_ERR',
          overlayVisibility: true
        })
      } else if (!props.commentDeleting.pending) {
        this.setState({commentDeletingPending: false})
      }
    }
  }

  componentWillMount () {
    if (this.props.comment.flags.length >= config.spamLimit) {
      this.setState({
        isSpam: true,
        overlayActive: 'IS_SPAM',
        overlayVisibility: true
      })
    }
  }

  handleUnvote = (evt) => {
    evt.currentTarget.classList.remove('active')
    this.props.onUnvote()
  }

  handleUpvote = (evt) => {
    evt.currentTarget.classList.add('active')
    this.props.onUpvote()
  }

  handleDownvote = (evt) => {
    evt.currentTarget.classList.add('active')
    this.props.onDownvote()
  }

  handleToggleReplies = () => {
    this.setState({repliesVisibility: !this.state.repliesVisibility})
  }

  handleToggleOptionsMenu = () => {
    this.setState({showOptionsMenu: !this.state.showOptionsMenu})
  }

  handleHideOverlay = () => {
    this.setState({
      overlayVisibility: false
    })
  }

  handleShowOverlay = (active) => () => {
    this.setState({
      overlayVisibility: true,
      overlayActive: active
    })
  }

  handleDelete = () => {
    this.setState({
      overlayVisibility: false,
      commentDeletingPending: true
    })
    this.props.onDelete({id: this.props.comment.id})
  }

  render () {
    const {
      comment,
      user,
      forum
    } = this.props

    if (user.state.pending) return null

    const {upvoted, downvoted} = (comment.currentUser || {})
    const userAttrs = user.state.value || {}
    const isOwner = userAttrs.id === comment.author.id

    return (
      <article className={`comments-list-item ${this.state.isSpam ? 'is-spam' : ''}`} id={`comment-${comment.id}`}>
        <CommentHeader
          comment={comment}
          isOwner={isOwner}
          onToggleOptionsMenu={this.handleToggleOptionsMenu}
          showOptionsMenu={this.state.showOptionsMenu}
          onToggleDeleteConfirmation={this.handleShowOverlay('CONFIRM_REMOVE')}
          user={user.state.value || null}
          flags={comment.flags}
          commentId={comment.id}
          onFlag={this.props.onFlag}
          onUnflag={this.props.onUnflag} />

        <CommentFooter
          score={comment.score}
          repliesCount={comment.repliesCount}
          isOwner={isOwner}
          upvoted={upvoted}
          downvoted={downvoted}
          onUnvote={this.handleUnvote}
          onUpvote={this.handleUpvote}
          onDownvote={this.handleDownvote}
          onToggleReplies={this.handleToggleReplies} />

        <CommentReplies
          commentId={comment.id}
          replies={comment.replies}
          forum={forum}
          user={user}
          repliesVisibility={this.state.repliesVisibility}
          onReply={this.props.onReply}
          onDeleteReply={this.props.onDeleteReply}
          commentsReplying={this.props.commentsReplying} />

        {
          this.state.overlayVisibility &&
          this.state.overlayActive === 'CONFIRM_REMOVE' &&
          (

{t('comments.arguments.confirm-remove')}

                <button
                  onClick={this.handleHideOverlay}
                  className='btn btn-sm btn-default'>
                  {t('common.cancel')}
                </button>
                <button
                  onClick={this.handleDelete}
                  className='btn btn-sm btn-danger'>
                  {t('common.ok')}
                </button>

          )
        }

        {
          this.state.overlayVisibility &&
          this.state.overlayActive === 'HAS_REPLIES_ERR' &&
          (

{t('comments.cannot-remove')}

                <button
                  onClick={this.handleHideOverlay}
                  className='btn btn-sm btn-default'>
                  {t('common.ok')}
                </button>

          )
        }

        {
          this.state.overlayVisibility &&
          this.state.overlayActive === 'IS_SPAM' &&
          (

{t('comment-card.flagged-as-spam')}

                <button
                  className='btn btn-sm btn-default'>
                  {t('comment-card.show')}
                </button>

          )
        }

    )
  }
}

export default userConnector(Comment)
<commit_msg>add hide comment overlay<commit_after>import React, {Component} from 'react'
import t from 't-component'
import config from 'lib/config'
import userConnector from 'lib/site/connectors/user'
import CommentReplies from './replies/component'
import CommentHeader from './header/component'
import CommentFooter from './footer/component'

export class Comment extends Component {
  constructor (props) {
    super(props)
    this.state = {
      repliesVisibility: false,
      showOptionsMenu: false,
      commentDeletingPending: false,
      isSpam: false,
      overlayActive: '',
      overlayVisibility: false
    }
  }

  componentWillReceiveProps (props) {
    if (props.commentDeleting) {
      if (
        props.commentDeleting.rejected &&
        props.commentDeleting.reason.error.code === 'HAS_REPLIES' &&
        this.state.commentDeletingPending
      ) {
        this.setState({
          overlayActive: 'HAS_REPLIES_ERR',
          overlayVisibility: true
        })
      } else if (!props.commentDeleting.pending) {
        this.setState({commentDeletingPending: false})
      }
    }
  }

  componentWillMount () {
    if (this.props.comment.flags.length >= config.spamLimit) {
      this.setState({
        isSpam: true,
        overlayActive: 'IS_SPAM',
        overlayVisibility: true
      })
    }
  }

  handleUnvote = (evt) => {
    evt.currentTarget.classList.remove('active')
    this.props.onUnvote()
  }

  handleUpvote = (evt) => {
    evt.currentTarget.classList.add('active')
    this.props.onUpvote()
  }

  handleDownvote = (evt) => {
    evt.currentTarget.classList.add('active')
    this.props.onDownvote()
  }

  handleToggleReplies = () => {
    this.setState({repliesVisibility: !this.state.repliesVisibility})
  }

  handleToggleOptionsMenu = () => {
    this.setState({showOptionsMenu: !this.state.showOptionsMenu})
  }

  handleHideOverlay = () => {
    this.setState({
      overlayVisibility: false
    })
  }

  handleShowOverlay = (active) => () => {
    this.setState({
      overlayVisibility: true,
      overlayActive: active
    })
  }

  handleDelete = () => {
    this.setState({
      overlayVisibility: false,
      commentDeletingPending: true
    })
    this.props.onDelete({id: this.props.comment.id})
  }

  render () {
    const {
      comment,
      user,
      forum
    } = this.props

    if (user.state.pending) return null

    const {upvoted, downvoted} = (comment.currentUser || {})
    const userAttrs = user.state.value || {}
    const isOwner = userAttrs.id === comment.author.id

    return (
      <article className={`comments-list-item ${this.state.isSpam ? 'is-spam' : ''}`} id={`comment-${comment.id}`}>
        <CommentHeader
          comment={comment}
          isOwner={isOwner}
          onToggleOptionsMenu={this.handleToggleOptionsMenu}
          showOptionsMenu={this.state.showOptionsMenu}
          onToggleDeleteConfirmation={this.handleShowOverlay('CONFIRM_REMOVE')}
          user={user.state.value || null}
          flags={comment.flags}
          commentId={comment.id}
          onFlag={this.props.onFlag}
          onUnflag={this.props.onUnflag} />

        <CommentFooter
          score={comment.score}
          repliesCount={comment.repliesCount}
          isOwner={isOwner}
          upvoted={upvoted}
          downvoted={downvoted}
          onUnvote={this.handleUnvote}
          onUpvote={this.handleUpvote}
          onDownvote={this.handleDownvote}
          onToggleReplies={this.handleToggleReplies} />

        <CommentReplies
          commentId={comment.id}
          replies={comment.replies}
          forum={forum}
          user={user}
          repliesVisibility={this.state.repliesVisibility}
          onReply={this.props.onReply}
          onDeleteReply={this.props.onDeleteReply}
          commentsReplying={this.props.commentsReplying} />

        {
          this.state.overlayVisibility &&
          this.state.overlayActive === 'CONFIRM_REMOVE' &&
          (

{t('comments.arguments.confirm-remove')}

                <button
                  onClick={this.handleHideOverlay}
                  className='btn btn-sm btn-default'>
                  {t('common.cancel')}
                </button>
                <button
                  onClick={this.handleDelete}
                  className='btn btn-sm btn-danger'>
                  {t('common.ok')}
                </button>

          )
        }

        {
          this.state.overlayVisibility &&
          this.state.overlayActive === 'HAS_REPLIES_ERR' &&
          (

{t('comments.cannot-remove')}

                <button
                  onClick={this.handleHideOverlay}
                  className='btn btn-sm btn-default'>
                  {t('common.ok')}
                </button>

          )
        }

        {
          this.state.overlayVisibility &&
          this.state.overlayActive === 'IS_SPAM' &&
          (

{t('comment-card.flagged-as-spam')}

                <button
                  onClick={this.handleHideOverlay}
                  className='btn btn-sm btn-default'>
                  {t('comment-card.show')}
                </button>

          )
        }

    )
  }
}

export default userConnector(Comment)
<|endoftext|>


<commit_before>var XYPoint = require('./xyPoint');

// Thanks to https://github.com/benknight/hue-python-rgb-converter/blob/master/rgb_cie.py
var ColorHelper = function() {
};

// See http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
ColorHelper.Red = new XYPoint(0.675, 0.322);
ColorHelper.Lime = new XYPoint(0.4091, 0.518);
ColorHelper.Blue = new XYPoint(0.167, 0.04);

ColorHelper.hexToRed = function(hex) {
  return parseInt(hex.slice(0, 2), 16);
};

ColorHelper.hexToGreen = function(hex) {
  return parseInt(hex.slice(2, 4), 16);
};

ColorHelper.hexToBlue = function(hex) {
  return parseInt(hex.slice(4, 6), 16);
};

ColorHelper.hexToRgb = function(hex) {
  return [this.hexToRed(hex), this.hexToGreen(hex), this.hexToBlue(hex)];
};

ColorHelper.rgbToHex = function(r, g, b) {
  return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};

ColorHelper.randomRgbValue = function() {
  return Math.floor(Math.random() * 256);
};

ColorHelper.crossProduct = function(p1, p2) {
  return p1.x * p2.y - p1.y * p2.x;
};

ColorHelper.checkPointInLampsReach = function(p) {
  var v1 = new XYPoint(this.Lime.x - this.Red.x, this.Lime.y - this.Red.y);
  var v2 = new XYPoint(this.Blue.x - this.Red.x, this.Blue.y - this.Red.y);
  var q = new XYPoint(p.x - this.Red.x, p.y - this.Red.y);
  var s = this.crossProduct(q, v2) / this.crossProduct(v1, v2);
  var t = this.crossProduct(v1, q) / this.crossProduct(v1, v2);
  return (s >= 0.0) && (t >= 0.0) && (s + t <= 1.0);
};

ColorHelper.getClosestPointToLine = function(A, B, P) {
  var AP = new XYPoint(P.x - A.x, P.y - A.y);
  var AB = new XYPoint(B.x - A.x, B.y - A.y);
  var ab2 = AB.x * AB.x + AB.y * AB.y;
  var apAb = AP.x * AB.x + AP.y * AB.y;
  var t = apAb / ab2;
  if (t < 0.0) {
    t = 0.0;
  } else if (t > 1.0) {
    t = 1.0;
  }
  return new XYPoint(A.x + AB.x * t, A.y + AB.y * t);
};

ColorHelper.getClosestPointToPoint = function(xyPoint) {
  var pAB = this.getClosestPointToLine(this.Red, this.Lime, xyPoint);
  var pAC = this.getClosestPointToLine(this.Blue, this.Red, xyPoint);
  var pBC = this.getClosestPointToLine(this.Lime, this.Blue, xyPoint);
  var dAB = this.getDistanceBetweenTwoPoints(xyPoint, pAB);
  var dAC = this.getDistanceBetweenTwoPoints(xyPoint, pAC);
  var dBC = this.getDistanceBetweenTwoPoints(xyPoint, pBC);
  var lowest = dAB;
  var closestPoint = pAB;
  if (dAC < lowest) {
    lowest = dAC;
    closestPoint = pAC;
  }
  if (dBC < lowest) {
    lowest = dBC;
    closestPoint = pBC;
  }
  return new XYPoint(closestPoint.x, closestPoint.y);
};

ColorHelper.getDistanceBetweenTwoPoints = function(one, two) {
  var dx = one.x - two.x;
  var dy = one.y - two.y;
  return Math.sqrt(dx * dx + dy * dy);
};

ColorHelper.getXYPointFromRGB = function(red, green, blue) {
  var r, g, b;
  if (red > 0.04045) {
    r = Math.pow((red + 0.055) / (1.0 + 0.055), 2.4);
  } else {
    r = (red / 12.92);
  }
  if (green > 0.04045) {
    g = Math.pow((green + 0.055) / (1.0 + 0.055), 2.4);
  } else {
    g = (green / 12.92);
  }
  if (blue > 0.04045) {
    b = Math.pow((blue + 0.055) / (1.0 + 0.055), 2.4);
  } else {
    b = (blue / 12.92);
  }

  var X = r * 0.4360747 + g * 0.3850649 + b * 0.0930804;
  var Y = r * 0.2225045 + g * 0.7168786 + b * 0.0406169;
  var Z = r * 0.0139322 + g * 0.0971045 + b * 0.7141733;

  var cx, cy;
  if (X + Y + Z === 0) {
    cx = 0;
    cy = 0;
  } else {
    cx = X / (X + Y + Z);
    cy = Y / (X + Y + Z);
  }

  var xyPoint = new XYPoint(cx, cy);
  var inReachOfLamps = this.checkPointInLampsReach(xyPoint);
  if (!inReachOfLamps) {
    xyPoint = this.getClosestPointToPoint(xyPoint);
  }
  return xyPoint;
}

module.exports = ColorHelper;
<commit_msg>Add getRGBFromXYAndBrightness<commit_after>var XYPoint = require('./xyPoint');

// Thanks to https://github.com/benknight/hue-python-rgb-converter/blob/master/rgb_cie.py
var ColorHelper = function() {
};

// See http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
ColorHelper.Red = new XYPoint(0.675, 0.322);
ColorHelper.Lime = new XYPoint(0.4091, 0.518);
ColorHelper.Blue = new XYPoint(0.167, 0.04);

ColorHelper.hexToRed = function(hex) {
  return parseInt(hex.slice(0, 2), 16);
};

ColorHelper.hexToGreen = function(hex) {
  return parseInt(hex.slice(2, 4), 16);
};

ColorHelper.hexToBlue = function(hex) {
  return parseInt(hex.slice(4, 6), 16);
};

ColorHelper.hexToRgb = function(hex) {
  return [this.hexToRed(hex), this.hexToGreen(hex), this.hexToBlue(hex)];
};

ColorHelper.rgbToHex = function(r, g, b) {
  return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};

ColorHelper.randomRgbValue = function() {
  return Math.floor(Math.random() * 256);
};

ColorHelper.crossProduct = function(p1, p2) {
  return p1.x * p2.y - p1.y * p2.x;
};

ColorHelper.checkPointInLampsReach = function(p) {
  var v1 = new XYPoint(this.Lime.x - this.Red.x, this.Lime.y - this.Red.y);
  var v2 = new XYPoint(this.Blue.x - this.Red.x, this.Blue.y - this.Red.y);
  var q = new XYPoint(p.x - this.Red.x, p.y - this.Red.y);
  var s = this.crossProduct(q, v2) / this.crossProduct(v1, v2);
  var t = this.crossProduct(v1, q) / this.crossProduct(v1, v2);
  return (s >= 0.0) && (t >= 0.0) && (s + t <= 1.0);
};

ColorHelper.getClosestPointToLine = function(A, B, P) {
  var AP = new XYPoint(P.x - A.x, P.y - A.y);
  var AB = new XYPoint(B.x - A.x, B.y - A.y);
  var ab2 = AB.x * AB.x + AB.y * AB.y;
  var apAb = AP.x * AB.x + AP.y * AB.y;
  var t = apAb / ab2;
  if (t < 0.0) {
    t = 0.0;
  } else if (t > 1.0) {
    t = 1.0;
  }
  return new XYPoint(A.x + AB.x * t, A.y + AB.y * t);
};

ColorHelper.getClosestPointToPoint = function(xyPoint) {
  var pAB = this.getClosestPointToLine(this.Red, this.Lime, xyPoint);
  var pAC = this.getClosestPointToLine(this.Blue, this.Red, xyPoint);
  var pBC = this.getClosestPointToLine(this.Lime, this.Blue, xyPoint);
  var dAB = this.getDistanceBetweenTwoPoints(xyPoint, pAB);
  var dAC = this.getDistanceBetweenTwoPoints(xyPoint, pAC);
  var dBC = this.getDistanceBetweenTwoPoints(xyPoint, pBC);
  var lowest = dAB;
  var closestPoint = pAB;
  if (dAC < lowest) {
    lowest = dAC;
    closestPoint = pAC;
  }
  if (dBC < lowest) {
    lowest = dBC;
    closestPoint = pBC;
  }
  return new XYPoint(closestPoint.x, closestPoint.y);
};

ColorHelper.getDistanceBetweenTwoPoints = function(one, two) {
  var dx = one.x - two.x;
  var dy = one.y - two.y;
  return Math.sqrt(dx * dx + dy * dy);
};

ColorHelper.getXYPointFromRGB = function(red, green, blue) {
  var r, g, b;
  if (red > 0.04045) {
    r = Math.pow((red + 0.055) / (1.0 + 0.055), 2.4);
  } else {
    r = (red / 12.92);
  }
  if (green > 0.04045) {
    g = Math.pow((green + 0.055) / (1.0 + 0.055), 2.4);
  } else {
    g = (green / 12.92);
  }
  if (blue > 0.04045) {
    b = Math.pow((blue + 0.055) / (1.0 + 0.055), 2.4);
  } else {
    b = (blue / 12.92);
  }

  var X = r * 0.4360747 + g * 0.3850649 + b * 0.0930804;
  var Y = r * 0.2225045 + g * 0.7168786 + b * 0.0406169;
  var Z = r * 0.0139322 + g * 0.0971045 + b * 0.7141733;

  var cx, cy;
  if (X + Y + Z === 0) {
    cx = 0;
    cy = 0;
  } else {
    cx = X / (X + Y + Z);
    cy = Y / (X + Y + Z);
  }

  var xyPoint = new XYPoint(cx, cy);
  var inReachOfLamps = this.checkPointInLampsReach(xyPoint);
  if (!inReachOfLamps) {
    xyPoint = this.getClosestPointToPoint(xyPoint);
  }
  return xyPoint;
}

ColorHelper.getRGBFromXYAndBrightness = function(x, y, bri) {
  if (typeof bri === 'undefined') {
    bri = 1;
  }
  var xyPoint = new XYPoint(x, y);
  if (!this.checkPointInLampsReach(xyPoint)) {
    xyPoint = this.getClosestPointToPoint(xyPoint);
  }
  var Y = bri;
  var X = (Y / xyPoint.y) * xyPoint.x;
  var Z = (Y / xyPoint.y) * (1 - xyPoint.x - xyPoint.y);
  var r =  X * 1.612 - Y * 0.203 - Z * 0.302;
  var g = -X * 0.509 + Y * 1.412 + Z * 0.066;
  var b =  X * 0.026 - Y * 0.072 + Z * 0.962;
  var reverseGammaCorrect = function(value) {
    if (value <= 0.0031308) {
      return (12.92 * value);
    }
    return ((1.0 + 0.055) * Math.pow(value, (1.0 / 2.4)) - 0.055);
  };
  r = reverseGammaCorrect(r);
  g = reverseGammaCorrect(g);
  b = reverseGammaCorrect(b);
  r = Math.max(0, r);
  g = Math.max(0, g);
  b = Math.max(0, b);
  var max_component = Math.max(r, g, b);
  if (max_component > 1) {
    r = r / max_component;
    g = g / max_component;
    b = b / max_component;
  }
  r = r * 255;
  g = g * 255;
  b = b * 255;
  return [r, g, b];
};

module.exports = ColorHelper;
<|endoftext|>