<commit_before>var React = require('react');
var classNames = require('classnames');

var SIZES = require('./SIZES');
var Button = require('./Button');
var Input = require('./Input');
var isServerSide = require('./isServerSide');

/**
 * Interractive select for forms
 *
 * It renders as a normal select on server and has a custom UI on browser (with search, images support).
 *
 * <Select name="test">
 *     <Select.Option key="en">English</Select.Option>
 *     <Select.Option key="fr">French</Select.Option>
 * </Select>
 */
var Select = React.createClass({
    propTypes: {
        // Current value of the select
        value:       React.PropTypes.oneOfType([
            React.PropTypes.string,
            React.PropTypes.arrayOf(React.PropTypes.string)
        ]).isRequired,

        // Optional callback when value changed
        onChange:  React.PropTypes.func,

        // Name when using server posting
        name:      React.PropTypes.string,

        // Text to display when no value is set
        placeholder:       React.PropTypes.string,

        // Delimiter for multiple values
        delimiter: React.PropTypes.string,

        // Prevent selection
        disabled:  React.PropTypes.bool,

        // Display the search filter?
        search:    React.PropTypes.bool,

        // Accept multiple values
        multiple:  React.PropTypes.multiple,

        // Size of the select to display
        size:      React.PropTypes.oneOf(SIZES)
    },

    getDefaultProps: function() {
        return {
            disabled:  false,
            search:    true,
            delimiter: ',',
            size:      SIZES[0]
        };
    },

    getInitialState: function() {
        return {
            value:  this.props.value,
            query:  '',
            opened: false
        };
    },

    componentWillReceiveProps: function(newProps) {
        this.setState({
            value: newProps.value
        });
    },

    onChange: function(e) {
        var newValue = e.target.value;

        this.setState({
            value: newValue
        });

        if (this.props.onChange) {
            this.props.onChange(newValue);
        }
    },

    /**
     * Search query changed
     */
    onSearchChanged: function(e) {
        this.setState({
            query: e.target.value
        });
    },

    /**
     * Toggle (close/open) the select
     */
    onToggle: function() {
        this.setState({
            opened: !this.state.opened
        });
    },

    /**
     * Toggle (close/open) the select
     */
    onToggleOption: function(value, e) {
        if (e) {
            e.preventDefault();
        }

        var acceptMultiple = this.props.multiple;
        var currentValue   = this.state.value;

        if (acceptMultiple) {
            this.setState({
                value: currentValue.concat([value])
            });
        } else {
            this.setState({
                value: value
            });
        }
    },

    /**
     * Get current value as a string
     * @return {String}
     */
    getStringValue: function() {
        var value = this.state.value;

        if (!this.props.multiple) {
            return value;
        } else {
            return value.join(this.props.delimiter);
        }
    },

    /**
     * Check if a value is selected
     * @param {String} value
     * @return {Boolean}
     */
    hasValue: function(value) {
        var currentValue = this.state.value;

        if (!this.props.multiple) {
            return (currentValue === value);
        } else {
            return (currentValue.indexOf(value) >= 0);
        }
    },

    /**
     * Focus the search input
     */
    focusSearch: function() {
        var input = this.refs.searchInput;
        if (!input) {
            return;
        }

        input.focus();
    },

    /**
     * Render button to open select
     */
    renderButton: function() {
        var disabled = this.props.disabled;
        var opened = this.state.opened;

        return (
            <Button size={this.props.size} disabled={disabled} active={opened} onClick={this.onToggle}>

            </Button>
        );
    },

    /**
     * Render button to open select
     */
    renderSearch: function() {
        var query = this.state.query;

        return (

                <Input ref="searchInput" value={query} onChange={this.onSearchChanged} />

        );
    },

    /**
     * Render the options selector
     */
    renderOptions: function() {
        var children;
        var search = this.props.search;

        children = React.Children.map(this.props.children, function(child) {
            var childKey = child.props.key;
            var className = classNames('select-option', {
                'active': this.hasValue(childKey)
            });

            return

                {child}

;
        }, this);

        return (

                {search? this.renderSearch() : ''}

                    {children}

        );
    },

    render: function() {
        var name     = this.props.name;
        var disabled = this.props.disabled;
        var opened = this.state.opened;

        if (isServerSide) {
            return (
                <select class="form-control" name={name} disabled={disabled}>
                    {this.props.children}
                </select>
            );
        }

        return

            <input type="hidden" value={this.getStringValue()} />
            {this.renderButton()}
            {opened? this.renderOptions() : ''}

;
    }
});

var SelectOption = React.createClass({
    propTypes: {
        key: React.PropTypes.string
    },

    render: function() {
        var key = this.props.key;

        if (isServerSide) {
            return <option value={key}>
                {this.props.children}
            </option>;
        }

        return

            {this.props.children}

;
    }
});

module.exports        = Select;
module.exports.Option = SelectOption;
<commit_msg>Rendent Select properties and set multiple as propTypes.bool<commit_after>var React = require('react');
var classNames = require('classnames');

var SIZES = require('./SIZES');
var Button = require('./Button');
var Input = require('./Input');
var isServerSide = require('./isServerSide');

/**
 * Interractive select for forms
 *
 * It renders as a normal select on server and has a custom UI on browser (with search, images support).
 *
 * <Select name="test">
 *     <Select.Option key="en">English</Select.Option>
 *     <Select.Option key="fr">French</Select.Option>
 * </Select>
 */
var Select = React.createClass({
    propTypes: {
        // Current value of the select
        value:       React.PropTypes.oneOfType([
            React.PropTypes.string,
            React.PropTypes.arrayOf(React.PropTypes.string)
        ]).isRequired,

        // Optional callback when value changed
        onChange:       React.PropTypes.func,

        // Name when using server posting
        name:           React.PropTypes.string,

        // Text to display when no value is set
        placeholder:    React.PropTypes.string,

        // Delimiter for multiple values
        delimiter:      React.PropTypes.string,

        // Prevent selection
        disabled:       React.PropTypes.bool,

        // Display the search filter?
        search:         React.PropTypes.bool,

        // Accept multiple values
        multiple:       React.PropTypes.bool,

        // Size of the select to display
        size:           React.PropTypes.oneOf(SIZES)
    },

    getDefaultProps: function() {
        return {
            disabled:  false,
            search:    true,
            delimiter: ',',
            size:      SIZES[0]
        };
    },

    getInitialState: function() {
        return {
            value:  this.props.value,
            query:  '',
            opened: false
        };
    },

    componentWillReceiveProps: function(newProps) {
        this.setState({
            value: newProps.value
        });
    },

    onChange: function(e) {
        var newValue = e.target.value;

        this.setState({
            value: newValue
        });

        if (this.props.onChange) {
            this.props.onChange(newValue);
        }
    },

    /**
     * Search query changed
     */
    onSearchChanged: function(e) {
        this.setState({
            query: e.target.value
        });
    },

    /**
     * Toggle (close/open) the select
     */
    onToggle: function() {
        this.setState({
            opened: !this.state.opened
        });
    },

    /**
     * Toggle (close/open) the select
     */
    onToggleOption: function(value, e) {
        if (e) {
            e.preventDefault();
        }

        var acceptMultiple = this.props.multiple;
        var currentValue   = this.state.value;

        if (acceptMultiple) {
            this.setState({
                value: currentValue.concat([value])
            });
        } else {
            this.setState({
                value: value
            });
        }
    },

    /**
     * Get current value as a string
     * @return {String}
     */
    getStringValue: function() {
        var value = this.state.value;

        if (!this.props.multiple) {
            return value;
        } else {
            return value.join(this.props.delimiter);
        }
    },

    /**
     * Check if a value is selected
     * @param {String} value
     * @return {Boolean}
     */
    hasValue: function(value) {
        var currentValue = this.state.value;

        if (!this.props.multiple) {
            return (currentValue === value);
        } else {
            return (currentValue.indexOf(value) >= 0);
        }
    },

    /**
     * Focus the search input
     */
    focusSearch: function() {
        var input = this.refs.searchInput;
        if (!input) {
            return;
        }

        input.focus();
    },

    /**
     * Render button to open select
     */
    renderButton: function() {
        var disabled = this.props.disabled;
        var opened = this.state.opened;

        return (
            <Button size={this.props.size} disabled={disabled} active={opened} onClick={this.onToggle}>

            </Button>
        );
    },

    /**
     * Render button to open select
     */
    renderSearch: function() {
        var query = this.state.query;

        return (

                <Input ref="searchInput" value={query} onChange={this.onSearchChanged} />

        );
    },

    /**
     * Render the options selector
     */
    renderOptions: function() {
        var children;
        var search = this.props.search;

        children = React.Children.map(this.props.children, function(child) {
            var childKey = child.props.key;
            var className = classNames('select-option', {
                'active': this.hasValue(childKey)
            });

            return

                {child}

;
        }, this);

        return (

                {search? this.renderSearch() : ''}

                    {children}

        );
    },

    render: function() {
        var name     = this.props.name;
        var disabled = this.props.disabled;
        var opened = this.state.opened;

        if (isServerSide) {
            return (
                <select class="form-control" name={name} disabled={disabled}>
                    {this.props.children}
                </select>
            );
        }

        return

            <input type="hidden" value={this.getStringValue()} />
            {this.renderButton()}
            {opened? this.renderOptions() : ''}

;
    }
});

var SelectOption = React.createClass({
    propTypes: {
        key: React.PropTypes.string
    },

    render: function() {
        var key = this.props.key;

        if (isServerSide) {
            return <option value={key}>
                {this.props.children}
            </option>;
        }

        return

            {this.props.children}

;
    }
});

module.exports        = Select;
module.exports.Option = SelectOption;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import {
  Cell,
  BarChart,
  Bar,
  CartesianGrid,
  Tooltip,
  XAxis,
  YAxis
} from 'recharts';
import styles from './styles.module.css';

export class HistogramVisualization extends React.Component {

  static propTypes = {
    counts: PropTypes.array.isRequired,
    fields: PropTypes.array.isRequired,
    height: PropTypes.number,
    width: PropTypes.number,
    onClick: PropTypes.func,
    filters: PropTypes.array
  }

  shouldComponentUpdate(nextProps) {
    return (nextProps.counts !== this.props.counts || nextProps.fields !== this.props.fields);
  }

  render() {
    const bars = this.props.fields.map((fieldName) => {
      return (
        <Bar
            key={fieldName}
            dataKey={fieldName}
            fill="#8884d8"
            onClick={(bar) => {
              this.props.onClick(bar.name);
            }}>
          {
            this.props.counts.map((entry) => {
              return (
                <Cell
                    key={entry.name}
                    fill={this.props.filters.includes(entry.name) ? '#4203c5' : '#8884d8'} />
              );
            })
          }

        </Bar>
      );
    });
    const width = this.props.width || 600;
    const height = this.props.height || 300;

    return (

          <BarChart
              width={width}
              height={height}
              data={this.props.counts}
              margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="name" />
            <YAxis />
            <Tooltip cursor={{ strokeDasharray: '3 3' }} />
            {bars}
          </BarChart>

    );
  }
}

export default HistogramVisualization;
<commit_msg>normal histogram default props<commit_after>import React, { PropTypes } from 'react';
import {
  Cell,
  BarChart,
  Bar,
  CartesianGrid,
  Tooltip,
  XAxis,
  YAxis
} from 'recharts';
import styles from './styles.module.css';

export class HistogramVisualization extends React.Component {

  static propTypes = {
    counts: PropTypes.array.isRequired,
    fields: PropTypes.array.isRequired,
    height: PropTypes.number,
    width: PropTypes.number,
    onClick: PropTypes.func,
    filters: PropTypes.array
  }

  static defaultProps = {
    height: 300,
    width: 600,
    onClick: () => {},
    filters: []
  }

  shouldComponentUpdate(nextProps) {
    return (nextProps.counts !== this.props.counts || nextProps.fields !== this.props.fields);
  }

  render() {
    const bars = this.props.fields.map((fieldName) => {
      return (
        <Bar
            key={fieldName}
            dataKey={fieldName}
            fill="#8884d8"
            onClick={(bar) => {
              this.props.onClick(bar.name);
            }}>
          {
            this.props.counts.map((entry) => {
              return (
                <Cell
                    key={entry.name}
                    fill={this.props.filters.includes(entry.name) ? '#4203c5' : '#8884d8'} />
              );
            })
          }

        </Bar>
      );
    });

    return (

          <BarChart
              width={this.props.width}
              height={this.props.height}
              data={this.props.counts}
              margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="name" />
            <YAxis />
            <Tooltip cursor={{ strokeDasharray: '3 3' }} />
            {bars}
          </BarChart>

    );
  }
}

export default HistogramVisualization;
<|endoftext|>


<commit_before>var util = require('util');
var events = require('events');

var formatRegExp = /%[sdj%]/g;

/*!
 * Base class for waitForElement commands. It provides a command
 * command method and element* methods to be overwritten by subclasses
 *
 * @constructor
 */
function WaitForElement() {
  events.EventEmitter.call(this);
  this.startTimer = null;
  this.cb = null;
  this.ms = null;
  this.element = null;
  this.abortOnFailure = true;
  this.selector = null;
  this.locateStrategy = this.client.locateStrategy || 'css selector';
  this.rescheduleInterval = 500; //ms
  this.protocol = require('../protocol.js')(this.client);
}

util.inherits(WaitForElement, events.EventEmitter);

/*!
 * The public command function which will be called by the test runner. Arguments can be passed in a variety of ways:
 *
 *  waitForElement('body')
 *  waitForElement('body', 500)
 *  waitForElement('body', 500, 'test message)
 *  waitForElement('body', 500, function() { .. });
 *  waitForElement('body', 500, true);
 *  waitForElement('body', 500, true, 'test message');
 *  waitForElement('body', 500, true, function() { .. });
 *  waitForElement('body', 500, true, function() { .. }, 'test message');
 *
 * @param {string} selector
 * @param {number} milliseconds
 * @param {function|boolean|string} callbackOrAbort
 * @returns {WaitForElement}
 */
WaitForElement.prototype.command = function(selector, milliseconds, callbackOrAbort) {
  assertMilliseconds.call(this, milliseconds)

  this.startTimer = new Date().getTime();

  if (typeof arguments[2] === 'boolean') {
    this.abortOnFailure = arguments[2];
    this.cb = arguments[3] || function() {};
  } else if (typeof arguments[2] === 'number') {
    this.rescheduleInterval = arguments[2];
    if (typeof arguments[3] === 'boolean') {
      this.abortOnFailure = arguments[3];
      this.cb = arguments[4] || function() {};
    } else {
      this.cb = arguments[3] || function() {};
    }
  } else {
    this.cb = (typeof callbackOrAbort === 'function' && callbackOrAbort) || function() {};
  }

  // support for a custom message
  this.message = null;
  var lastArgument = arguments[arguments.length - 1];
  if (typeof lastArgument === 'string') {
    this.message = lastArgument;
  }

  this.ms = milliseconds || this.client.api.globals.waitForConditionTimeout;
  this.selector = selector;
  this.checkElement();
  return this;
};

/*!
 * @override
 */
WaitForElement.prototype.elementFound = function(result, now) {};

/*!
 * @override
 */
WaitForElement.prototype.elementNotFound = function(result, now) {};

/*!
 * @override
 */
WaitForElement.prototype.elementVisible = function(result, now) {};

/*!
 * @override
 */
WaitForElement.prototype.elementNotVisible = function(result, now) {};

/*!
 * Reschedule the checkElement
 */
WaitForElement.prototype.reschedule = function(method) {
  var self = this;
  method = method || 'checkElement';

  setTimeout(function() {
    self[method]();
  }, this.rescheduleInterval);
};

WaitForElement.prototype.complete = function() {
  var args = Array.prototype.slice.call(arguments, 0);
  args.push(this);
  this.cb.apply(this.client.api, args);
  this.emit('complete');
  return this;
};

WaitForElement.prototype.pass = function(result, defaultMsg, timeMs) {
  this.message = this.formatMessage(defaultMsg, timeMs);
  this.client.assertion(true, null, null, this.message, this.abortOnFailure);
  return this.complete(result);
};

WaitForElement.prototype.fail = function(result, actual, expected, defaultMsg) {
  this.message = this.formatMessage(defaultMsg);
  this.client.assertion(false, actual, expected, this.message, this.abortOnFailure);
  return this.complete(result);
};

/*!
 * Will start checking if the element exists and if not re-schedule the check
 * until the timeout expires or the condition has been met
 */
WaitForElement.prototype.checkElement = function() {
  var self = this;
  this.protocol.element(this.locateStrategy, this.selector, function(result) {
    var now = new Date().getTime();
    if (result.status === 0) {
      self.element = result.value.ELEMENT;
      return self.elementFound(result, now);
    }

    return self.elementNotFound(result, now);
  });
};

/*!
 * Will start checking if the element is visible and if not re-schedule the check
 * until the timeout expires or the condition has been met
 */
WaitForElement.prototype.isVisible = function() {
  var self = this;
  this.protocol.elementIdDisplayed(this.element, function(result) {
    var now = new Date().getTime();
    if (result.status === 0 && result.value === true) {
      // element was visible
      return self.elementVisible(result, now);
    }

    return self.elementNotVisible(result, now);
  });
};

/**
 * @param {string} defaultMsg
 * @param {number} [timeMs]
 * @returns {string}
 */
WaitForElement.prototype.formatMessage = function (defaultMsg, timeMs) {
  return format(this.message || defaultMsg, this.selector, timeMs || this.ms);
};

/**
 * A smaller version of util.format that doesn't support json and
 * if a placeholder is missing, it is omitted instead of appended
 *
 * @param f
 * @returns {string}
 */
function format(f) {
  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') {
      return '%';
    }
    if (i >= len) {
      return x;
    }
    switch (x) {
    case '%s':
      return String(args[i++]);
    case '%d':
      return Number(args[i++]);
    default:
      return x;
    }
  });

  return str;
}

/**
 * @param {number} [timeoutMs]
 * @throws Will throw an error if the argument is invalid
 * @returns {number}
 */
function assertMilliseconds(timeoutMs) {
  var globalTimeout = this.client.api.globals.waitForConditionTimeout;

  if (!timeoutMs && typeof globalTimeout !== 'number') {
    throw new Error('waitForElement expects second parameter to have a global default ' +
      '(waitForConditionTimeout) to be specified if not passed as the second parameter ');
  }
  else if (timeoutMs && typeof timeoutMs !== 'number') {
    throw new Error('waitForElement expects second parameter to be number; ' +
      typeof (timeoutMs) + ' given');
  }
}

module.exports = WaitForElement;<commit_msg>add missing semicolon<commit_after>var util = require('util');
var events = require('events');

var formatRegExp = /%[sdj%]/g;

/*!
 * Base class for waitForElement commands. It provides a command
 * command method and element* methods to be overwritten by subclasses
 *
 * @constructor
 */
function WaitForElement() {
  events.EventEmitter.call(this);
  this.startTimer = null;
  this.cb = null;
  this.ms = null;
  this.element = null;
  this.abortOnFailure = true;
  this.selector = null;
  this.locateStrategy = this.client.locateStrategy || 'css selector';
  this.rescheduleInterval = 500; //ms
  this.protocol = require('../protocol.js')(this.client);
}

util.inherits(WaitForElement, events.EventEmitter);

/*!
 * The public command function which will be called by the test runner. Arguments can be passed in a variety of ways:
 *
 *  waitForElement('body')
 *  waitForElement('body', 500)
 *  waitForElement('body', 500, 'test message)
 *  waitForElement('body', 500, function() { .. });
 *  waitForElement('body', 500, true);
 *  waitForElement('body', 500, true, 'test message');
 *  waitForElement('body', 500, true, function() { .. });
 *  waitForElement('body', 500, true, function() { .. }, 'test message');
 *
 * @param {string} selector
 * @param {number} milliseconds
 * @param {function|boolean|string} callbackOrAbort
 * @returns {WaitForElement}
 */
WaitForElement.prototype.command = function(selector, milliseconds, callbackOrAbort) {
  assertMilliseconds.call(this, milliseconds);

  this.startTimer = new Date().getTime();

  if (typeof arguments[2] === 'boolean') {
    this.abortOnFailure = arguments[2];
    this.cb = arguments[3] || function() {};
  } else if (typeof arguments[2] === 'number') {
    this.rescheduleInterval = arguments[2];
    if (typeof arguments[3] === 'boolean') {
      this.abortOnFailure = arguments[3];
      this.cb = arguments[4] || function() {};
    } else {
      this.cb = arguments[3] || function() {};
    }
  } else {
    this.cb = (typeof callbackOrAbort === 'function' && callbackOrAbort) || function() {};
  }

  // support for a custom message
  this.message = null;
  var lastArgument = arguments[arguments.length - 1];
  if (typeof lastArgument === 'string') {
    this.message = lastArgument;
  }

  this.ms = milliseconds || this.client.api.globals.waitForConditionTimeout;
  this.selector = selector;
  this.checkElement();
  return this;
};

/*!
 * @override
 */
WaitForElement.prototype.elementFound = function(result, now) {};

/*!
 * @override
 */
WaitForElement.prototype.elementNotFound = function(result, now) {};

/*!
 * @override
 */
WaitForElement.prototype.elementVisible = function(result, now) {};

/*!
 * @override
 */
WaitForElement.prototype.elementNotVisible = function(result, now) {};

/*!
 * Reschedule the checkElement
 */
WaitForElement.prototype.reschedule = function(method) {
  var self = this;
  method = method || 'checkElement';

  setTimeout(function() {
    self[method]();
  }, this.rescheduleInterval);
};

WaitForElement.prototype.complete = function() {
  var args = Array.prototype.slice.call(arguments, 0);
  args.push(this);
  this.cb.apply(this.client.api, args);
  this.emit('complete');
  return this;
};

WaitForElement.prototype.pass = function(result, defaultMsg, timeMs) {
  this.message = this.formatMessage(defaultMsg, timeMs);
  this.client.assertion(true, null, null, this.message, this.abortOnFailure);
  return this.complete(result);
};

WaitForElement.prototype.fail = function(result, actual, expected, defaultMsg) {
  this.message = this.formatMessage(defaultMsg);
  this.client.assertion(false, actual, expected, this.message, this.abortOnFailure);
  return this.complete(result);
};

/*!
 * Will start checking if the element exists and if not re-schedule the check
 * until the timeout expires or the condition has been met
 */
WaitForElement.prototype.checkElement = function() {
  var self = this;
  this.protocol.element(this.locateStrategy, this.selector, function(result) {
    var now = new Date().getTime();
    if (result.status === 0) {
      self.element = result.value.ELEMENT;
      return self.elementFound(result, now);
    }

    return self.elementNotFound(result, now);
  });
};

/*!
 * Will start checking if the element is visible and if not re-schedule the check
 * until the timeout expires or the condition has been met
 */
WaitForElement.prototype.isVisible = function() {
  var self = this;
  this.protocol.elementIdDisplayed(this.element, function(result) {
    var now = new Date().getTime();
    if (result.status === 0 && result.value === true) {
      // element was visible
      return self.elementVisible(result, now);
    }

    return self.elementNotVisible(result, now);
  });
};

/**
 * @param {string} defaultMsg
 * @param {number} [timeMs]
 * @returns {string}
 */
WaitForElement.prototype.formatMessage = function (defaultMsg, timeMs) {
  return format(this.message || defaultMsg, this.selector, timeMs || this.ms);
};

/**
 * A smaller version of util.format that doesn't support json and
 * if a placeholder is missing, it is omitted instead of appended
 *
 * @param f
 * @returns {string}
 */
function format(f) {
  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') {
      return '%';
    }
    if (i >= len) {
      return x;
    }
    switch (x) {
    case '%s':
      return String(args[i++]);
    case '%d':
      return Number(args[i++]);
    default:
      return x;
    }
  });

  return str;
}

/**
 * @param {number} [timeoutMs]
 * @throws Will throw an error if the argument is invalid
 * @returns {number}
 */
function assertMilliseconds(timeoutMs) {
  var globalTimeout = this.client.api.globals.waitForConditionTimeout;

  if (!timeoutMs && typeof globalTimeout !== 'number') {
    throw new Error('waitForElement expects second parameter to have a global default ' +
      '(waitForConditionTimeout) to be specified if not passed as the second parameter ');
  }
  else if (timeoutMs && typeof timeoutMs !== 'number') {
    throw new Error('waitForElement expects second parameter to be number; ' +
      typeof (timeoutMs) + ' given');
  }
}

module.exports = WaitForElement;<|endoftext|>


<commit_before>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

//note: returns array of numbers.
function splitInHalf(x)
{
	var result = [];
	result.push( new number( x.positive,  x.value.substr(0, Math.ceil( x.value.length / 2 )) ));
	result.push( new number( x.positive,  x.value.substr( Math.ceil( x.value.length / 2 ), x.value.length -  Math.ceil(x.value.length / 2)) ));

	return result;
}

function getChars(x, char)
{
	var n = x;
	result = "";
	while(n > 0){
		result += char;
		n--;
	}
	return result;
}

//note: this needs to be more accurate for x >> y and x << y, or will cause rounding errors.
function longMultiply(x, y)
{
	var positive = x.positive == y.positive;
	return new number(positive , parseInt(x.value) * parseInt(y.value) );
}

number.prototype.timesTenToThe = function(x)
{
	var tempThis = new number(this.positive, this.value);
	tempThis.value += getChars(x, "0");
	return tempThis;
}

function karatsuba(x, y)
{
	x_length = x.value.length;
	y_length = y.value.length;

	if(x_length == 1 || y_length == 1)
	{
		return longMultiply(x, y);
	}

	var deg = Math.floor(x_length / 2);

	var xSplit = splitInHalf(x);
	var ySplit = splitInHalf(y);

	var a = karatsuba(xSplit[0], ySplit[0]);
	var a_powed = a.timesTenToThe(2 * deg);
	var c = karatsuba(xSplit[1], ySplit[1]);

	var x_sum = xSplit[0].plus(xSplit[1]);
	var y_sum = ySplit[0].plus(ySplit[1]);

	var b = karatsuba(x_sum, y_sum);

	var b_minus_a = b.minus(a);
	var b_minus_a_minus_c = b_minus_a.minus(c);
	var b_powed = b_minus_a_minus_c.timesTenToThe(deg);

	return a_powed.plus(c).plus(b_powed);
}

<commit_msg>Update number.js<commit_after>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

//note: returns array of numbers.
function splitInHalf(x)
{
	var result = [];
	result.push( new number( x.positive,  x.value.substr(0, Math.ceil( x.value.length / 2 )) ));
	result.push( new number( x.positive,  x.value.substr( Math.ceil( x.value.length / 2 ), x.value.length -  Math.ceil(x.value.length / 2)) ));

	return result;
}

function getChars(x, char)
{
	var n = x;
	result = "";
	while(n > 0){
		result += char;
		n--;
	}
	return result;
}

//note: this needs to be more accurate for x >> y and x << y, or will cause rounding errors.
function longMultiply(x, y)
{
	var positive = x.positive == y.positive;
	return new number(positive , parseInt(x.value) * parseInt(y.value) );
}

number.prototype.timesTenToThe = function(x)
{
	var tempThis = new number(this.positive, this.value);
	tempThis.value += getChars(x, "0");
	return tempThis;
}

function karatsuba(x, y)
{
	x_length = x.value.length;
	y_length = y.value.length;

	if(x_length == 1 || y_length == 1)
	{
		return longMultiply(x, y);
	}

	var deg = Math.floor(x_length / 2);

	var xSplit = splitInHalf(x);
	var ySplit = splitInHalf(y);

	var a = karatsuba(xSplit[0], ySplit[0]);
	var a_powed = a.timesTenToThe(2 * deg);
	var c = karatsuba(xSplit[1], ySplit[1]);

	var x_sum = xSplit[0].plus(xSplit[1]);
	var y_sum = ySplit[0].plus(ySplit[1]);

	var b = karatsuba(x_sum, y_sum).minus(a).minus(c).timesTenToThe(deg);

	return a_powed.plus(c).plus(b);
}

<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');

var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);

var _baobabPropTypes = require('baobab-prop-types');

var _baobabPropTypes2 = _interopRequireDefault(_baobabPropTypes);

var _baobabReactMixins = require('baobab-react-mixins');

var _mixins = require('../mixins');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _react2.default.createClass({
    displayName: 'Input',

    mixins: [_baobabReactMixins.BranchMixin, _mixins.FormComponentMixin, _mixins.ComponentActionsMixin, _reactAddonsPureRenderMixin2.default],

    propTypes: {
        cursor: _baobabPropTypes2.default.cursor,
        onChange: _react2.default.PropTypes.func,
        onKeyPress: _react2.default.PropTypes.func,
        onSync: _react2.default.PropTypes.func,
        onBlur: _react2.default.PropTypes.func,
        sync: _react2.default.PropTypes.bool,
        syncOnlyOnBlur: _react2.default.PropTypes.bool,
        nullable: _react2.default.PropTypes.bool,
        autoFocus: _react2.default.PropTypes.bool,
        toInternal: _react2.default.PropTypes.func,
        toRepresentation: _react2.default.PropTypes.func
    },

    deferredSyncTimer: null,

    msToPoll: 200,

    cursors: function cursors(props, context) {
        return {
            cursorValue: this.getCursor(props, context)
        };
    },
    getInitialState: function getInitialState() {
        return {
            value: this.props.toInternal(this.getCursor().get()) || ''
        };
    },
    getDefaultProps: function getDefaultProps() {
        return {
            type: 'text',
            nullable: false,
            toInternal: _lodash2.default.identity,
            toRepresentation: _lodash2.default.identity,
            onBlur: _lodash2.default.identity,
            onChange: _lodash2.default.identity,
            onSync: _lodash2.default.identity,
            onKeyPress: _lodash2.default.identity,
            sync: false
        };
    },
    componentDidUpdate: function componentDidUpdate(prevProps, prevState, prevContext) {
        if (this.deferredSyncTimer) {
            // Does not set state when component received props while user inputs
            return;
        }

        if (this.state.cursorValue !== prevState.cursorValue) {
            this.setState({
                value: this.props.toInternal(this.state.cursorValue) || ''
            });
        }
    },
    componentDidMount: function componentDidMount() {
        var _this = this;

        if (this.props.autoFocus) {
            setTimeout(function () {
                var element = _reactDom2.default.findDOMNode(_this.refs.input);

                if (element) {
                    element.focus();
                }
            }, 0);
        }
    },
    componentWillUnmount: function componentWillUnmount() {
        this.clearDeferredSyncTimer();
    },
    clearDeferredSyncTimer: function clearDeferredSyncTimer() {
        if (this.deferredSyncTimer) {
            clearTimeout(this.deferredSyncTimer);
            this.deferredSyncTimer = null;
        }
    },
    deferredSyncValue: function deferredSyncValue(eventCallback) {
        var _this2 = this;

        this.clearDeferredSyncTimer();
        this.deferredSyncTimer = setTimeout(function () {
            return _this2.syncValue(eventCallback);
        }, this.msToPoll);
    },
    syncValue: function syncValue(eventCallback) {
        var _this3 = this;

        // Synchronizes value with cursor
        var value = this.props.nullable && this.state.value === '' ? null : this.state.value;
        var previousValue = this.state.cursorValue;

        if (value === previousValue) {
            if (_lodash2.default.isFunction(eventCallback)) {
                eventCallback();
            }

            return;
        }

        this.setValue(value, function () {
            _this3.setDirtyState();
            _this3.props.onSync(value, previousValue);

            if (_lodash2.default.isFunction(eventCallback)) {
                eventCallback();
            }
        });
    },
    updateValue: function updateValue(value) {
        var forceSync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
        var eventCallback = arguments[2];

        // Synchronizes value with state
        this.setState({ value: value }, function () {
            if (this.props.sync || forceSync) {
                this.syncValue(eventCallback);
                return;
            }

            if (!this.props.syncOnlyOnBlur) {
                this.deferredSyncValue(eventCallback);
            }
        });
    },
    onChange: function onChange(event) {
        var value = this.props.toInternal(event.target.value);
        var previousValue = this.state.value;

        if (value === previousValue) {
            return;
        }

        this.updateValue(value);
        this.props.onChange(event, { value: value, previousValue: previousValue });
    },
    onBlur: function onBlur(event) {
        var _this4 = this;

        var value = this.props.toInternal(event.target.value);

        // Prevent future updates
        this.clearDeferredSyncTimer();

        // Set inner state value and force synchronization
        this.updateValue(value, true, function () {
            return _this4.props.onBlur(event);
        });
    },
    onKeyPress: function onKeyPress(event) {
        var _this5 = this;

        this.processKeyPress(event, function () {
            _this5.clearDeferredSyncTimer();
            _this5.syncValue(function () {
                return _this5.context.form && _this5.context.form.submit();
            });
        });
    },
    render: function render() {
        var props = {
            value: this.props.toRepresentation(this.state.value),
            onChange: this.onChange,
            onBlur: this.onBlur
        };

        var restProps = _lodash2.default.omit(this.props, ['cursor', 'onChange', 'onKeyPress', 'onSync', 'onBlur', 'sync', 'syncOnlyOnBlur', 'autoFocus', 'toInternal', 'toRepresentation', 'nullable']);

        if (this.props.type == 'textarea') {
            return _react2.default.createElement('textarea', _extends({}, restProps, props, { ref: 'input' }));
        }

        return _react2.default.createElement('input', _extends({}, restProps, props, {
            type: this.props.type,
            onKeyPress: this.onKeyPress,
            ref: 'input' }));
    }
});<commit_msg>Build<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');

var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);

var _baobabPropTypes = require('baobab-prop-types');

var _baobabPropTypes2 = _interopRequireDefault(_baobabPropTypes);

var _baobabReactMixins = require('baobab-react-mixins');

var _mixins = require('../mixins');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _react2.default.createClass({
    displayName: 'Input',

    mixins: [_baobabReactMixins.BranchMixin, _mixins.FormComponentMixin, _mixins.ComponentActionsMixin, _reactAddonsPureRenderMixin2.default],

    propTypes: {
        cursor: _baobabPropTypes2.default.cursor,
        onChange: _react2.default.PropTypes.func,
        onKeyPress: _react2.default.PropTypes.func,
        onSync: _react2.default.PropTypes.func,
        onBlur: _react2.default.PropTypes.func,
        sync: _react2.default.PropTypes.bool,
        syncOnlyOnBlur: _react2.default.PropTypes.bool,
        nullable: _react2.default.PropTypes.bool,
        autoFocus: _react2.default.PropTypes.bool,
        toInternal: _react2.default.PropTypes.func,
        toRepresentation: _react2.default.PropTypes.func
    },

    deferredSyncTimer: null,

    msToPoll: 200,

    cursors: function cursors(props, context) {
        return {
            cursorValue: this.getCursor(props, context)
        };
    },
    getInitialState: function getInitialState() {
        return {
            value: this.props.toInternal(this.getCursor().get()) || ''
        };
    },
    getDefaultProps: function getDefaultProps() {
        return {
            type: 'text',
            nullable: false,
            toInternal: _lodash2.default.identity,
            toRepresentation: _lodash2.default.identity,
            onBlur: _lodash2.default.identity,
            onChange: _lodash2.default.identity,
            onSync: _lodash2.default.identity,
            onKeyPress: _lodash2.default.identity,
            sync: false
        };
    },
    componentDidUpdate: function componentDidUpdate(prevProps, prevState, prevContext) {
        if (this.deferredSyncTimer) {
            // Does not set state when component received props while user inputs
            return;
        }

        if (this.state.cursorValue !== prevState.cursorValue) {
            this.setState({
                value: this.props.toInternal(this.state.cursorValue) || ''
            });
        }
    },
    componentDidMount: function componentDidMount() {
        var _this = this;

        if (this.props.autoFocus) {
            setTimeout(function () {
                var element = _reactDom2.default.findDOMNode(_this.refs.input);

                if (element) {
                    element.focus();
                }
            }, 0);
        }
    },
    componentWillUnmount: function componentWillUnmount() {
        this.clearDeferredSyncTimer();
    },
    clearDeferredSyncTimer: function clearDeferredSyncTimer() {
        if (this.deferredSyncTimer) {
            clearTimeout(this.deferredSyncTimer);
            this.deferredSyncTimer = null;
        }
    },
    deferredSyncValue: function deferredSyncValue(eventCallback) {
        var _this2 = this;

        this.clearDeferredSyncTimer();
        this.deferredSyncTimer = setTimeout(function () {
            _this2.deferredSyncTimer = null;
            _this2.syncValue(eventCallback);
        }, this.msToPoll);
    },
    syncValue: function syncValue(eventCallback) {
        var _this3 = this;

        // Synchronizes value with cursor
        var value = this.props.nullable && this.state.value === '' ? null : this.state.value;
        var previousValue = this.state.cursorValue;

        if (value === previousValue) {
            if (_lodash2.default.isFunction(eventCallback)) {
                eventCallback();
            }

            return;
        }

        this.setValue(value, function () {
            _this3.setDirtyState();
            _this3.props.onSync(value, previousValue);

            if (_lodash2.default.isFunction(eventCallback)) {
                eventCallback();
            }
        });
    },
    updateValue: function updateValue(value) {
        var forceSync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
        var eventCallback = arguments[2];

        // Synchronizes value with state
        this.setState({ value: value }, function () {
            if (this.props.sync || forceSync) {
                this.syncValue(eventCallback);
                return;
            }

            if (!this.props.syncOnlyOnBlur) {
                this.deferredSyncValue(eventCallback);
            }
        });
    },
    onChange: function onChange(event) {
        var value = this.props.toInternal(event.target.value);
        var previousValue = this.state.value;

        if (value === previousValue) {
            return;
        }

        this.updateValue(value);
        this.props.onChange(event, { value: value, previousValue: previousValue });
    },
    onBlur: function onBlur(event) {
        var _this4 = this;

        var value = this.props.toInternal(event.target.value);

        // Prevent future updates
        this.clearDeferredSyncTimer();

        // Set inner state value and force synchronization
        this.updateValue(value, true, function () {
            return _this4.props.onBlur(event);
        });
    },
    onKeyPress: function onKeyPress(event) {
        var _this5 = this;

        this.processKeyPress(event, function () {
            _this5.clearDeferredSyncTimer();
            _this5.syncValue(function () {
                return _this5.context.form && _this5.context.form.submit();
            });
        });
    },
    render: function render() {
        var props = {
            value: this.props.toRepresentation(this.state.value),
            onChange: this.onChange,
            onBlur: this.onBlur
        };

        var restProps = _lodash2.default.omit(this.props, ['cursor', 'onChange', 'onKeyPress', 'onSync', 'onBlur', 'sync', 'syncOnlyOnBlur', 'autoFocus', 'toInternal', 'toRepresentation', 'nullable']);

        if (this.props.type == 'textarea') {
            return _react2.default.createElement('textarea', _extends({}, restProps, props, { ref: 'input' }));
        }

        return _react2.default.createElement('input', _extends({}, restProps, props, {
            type: this.props.type,
            onKeyPress: this.onKeyPress,
            ref: 'input' }));
    }
});<|endoftext|>


<commit_before>module.exports = {

	// http://fiidmi.fi/documentation/restaurant_list
	'list': {
		"type": "object",
		"properties": {
			"session_id":      { "type": "string", "minLength": 2, "maxLength": 50 },
			"address":         { "type": "string", "minLength": 1, "maxLength": 150 },
			"postal_code":     { "type": "string", "minLength": 1, "maxLength": 5 },
			"city":            { "type": "string", "minLength": 1, "maxLength": 100 },
			"radius":          { "type": "string", "minLength": 1, "maxLength": 50 },
			"chain_id":        { "type": "string", "minLength": 1, "maxLength": 50 },
			"sort_by":         { "type": "string", "minLength": 1, "maxLength": 50 },
			"latitude":        { "type": "string", "pattern": "^[0-9]{2}\.[0-9]{6}$" },
			"longitude":       { "type": "string", "pattern": "^[0-9]{2}\.[0-9]{6}$" }
		},
		"required": ["session_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_get
	'get': {
		"type": "object",
		"properties": {
			"session_id":      { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_timetable
	'timetable': {
		"type": "object",
		"properties": {
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_timetable
	'rate': {
		"type": "object",
		"properties": {
			"user_id":            { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 },
			"review":             { "type": "string", "minLength": 2, "maxLength": 200 },
			"portion_size":       { "type": "string", "minLength": 2, "maxLength": 200 },
			"portion_quality":    { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_menu":    { "type": "string", "minLength": 2, "maxLength": 200 },
			"qpr":                { "type": "string", "minLength": 2, "maxLength": 200 },
			"enjoyment":          { "type": "string", "minLength": 2, "maxLength": 200 },
			"service":            { "type": "string", "minLength": 2, "maxLength": 200 },
			"location":           { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id", "user_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_rating
	'rating': {
		"type": "object",
		"properties": {
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_chains
	'chains': {
		"type": "object",
		"properties": {
		},
		"required": []
	},

	// http://fiidmi.fi/documentation/restaurant_make_order
	'make_order': {
		"type": "object",
		"properties": {
			"session_id":                      { "type": "string", "minLength": 2, "maxLength": 200 },
			"user_id":                         { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_id":                   { "type": "string", "minLength": 2, "maxLength": 200 },
			"validate_against_restaurant_id":  { "type": "string", "minLength": 2, "maxLength": 200 },
			"forename":                        { "type": "string", "minLength": 2, "maxLength": 200 },
			"surname":                         { "type": "string", "minLength": 2, "maxLength": 200 },
			"email":                           { "type": "string", "minLength": 2, "maxLength": 200 },
			"phone_number":                    { "type": "string", "minLength": 2, "maxLength": 200 },
			"products": {
				"type": "array",
				"items": {
					"type": "object",
					"properties": {
						"product_id":          { "type": "string", "minLength": 2, "maxLength": 200 },
						"variant_id":          { "type": "string", "minLength": 2, "maxLength": 200 },
						"price":               { "type": "string", "minLength": 2, "maxLength": 200 },
						"side_dish":           { "type": "string", "minLength": 2, "maxLength": 200 },
						"changed_ingredients": { "type": "string", "minLength": 2, "maxLength": 200 },
						"added_ingredients":   { "type": "string", "minLength": 2, "maxLength": 200 },
						"extras":              { "type": "string", "minLength": 2, "maxLength": 200 }
					}
				}
			},
			"delivery_address": {
				"type": "object",
				"oneOf": [
					{ "type": "string", "minLength": 2, "maxLength": 200 },
					{
						"type": "object",
						"properties": {
							"address":     { "type": "string", "minLength": 2, "maxLength": 200 },
							"city":        { "type": "string", "minLength": 2, "maxLength": 200 },
							"postal_code": { "type": "string", "minLength": 2, "maxLength": 200 }
						}
					}
				]
			},
			"delivery_method":                 { "type": "string", "minLength": 2, "maxLength": 200 },
			"additional_info":                 { "type": "string", "minLength": 2, "maxLength": 200 },
			"delivery_price":                  { "type": "string", "minLength": 2, "maxLength": 200 },
			"total_price":                     { "type": "string", "minLength": 2, "maxLength": 200 },
			"alternative_delivery_time":       { "type": "string", "minLength": 2, "maxLength": 200 },
			"small_order_additional_fee":      { "type": "string", "minLength": 2, "maxLength": 200 },
			"payment_data": {
				"type": "object",
				"properties": {
					"method":              { "type": "string", "minLength": 2, "maxLength": 200 },
					"used_bonus":          { "type": "string", "minLength": 2, "maxLength": 200 },
					"used_po_credit":      { "type": "string", "minLength": 2, "maxLength": 200 },
					"redirect_to":         { "type": "string", "minLength": 2, "maxLength": 150 }
				},
				"required": ["method"]
			}
		},
		"required": ["session_id", "restaurant_id", "products", "delivery_address", "delivery_method", "delivery_price", "total_price", "payment_data"]
	},

	// http://fiidmi.fi/documentation/restaurant_timetable
	'order_status': {
		"type": "object",
		"properties": {
			"order_id":        { "type": "string", "minLength": 2, "maxLength": 200 },
			"session_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		}
	}

};
<commit_msg>Removed session_id from restaurantList()<commit_after>module.exports = {

	// http://fiidmi.fi/documentation/restaurant_list
	'list': {
		"type": "object",
		"properties": {
			"session_id":      { "type": "string", "minLength": 2, "maxLength": 50 },
			"address":         { "type": "string", "minLength": 1, "maxLength": 150 },
			"postal_code":     { "type": "string", "minLength": 1, "maxLength": 5 },
			"city":            { "type": "string", "minLength": 1, "maxLength": 100 },
			"radius":          { "type": "string", "minLength": 1, "maxLength": 50 },
			"chain_id":        { "type": "string", "minLength": 1, "maxLength": 50 },
			"sort_by":         { "type": "string", "minLength": 1, "maxLength": 50 },
			"latitude":        { "type": "string", "pattern": "^[0-9]{2}\.[0-9]{6}$" },
			"longitude":       { "type": "string", "pattern": "^[0-9]{2}\.[0-9]{6}$" }
		}
		//"required": ["session_id"] // Docs say it's required but other sites can call without it...
	},

	// http://fiidmi.fi/documentation/restaurant_get
	'get': {
		"type": "object",
		"properties": {
			"session_id":      { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_timetable
	'timetable': {
		"type": "object",
		"properties": {
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_timetable
	'rate': {
		"type": "object",
		"properties": {
			"user_id":            { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 },
			"review":             { "type": "string", "minLength": 2, "maxLength": 200 },
			"portion_size":       { "type": "string", "minLength": 2, "maxLength": 200 },
			"portion_quality":    { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_menu":    { "type": "string", "minLength": 2, "maxLength": 200 },
			"qpr":                { "type": "string", "minLength": 2, "maxLength": 200 },
			"enjoyment":          { "type": "string", "minLength": 2, "maxLength": 200 },
			"service":            { "type": "string", "minLength": 2, "maxLength": 200 },
			"location":           { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id", "user_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_rating
	'rating': {
		"type": "object",
		"properties": {
			"restaurant_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		},
		"required": ["restaurant_id"]
	},

	// http://fiidmi.fi/documentation/restaurant_chains
	'chains': {
		"type": "object",
		"properties": {
		},
		"required": []
	},

	// http://fiidmi.fi/documentation/restaurant_make_order
	'make_order': {
		"type": "object",
		"properties": {
			"session_id":                      { "type": "string", "minLength": 2, "maxLength": 200 },
			"user_id":                         { "type": "string", "minLength": 2, "maxLength": 200 },
			"restaurant_id":                   { "type": "string", "minLength": 2, "maxLength": 200 },
			"validate_against_restaurant_id":  { "type": "string", "minLength": 2, "maxLength": 200 },
			"forename":                        { "type": "string", "minLength": 2, "maxLength": 200 },
			"surname":                         { "type": "string", "minLength": 2, "maxLength": 200 },
			"email":                           { "type": "string", "minLength": 2, "maxLength": 200 },
			"phone_number":                    { "type": "string", "minLength": 2, "maxLength": 200 },
			"products": {
				"type": "array",
				"items": {
					"type": "object",
					"properties": {
						"product_id":          { "type": "string", "minLength": 2, "maxLength": 200 },
						"variant_id":          { "type": "string", "minLength": 2, "maxLength": 200 },
						"price":               { "type": "string", "minLength": 2, "maxLength": 200 },
						"side_dish":           { "type": "string", "minLength": 2, "maxLength": 200 },
						"changed_ingredients": { "type": "string", "minLength": 2, "maxLength": 200 },
						"added_ingredients":   { "type": "string", "minLength": 2, "maxLength": 200 },
						"extras":              { "type": "string", "minLength": 2, "maxLength": 200 }
					}
				}
			},
			"delivery_address": {
				"type": "object",
				"oneOf": [
					{ "type": "string", "minLength": 2, "maxLength": 200 },
					{
						"type": "object",
						"properties": {
							"address":     { "type": "string", "minLength": 2, "maxLength": 200 },
							"city":        { "type": "string", "minLength": 2, "maxLength": 200 },
							"postal_code": { "type": "string", "minLength": 2, "maxLength": 200 }
						}
					}
				]
			},
			"delivery_method":                 { "type": "string", "minLength": 2, "maxLength": 200 },
			"additional_info":                 { "type": "string", "minLength": 2, "maxLength": 200 },
			"delivery_price":                  { "type": "string", "minLength": 2, "maxLength": 200 },
			"total_price":                     { "type": "string", "minLength": 2, "maxLength": 200 },
			"alternative_delivery_time":       { "type": "string", "minLength": 2, "maxLength": 200 },
			"small_order_additional_fee":      { "type": "string", "minLength": 2, "maxLength": 200 },
			"payment_data": {
				"type": "object",
				"properties": {
					"method":              { "type": "string", "minLength": 2, "maxLength": 200 },
					"used_bonus":          { "type": "string", "minLength": 2, "maxLength": 200 },
					"used_po_credit":      { "type": "string", "minLength": 2, "maxLength": 200 },
					"redirect_to":         { "type": "string", "minLength": 2, "maxLength": 150 }
				},
				"required": ["method"]
			}
		},
		"required": ["session_id", "restaurant_id", "products", "delivery_address", "delivery_method", "delivery_price", "total_price", "payment_data"]
	},

	// http://fiidmi.fi/documentation/restaurant_timetable
	'order_status': {
		"type": "object",
		"properties": {
			"order_id":        { "type": "string", "minLength": 2, "maxLength": 200 },
			"session_id":      { "type": "string", "minLength": 2, "maxLength": 200 }
		}
	}

};
<|endoftext|>


<commit_before>// fatcontroller - simple pub-sub
// https://github.com/markfinger/fatcontroller

(function(root, factory) {

  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(factory);
  } else {
    // Browser globals
    root.fc = factory();
  }

}(this, function fatcontroller() {

  // Registry of subscribers
  var registry = {
    // event: [
    //   {
    //     callback: ...,
    //     context: ...
    //   },
    //   ...
    // ],
  };

  var on = function on(event, callback, context) {

    var binding = {
      callback: callback,
      context: context
    };

    if (registry[event] === undefined) {
      registry[event] = [];
    }
    registry[event].push(binding);

    return binding;
  };

  var off = function off(event, callback, context) {

    if (event && !callback && !context) {

      delete registry[event];

    } else if (callback || context) {

      var subscribers;

      if (event) {
        subscribers = {};
        subscribers[event] = registry[event]
      } else {
        subscribers = registry;
      }

      for (var key in subscribers) {

        if (subscribers.hasOwnProperty(key)) {

          var bindings = subscribers[key];

          for (var i = 0; i < bindings.length; i++) {

            var binding = bindings[i];

            var matchingCallback = callback && binding.callback === callback;
            var matchingContext = context && binding.callback === callback;

            if (
              (matchingCallback && matchingContext) ||
              (!callback && matchingContext) ||
              (!context && matchingCallback)
            ) {
              bindings.splice(i, 1);
            }
          }

          if (binding.length === 0) {
            delete subscribers[key];
          }

        }

      }

    }

  };

  var trigger = function trigger(event) {

    var args = Array.prototype.slice.call(arguments, 1);

    var subscribers = registry[event];

    if (subscribers !== undefined) {

      for (var i = 0; i < subscribers.length; i++) {

        var binding = subscribers[i];

        if (binding.context !== undefined) {
          binding.callback.call(binding.context, args);
        } else {
          binding.callback(args);
        }

      }

    }

    return event;
  };

  return {
    on: on,
    off: off,
    trigger: trigger,
    registry: registry
  };

}));<commit_msg>Added `fc.once` method.<commit_after>// fatcontroller - simple pub-sub
// https://github.com/markfinger/fatcontroller

(function(root, factory) {

  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(factory);
  } else {
    // Browser globals
    root.fc = factory();
  }

}(this, function() {

  // Registry of subscribers
  var registry = {
    // event: [
    //   {
    //     callback: ...,
    //     context: ...,
    //     once: ...
    //   },
    //   ...
    // ],
  };

  var on = function on(event, callback, context) {
    var binding = {
      callback: callback,
      context: context,
      once: false
    };
    if (registry[event] === undefined) {
      registry[event] = [];
    }
    registry[event].push(binding);
    return binding;
  };

  var once = function once() {
    var binding = on.apply(this, arguments);
    binding.once = true;
    return binding;
  };

  var off = function off(event) {
    var callback = undefined;
    var context = undefined;
    if (typeof event === 'object') {
      event = obj.event;
      callback = obj.callback;
      context = obj.context;
    }

    if (event && !callback && !context) {
      delete registry[event];
    } else if (callback || context) {
      var subscribers;
      if (event) {
        subscribers = {};
        subscribers[event] = registry[event]
      } else {
        subscribers = registry;
      }
      for (var key in subscribers) {
        if (subscribers.hasOwnProperty(key)) {
          var bindings = subscribers[key];
          for (var i = 0; i < bindings.length; i++) {
            var binding = bindings[i];
            var matchingCallback = callback && binding.callback === callback;
            var matchingContext = context && binding.callback === callback;
            if (
              (matchingCallback && matchingContext) ||
                (!callback && matchingContext) ||
                (!context && matchingCallback)
              ) {
              bindings.splice(i, 1);
            }
          }
          if (binding.length === 0) {
            delete subscribers[key];
          }
        }
      }
    }
  };

  var trigger = function trigger(event) {
    var args = Array.prototype.slice.call(arguments, 1);
    var subscribers = registry[event];
    if (subscribers !== undefined) {
      for (var i = 0; i < subscribers.length; i++) {
        var binding = subscribers[i];
        if (binding.context !== undefined) {
          binding.callback.call(binding.context, args);
        } else {
          binding.callback(args);
        }
        if (binding.once) {
          subscribers.splice(i, 1);
        }
        if (subscribers.length === 0) {
          delete registry[event];
        }
      }
    }
    return event;
  };

  return {
    on: on,
    once: once,
    off: off,
    trigger: trigger,
    registry: registry
  };

}));<|endoftext|>


<commit_before>/*
var ball;

function setup() {
  createCanvas(1024, 600);
  ball = new Ball(60);
}

function draw() {
  background(255,0,0, 50);
  ball.update();
  ball.render();
}
*/

var n = 1000;
var minRad = 10;
var maxRad = 570;
var nfAng;//0.005;
var nfTime = 0.002;
var fillColor = 255;
var acc = 0.07;

function setup() {
    createCanvas(1024, 1024);
    background(0);
    noFill();

    nfAng = createSlider(5,100,1);
}

function draw()
{
  stroke(fillColor, 25);
  translate(width/2, height/2);
  rotate(radians(frameCount/frameRate));
  beginShape();
  for (var i=0; i<n; i++) {
    var ang = map(i, 0, n, 0, 6.283);
    var rad = map(noise(i*(nfAng.value() / 100), frameCount*nfTime), 0, 1, minRad, maxRad);
    var x = rad * cos(ang);
    var y = rad * sin(ang);
    curveVertex(x, y);
  }
  endShape(CLOSE);
  //nfAng+=0.000001;
    if (fillColor > 0) {
        fillColor -= acc;
        acc *= 1.0009;
    } else {
        console.log("Finished");
        noLoop();
    }
}
<commit_msg>Update sketch.js<commit_after>/*
var ball;

function setup() {
  createCanvas(1024, 600);
  ball = new Ball(60);
}

function draw() {
  background(255,0,0, 50);
  ball.update();
  ball.render();
}
*/

var n = 1000;
var minRad = 10;
var maxRad = 570;
var nfAng;//0.005;
var nfTime = 0.002;
var fillColor = 255;
var acc = 0.07;

function setup() {
    createCanvas(1024, 1024);
    background(0);
    noFill();

    nfAng = createSlider(5,100,1);
}

function draw()
{
  stroke(fillColor, 25);
  translate(width/2, height/2);
  rotate(radians(frameCount/frameRate));
  beginShape();
  for (var i=0; i<n; i++) {
    var ang = map(i, 0, n, 0, 6.283);
    var rad = map(noise(i*(nfAng.value() / 1000), frameCount*nfTime), 0, 1, minRad, maxRad);
    var x = rad * cos(ang);
    var y = rad * sin(ang);
    curveVertex(x, y);
  }
  endShape(CLOSE);
  //nfAng+=0.000001;
    if (fillColor > 0) {
        fillColor -= acc;
        acc *= 1.0009;
    } else {
        console.log("Finished");
        noLoop();
    }
}
<|endoftext|>


<commit_before>var vows = require('vows'),
    assert = require('assert'),
    jsdom = require('jsdom');

/*
 * Don't require d3 in a var declaration so the name is available to
 * d3-transform. This makes it global, which should probably be avoided but
 * ???
 */
d3 = require('d3');
var transform = require("../src/d3-transform.js");

vows.describe('d3-transform').addBatch({
  'the initial object' : {
    topic : function() {
      return d3.svg.transform();
    },
    'is an identity transform' : function(topic) {
      assert.equal(topic(), "");
    }
  },
  'calling translate' : {
    'works for one argument' : function() {
      var transform = d3.svg.transform()
          .translate(1);

      assert.equal(transform(), 'translate(1)');
    },
    'works for two arguments' : function() {
      var transform = d3.svg.transform()
          .translate(1, 2);

      assert.equal(transform(), 'translate(1,2)');
    },
    'works for a function argument' : function() {
      var transform = d3.svg.transform()
          .translate(function() { return [3, 5]; });

      assert.equal(transform(), 'translate(3,5)');
    },
    'works for a function argument, given arguments' : function() {
      var transform = d3.svg.transform()
          .translate(function(x) { return [x, 13]; });

      assert.equal(transform(8), 'translate(8,13)');
    }
  },
  'composing transforms' : {
    'works' : function() {
      var transform = d3.svg.transform()
          .translate(1, 1)
          .rotate(2);
      assert.equal(transform(), 'translate(1,1) rotate(2)');
    }
  }
}).export(module);
<commit_msg>Add test for function argument as method call<commit_after>var vows = require('vows'),
    assert = require('assert'),
    jsdom = require('jsdom');

/*
 * Don't require d3 in a var declaration so the name is available to
 * d3-transform. This makes it global, which should probably be avoided but
 * ???
 */
d3 = require('d3');
var transform = require("../src/d3-transform.js");

vows.describe('d3-transform').addBatch({
  'the initial object' : {
    topic : function() {
      return d3.svg.transform();
    },
    'is an identity transform' : function(topic) {
      assert.equal(topic(), "");
    }
  },
  'calling translate' : {
    'works for one argument' : function() {
      var transform = d3.svg.transform()
          .translate(1);

      assert.equal(transform(), 'translate(1)');
    },
    'works for two arguments' : function() {
      var transform = d3.svg.transform()
          .translate(1, 2);

      assert.equal(transform(), 'translate(1,2)');
    },
    'works for a function argument' : function() {
      var transform = d3.svg.transform()
          .translate(function() { return [3, 5]; });

      assert.equal(transform(), 'translate(3,5)');
    },
    'works for a function argument, given arguments' : function() {
      var transform = d3.svg.transform()
          .translate(function(x) { return [x, 13]; });

      assert.equal(transform(8), 'translate(8,13)');
    },
    'works for a function argument, as a method' : function() {
      var transform = d3.svg.transform()
          .translate(function() { return [this.x, 34]; });
      var cxt = { 'x' : 21 };

      assert.equal(transform.call(cxt), 'translate(21,34)');
    }
  },
  'composing transforms' : {
    'works' : function() {
      var transform = d3.svg.transform()
          .translate(1, 1)
          .rotate(2);
      assert.equal(transform(), 'translate(1,1) rotate(2)');
    }
  }
}).export(module);
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { withRouter } from 'react-router-dom';

import { withStyles } from "@material-ui/core/styles";
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from "@material-ui/core/FormGroup";
import Checkbox from '@material-ui/core/Checkbox';
import TextField from "@material-ui/core/TextField";
import CardContent from "@material-ui/core/CardContent";

import TitleBar from "../../components/TitleBar";
import TitleBarTitle from "../../components/TitleBarTitle";
import AutocompleteSelect from "../../components/AutocompleteSelect";
import FormComponent from "../../classes/FormComponent";
import Form from "../../components/Form";
import UserStore from "../../stores/UserStore";
import OrganizationStore from "../../stores/OrganizationStore";
import SessionStore from "../../stores/SessionStore";
import theme from "../../theme";

const styles = {
  card: {
    overflow: "visible",
  },
  tabs: {
    borderBottom: "1px solid " + theme.palette.divider,
    height: "48px",
    overflow: "visible",
  },
  formLabel: {
    fontSize: 12,
  },
};

class AssignUserForm extends FormComponent {
  constructor() {
    super();

    this.getUserOptions = this.getUserOptions.bind(this);
  }

  getUserOptions(search, callbackFunc) {
    UserStore.list(search, 10, 0, resp => {
      const options = resp.result.map((u, i) => {return {label: u.username, value: u.id}});
      callbackFunc(options);
    });
  }

  render() {
    if (this.state.object === undefined) {
      return(

);
    }

    return(
      <Form
        submitLabel="Add user"
        onSubmit={this.onSubmit}
      >
        <FormControl margin="normal" fullWidth>
          <FormLabel className={this.props.classes.formLabel} required>Username</FormLabel>
          <AutocompleteSelect
            id="userID"
            label="Select username"
            value={this.state.object.userID || null}
            onChange={this.onChange}
            getOptions={this.getUserOptions}
          />
        </FormControl>
        <FormGroup>
          <FormControlLabel
            label="Is organization admin"
            control={
              <Checkbox
                id="isAdmin"
                checked={!!this.state.object.isAdmin}
                onChange={this.onChange}
                color="primary"
              />
            }
          />
        </FormGroup>
      </Form>
    );
  };
}

AssignUserForm = withStyles(styles)(AssignUserForm);

class CreateUserForm extends FormComponent {
  render() {
    if (this.state.object === undefined) {
      return(

);
    }

    return(
      <Form
        submitLabel="Create user"
        onSubmit={this.onSubmit}
      >
        <TextField
          id="username"
          label="Username"
          margin="normal"
          value={this.state.object.username || ""}
          onChange={this.onChange}
          required
          fullWidth
        />
        <TextField
          id="email"
          label="E-mail address"
          margin="normal"
          value={this.state.object.email || ""}
          onChange={this.onChange}
          required
          fullWidth
        />
        <TextField
          id="note"
          label="Optional note"
          helperText="Optional note, e.g. a phone number, address, comment..."
          margin="normal"
          value={this.state.object.note || ""}
          onChange={this.onChange}
          rows={4}
          fullWidth
          multiline
        />
        <TextField
          id="password"
          label="Password"
          type="password"
          margin="normal"
          value={this.state.object.password || ""}
          onChange={this.onChange}
          required
          fullWidth
        />
        <FormGroup>
          <FormControlLabel
            label="Is organization admin"
            control={
              <Checkbox
                id="isAdmin"
                checked={!!this.state.object.isAdmin}
                onChange={this.onChange}
                color="primary"
              />
            }
          />
        </FormGroup>
      </Form>
    );
  }
}

class CreateOrganizationUser extends Component {
  constructor() {
    super();

    this.state = {
      tab: 0,
      assignUser: false,
    };

    this.onChangeTab = this.onChangeTab.bind(this);
    this.onAssignUser = this.onAssignUser.bind(this);
    this.onCreateUser = this.onCreateUser.bind(this);
    this.setAssignUser = this.setAssignUser.bind(this);
  }

  componentDidMount() {
    this.setAssignUser();

    SessionStore.on("change", this.setAssignUser);
  }

  comomentWillUnmount() {
    SessionStore.removeListener("change", this.setAssignUser);
  }

  setAssignUser() {
    const settings = SessionStore.getSettings();
    this.setState({
      assignUser: !settings.disableAssignExistingUsers || SessionStore.isAdmin(),
    });
  }

  onChangeTab(e, v) {
    this.setState({
      tab: v,
    });
  }

  onAssignUser(user) {
    OrganizationStore.addUser(this.props.match.params.organizationID, user, resp => {
      this.props.history.push(`/organizations/${this.props.match.params.organizationID}/users`);
    });
  };

  onCreateUser(user) {
    const orgs = [
      {isAdmin: user.isAdmin, organizationID: this.props.match.params.organizationID},
    ];

    let u = user;
    u.isAdmin = false;
    u.isActive = true;

    UserStore.create(u, user.password, orgs, resp => {
      this.props.history.push(`/organizations/${this.props.match.params.organizationID}/users`);
    });
  };

  render() {
    return(
      <Grid container spacing={4}>
        <TitleBar>
          <TitleBarTitle title="Organization users" to={`/organizations/${this.props.match.params.organizationID}/users`} />
          <TitleBarTitle title="/" />
          <TitleBarTitle title="Create" />
        </TitleBar>

        <Grid item xs={12}>
          <Tabs value={this.state.tab} onChange={this.onChangeTab} indicatorColor="primary" fullWidth className={this.props.classes.tabs}>
            {this.state.assignUser && <Tab label="Assign existing user" />}
            <Tab label="Create and assign user" />
          </Tabs>
        </Grid>

        <Grid item xs={12}>
          <Card className={this.props.classes.card}>
            <CardContent>
              {(this.state.tab === 0 && this.state.assignUser) && <AssignUserForm onSubmit={this.onAssignUser} />}
              {(this.state.tab === 1 || !this.state.assignUser) && <CreateUserForm onSubmit={this.onCreateUser} />}
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    );
  }
}

export default withStyles(styles)(withRouter(CreateOrganizationUser));
<commit_msg>ui: fix fullWidth argument warning.<commit_after>import React, { Component } from "react";
import { withRouter } from 'react-router-dom';

import { withStyles } from "@material-ui/core/styles";
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from "@material-ui/core/FormGroup";
import Checkbox from '@material-ui/core/Checkbox';
import TextField from "@material-ui/core/TextField";
import CardContent from "@material-ui/core/CardContent";

import TitleBar from "../../components/TitleBar";
import TitleBarTitle from "../../components/TitleBarTitle";
import AutocompleteSelect from "../../components/AutocompleteSelect";
import FormComponent from "../../classes/FormComponent";
import Form from "../../components/Form";
import UserStore from "../../stores/UserStore";
import OrganizationStore from "../../stores/OrganizationStore";
import SessionStore from "../../stores/SessionStore";
import theme from "../../theme";

const styles = {
  card: {
    overflow: "visible",
  },
  tabs: {
    borderBottom: "1px solid " + theme.palette.divider,
    height: "48px",
    overflow: "visible",
  },
  formLabel: {
    fontSize: 12,
  },
};

class AssignUserForm extends FormComponent {
  constructor() {
    super();

    this.getUserOptions = this.getUserOptions.bind(this);
  }

  getUserOptions(search, callbackFunc) {
    UserStore.list(search, 10, 0, resp => {
      const options = resp.result.map((u, i) => {return {label: u.username, value: u.id}});
      callbackFunc(options);
    });
  }

  render() {
    if (this.state.object === undefined) {
      return(

);
    }

    return(
      <Form
        submitLabel="Add user"
        onSubmit={this.onSubmit}
      >
        <FormControl margin="normal" fullWidth>
          <FormLabel className={this.props.classes.formLabel} required>Username</FormLabel>
          <AutocompleteSelect
            id="userID"
            label="Select username"
            value={this.state.object.userID || null}
            onChange={this.onChange}
            getOptions={this.getUserOptions}
          />
        </FormControl>
        <FormGroup>
          <FormControlLabel
            label="Is organization admin"
            control={
              <Checkbox
                id="isAdmin"
                checked={!!this.state.object.isAdmin}
                onChange={this.onChange}
                color="primary"
              />
            }
          />
        </FormGroup>
      </Form>
    );
  };
}

AssignUserForm = withStyles(styles)(AssignUserForm);

class CreateUserForm extends FormComponent {
  render() {
    if (this.state.object === undefined) {
      return(

);
    }

    return(
      <Form
        submitLabel="Create user"
        onSubmit={this.onSubmit}
      >
        <TextField
          id="username"
          label="Username"
          margin="normal"
          value={this.state.object.username || ""}
          onChange={this.onChange}
          required
          fullWidth
        />
        <TextField
          id="email"
          label="E-mail address"
          margin="normal"
          value={this.state.object.email || ""}
          onChange={this.onChange}
          required
          fullWidth
        />
        <TextField
          id="note"
          label="Optional note"
          helperText="Optional note, e.g. a phone number, address, comment..."
          margin="normal"
          value={this.state.object.note || ""}
          onChange={this.onChange}
          rows={4}
          fullWidth
          multiline
        />
        <TextField
          id="password"
          label="Password"
          type="password"
          margin="normal"
          value={this.state.object.password || ""}
          onChange={this.onChange}
          required
          fullWidth
        />
        <FormGroup>
          <FormControlLabel
            label="Is organization admin"
            control={
              <Checkbox
                id="isAdmin"
                checked={!!this.state.object.isAdmin}
                onChange={this.onChange}
                color="primary"
              />
            }
          />
        </FormGroup>
      </Form>
    );
  }
}

class CreateOrganizationUser extends Component {
  constructor() {
    super();

    this.state = {
      tab: 0,
      assignUser: false,
    };

    this.onChangeTab = this.onChangeTab.bind(this);
    this.onAssignUser = this.onAssignUser.bind(this);
    this.onCreateUser = this.onCreateUser.bind(this);
    this.setAssignUser = this.setAssignUser.bind(this);
  }

  componentDidMount() {
    this.setAssignUser();

    SessionStore.on("change", this.setAssignUser);
  }

  comomentWillUnmount() {
    SessionStore.removeListener("change", this.setAssignUser);
  }

  setAssignUser() {
    const settings = SessionStore.getSettings();
    this.setState({
      assignUser: !settings.disableAssignExistingUsers || SessionStore.isAdmin(),
    });
  }

  onChangeTab(e, v) {
    this.setState({
      tab: v,
    });
  }

  onAssignUser(user) {
    OrganizationStore.addUser(this.props.match.params.organizationID, user, resp => {
      this.props.history.push(`/organizations/${this.props.match.params.organizationID}/users`);
    });
  };

  onCreateUser(user) {
    const orgs = [
      {isAdmin: user.isAdmin, organizationID: this.props.match.params.organizationID},
    ];

    let u = user;
    u.isAdmin = false;
    u.isActive = true;

    UserStore.create(u, user.password, orgs, resp => {
      this.props.history.push(`/organizations/${this.props.match.params.organizationID}/users`);
    });
  };

  render() {
    return(
      <Grid container spacing={4}>
        <TitleBar>
          <TitleBarTitle title="Organization users" to={`/organizations/${this.props.match.params.organizationID}/users`} />
          <TitleBarTitle title="/" />
          <TitleBarTitle title="Create" />
        </TitleBar>

        <Grid item xs={12}>
          <Tabs value={this.state.tab} onChange={this.onChangeTab} indicatorColor="primary" className={this.props.classes.tabs}>
            {this.state.assignUser && <Tab label="Assign existing user" />}
            <Tab label="Create and assign user" />
          </Tabs>
        </Grid>

        <Grid item xs={12}>
          <Card className={this.props.classes.card}>
            <CardContent>
              {(this.state.tab === 0 && this.state.assignUser) && <AssignUserForm onSubmit={this.onAssignUser} />}
              {(this.state.tab === 1 || !this.state.assignUser) && <CreateUserForm onSubmit={this.onCreateUser} />}
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    );
  }
}

export default withStyles(styles)(withRouter(CreateOrganizationUser));
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name SegmentPoint
 * @class An internal version of Point that notifies its segment of each change
 * Note: This prototype is not exported.
 *
 * @private
 */
var SegmentPoint = Point.extend({
	set: function(x, y) {
		this._x = x;
		this._y = y;
		this._owner._changed(this);
		return this;
	},

	getX: function() {
		return this._x;
	},

	setX: function(x) {
		this._x = x;
		this._owner._changed(this);
	},

	getY: function() {
		return this._y;
	},

	setY: function(y) {
		this._y = y;
		this._owner._changed(this);
	},

	setSelected: function(selected) {
		this._owner._setSelected(this, selected);
	},

	isSelected: function() {
		return this._owner._isSelected(this);
	},

	statics: {
		create: function(segment, key, pt) {
			var point = new SegmentPoint(SegmentPoint.dont),
				x, y, selected;
			if (!pt) {
				x = y = 0;
			} else if (pt.x !== undefined) {
				x = pt.x;
				y = pt.y;
				selected = pt.selected;
			} else {
				x = pt[0];
				y = pt[1];
			}
			point._x = x;
			point._y = y;
			point._owner = segment;
			// We need to set the point on the segment before copying over the
			// selected state, as otherwise this won't actually select it.
			segment[key] = point;
			if (selected)
				point.setSelected(true);
			return point;
		}
	}
});
<commit_msg>Fix problem with passing a Size to the Segment constructor.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name SegmentPoint
 * @class An internal version of Point that notifies its segment of each change
 * Note: This prototype is not exported.
 *
 * @private
 */
var SegmentPoint = Point.extend({
	set: function(x, y) {
		this._x = x;
		this._y = y;
		this._owner._changed(this);
		return this;
	},

	getX: function() {
		return this._x;
	},

	setX: function(x) {
		this._x = x;
		this._owner._changed(this);
	},

	getY: function() {
		return this._y;
	},

	setY: function(y) {
		this._y = y;
		this._owner._changed(this);
	},

	setSelected: function(selected) {
		this._owner._setSelected(this, selected);
	},

	isSelected: function() {
		return this._owner._isSelected(this);
	},

	statics: {
		create: function(segment, key, pt) {
			var point = new SegmentPoint(SegmentPoint.dont),
				x, y, selected;
			if (!pt) {
				x = y = 0;
			} else if (pt.x !== undefined) {
				x = pt.x;
				y = pt.y;
				selected = pt.selected;
			} else if (pt.width !== undefined) {
				x = pt.width;
				y = pt.height;
			} else {
				x = pt[0];
				y = pt[1];
			}
			point._x = x;
			point._y = y;
			point._owner = segment;
			// We need to set the point on the segment before copying over the
			// selected state, as otherwise this won't actually select it.
			segment[key] = point;
			if (selected)
				point.setSelected(true);
			return point;
		}
	}
});
<|endoftext|>