<commit_before>const _ = require('lodash');
const async = require('async');
const utils = require('../utils');

const Stop = require('../../models/Stop');
const StopTime = require('../../models/StopTime');
const Trip = require('../../models/Trip');

/*
 * Returns an array of stops for the `agency_key` specified, optionally
 * limited to the `stop_ids` specified
 */
exports.getStops = (agency_key, stop_ids, cb) => {
  if (_.isFunction(stop_ids)) {
    cb = stop_ids;
    stop_ids = undefined;
  }

  const query = {
    agency_key
  };

  if (stop_ids !== undefined) {
    if (!_.isArray(stop_ids)) {
      stop_ids = [stop_ids];
    }

    query.stop_id = {
      $in: stop_ids
    };
  }

  return Stop.find(query).exec(cb);
};

/*
 * Returns an array of stops for the `agency_key` specified, optionally
 * limited to the `stop_code` specified
 */
exports.getStopsByStopCode = (agency_key, stop_code, cb) => {
  if (_.isFunction(stop_code)) {
    cb = stop_code;
    stop_code = undefined;
  }

  const query = {
    agency_key
  }

  if (stop_code !== undefined) {
    if (!_.isArray(stop_code)) {
      stop_code = [stop_code];
    }

    query.stop_code = {
      stop_code : stop_code
    };
  }

  return Stop.find(query).exec(cb);
};

/*
 * Returns an array of stops along the `route_id` for the `agency_key` and `direction_id` specified
 */
exports.getStopsByRoute = (agency_key, route_id, direction_id, cb) => {
  if (_.isFunction(direction_id)) {
    cb = direction_id;
    direction_id = undefined;
  }

  const longestTrip = {};
  const stops = {};
  const trip_ids = {};

  async.series([
    getTrips,
    getStopTimes,
    getStops
  ], (err) => {
    if (err) return cb(err);

    // transform results based on whether direction_id was
    // - specified (return stops for a direction)
    // - or not specified (return stops for all directions)
    let results;
    if (direction_id !== undefined) {
      results = stops[direction_id] || [];
    } else {
      results = _.map(stops, (stops, direction_id) => {
        return {
          direction_id,
          stops: stops || []
        };
      });
    }
    cb(null, results);
  });

  function getTrips(cb) {
    const query = {
      agency_key,
      route_id
    };
    if (direction_id !== undefined) {
      query.direction_id = direction_id;
    } // else match all direction_ids

    Trip.find(query).exec()
    .then((trips) => {
      trips.forEach((trip) => {
        if (!trip_ids[trip.direction_id]) {
          trip_ids[trip.direction_id] = [];
        }
        trip_ids[trip.direction_id].push(trip.trip_id);
      });
      cb();
    }, cb);
  }

  function getStopTimes(cb) {
    const direction_ids = _.keys(trip_ids);
    async.forEach(direction_ids, (direction_id, cb) => {
      if (!trip_ids[direction_id]) {
        return cb();
      }

      async.forEach(trip_ids[direction_id], (trip_id, cb) => {
        StopTime.find({
          agency_key,
          trip_id
        },
        null, {
          sort: 'stop_sequence'
        },
        (err, stopTimes) => {
          if (err) return cb(err);

          if (!stopTimes || !stopTimes.length) {
            return cb();
          }

          // compare to longest trip for given direction_id to see if trip length is longest for given direction
          if (!longestTrip[direction_id]) {
            longestTrip[direction_id] = [];
          }
          if (stopTimes.length > longestTrip[direction_id].length) {
            longestTrip[direction_id] = stopTimes;
          }
          cb();
        });
      }, cb);
    }, cb);
  }

  function getStops(cb) {
    const direction_ids = _.keys(trip_ids);
    async.forEach(direction_ids, (direction_id, cb) => {
      if (!longestTrip[direction_id]) {
        return cb();
      }
      async.forEachSeries(longestTrip[direction_id], (stopTime, cb) => {
        Stop.findOne({
          agency_key,
          stop_id: stopTime.stop_id
        },
        (err, stop) => {
          if (err) return cb(err);

          if (!stops[direction_id]) {
            stops[direction_id] = [];
          }
          stops[direction_id].push(stop.toObject());
          cb();
        });
      }, cb);
    },
    (err) => {
      if (err) {
        return cb(new Error('No stops found'), 'stops');
      }
      cb(null, 'stops');
    });
  }
};

/*
 * Returns an array of stops within a `radius` of the `lat`, `lon` specified
 */
exports.getStopsByDistance = (lat, lon, radius, cb) => {
  if (_.isFunction(radius)) {
    cb = radius;
    radius = 1; // default is 1 mile
  }

  lat = parseFloat(lat);
  lon = parseFloat(lon);

  return Stop
    .where('loc')
    .near(lon, lat).maxDistance(utils.milesToDegrees(radius))
    .exec(cb);
};
<commit_msg>Fixed getStopsByCode failing tests<commit_after>const _ = require('lodash');
const async = require('async');
const utils = require('../utils');

const Stop = require('../../models/Stop');
const StopTime = require('../../models/StopTime');
const Trip = require('../../models/Trip');

/*
 * Returns an array of stops for the `agency_key` specified, optionally
 * limited to the `stop_ids` specified
 */
exports.getStops = (agency_key, stop_ids, cb) => {
  if (_.isFunction(stop_ids)) {
    cb = stop_ids;
    stop_ids = undefined;
  }

  const query = {
    agency_key
  };

  if (stop_ids !== undefined) {
    if (!_.isArray(stop_ids)) {
      stop_ids = [stop_ids];
    }

    query.stop_id = {
      $in: stop_ids
    };
  }

  return Stop.find(query).exec(cb);
};

/*
 * Returns an array of stops for the `agency_key` specified, optionally
 * limited to the `stop_code` specified
 */
exports.getStopsByStopCode = (agency_key, stop_code, cb) => {
  if (_.isFunction(stop_code)) {
    cb = stop_code;
    stop_code = undefined;
  }

  const query = {
    agency_key
  }

  if (stop_code !== undefined) {
    if (!_.isArray(stop_code)) {
      stop_code = [stop_code];
    }

    query.stop_code = {
      $in : stop_code
    };
  }

  return Stop.find(query).exec(cb);
};

/*
 * Returns an array of stops along the `route_id` for the `agency_key` and `direction_id` specified
 */
exports.getStopsByRoute = (agency_key, route_id, direction_id, cb) => {
  if (_.isFunction(direction_id)) {
    cb = direction_id;
    direction_id = undefined;
  }

  const longestTrip = {};
  const stops = {};
  const trip_ids = {};

  async.series([
    getTrips,
    getStopTimes,
    getStops
  ], (err) => {
    if (err) return cb(err);

    // transform results based on whether direction_id was
    // - specified (return stops for a direction)
    // - or not specified (return stops for all directions)
    let results;
    if (direction_id !== undefined) {
      results = stops[direction_id] || [];
    } else {
      results = _.map(stops, (stops, direction_id) => {
        return {
          direction_id,
          stops: stops || []
        };
      });
    }
    cb(null, results);
  });

  function getTrips(cb) {
    const query = {
      agency_key,
      route_id
    };
    if (direction_id !== undefined) {
      query.direction_id = direction_id;
    } // else match all direction_ids

    Trip.find(query).exec()
    .then((trips) => {
      trips.forEach((trip) => {
        if (!trip_ids[trip.direction_id]) {
          trip_ids[trip.direction_id] = [];
        }
        trip_ids[trip.direction_id].push(trip.trip_id);
      });
      cb();
    }, cb);
  }

  function getStopTimes(cb) {
    const direction_ids = _.keys(trip_ids);
    async.forEach(direction_ids, (direction_id, cb) => {
      if (!trip_ids[direction_id]) {
        return cb();
      }

      async.forEach(trip_ids[direction_id], (trip_id, cb) => {
        StopTime.find({
          agency_key,
          trip_id
        },
        null, {
          sort: 'stop_sequence'
        },
        (err, stopTimes) => {
          if (err) return cb(err);

          if (!stopTimes || !stopTimes.length) {
            return cb();
          }

          // compare to longest trip for given direction_id to see if trip length is longest for given direction
          if (!longestTrip[direction_id]) {
            longestTrip[direction_id] = [];
          }
          if (stopTimes.length > longestTrip[direction_id].length) {
            longestTrip[direction_id] = stopTimes;
          }
          cb();
        });
      }, cb);
    }, cb);
  }

  function getStops(cb) {
    const direction_ids = _.keys(trip_ids);
    async.forEach(direction_ids, (direction_id, cb) => {
      if (!longestTrip[direction_id]) {
        return cb();
      }
      async.forEachSeries(longestTrip[direction_id], (stopTime, cb) => {
        Stop.findOne({
          agency_key,
          stop_id: stopTime.stop_id
        },
        (err, stop) => {
          if (err) return cb(err);

          if (!stops[direction_id]) {
            stops[direction_id] = [];
          }
          stops[direction_id].push(stop.toObject());
          cb();
        });
      }, cb);
    },
    (err) => {
      if (err) {
        return cb(new Error('No stops found'), 'stops');
      }
      cb(null, 'stops');
    });
  }
};

/*
 * Returns an array of stops within a `radius` of the `lat`, `lon` specified
 */
exports.getStopsByDistance = (lat, lon, radius, cb) => {
  if (_.isFunction(radius)) {
    cb = radius;
    radius = 1; // default is 1 mile
  }

  lat = parseFloat(lat);
  lon = parseFloat(lon);

  return Stop
    .where('loc')
    .near(lon, lat).maxDistance(utils.milesToDegrees(radius))
    .exec(cb);
};
<|endoftext|>


<commit_before>/**
 * Developed by Oleksandr Tryshchenko, 2016
 * MIT
 */
var Pianoboard = (function(){
	'use strict';

	var counter = 3;
	var octave = 1;
	// Notes with halfnotes for iterations
	var notes = [
		{
			full: 'C',
			half: 'C#'
		},
		{
			full: 'D',
			half: 'D#',
		},
		{
			full: 'E',
			half: null
		},
		{
			full: 'F',
			half: 'F#'
		},
		{
			full: 'G',
			half: 'G#'
		},
		{
			full: 'A',
			half: 'A#'
		},
		{
			full: 'B',
			half: null
		}
	];
	/**
	 * Keyboard identifier. Adds notes id, halftone data and label
	 * @param  {string} key  Object key
	 * @param  {object} keys Keys object
	 */
	var initialIteration = function(key, keys) {
		var labelElement = document.createElement('b');
		var halftone = null;
		var note = {};
		var button = keys[key];

		if (button.className == undefined && button.className !== 'key') {
			return;
		}
		// TODO: Write an ES6 iterator here
		if (counter == notes.length) {
			counter = 0;
			octave++;
		}

		note = notes[counter];

		if (note.half !== null) {
			halftone = note.half + octave;
			button.parentNode.querySelector('span').id = halftone;
		}

		labelElement.inner\Html = note.full;
		button.parentNode.appendChild(labelElement);

		button.id = note.full + octave;
		labelElement.innerHTML = note.full + octave;
		counter++;
	}

	var keys = document.querySelectorAll('.key');

	// Goes through .key elements add add notes
	for (var key in keys) {
		initialIteration(key, keys);
	}
})();<commit_msg>Keyboard fix<commit_after>/**
 * Developed by Oleksandr Tryshchenko, 2016
 * MIT
 */
var Pianoboard = (function(){
	'use strict';

	var counter = 3;
	var octave = 1;
	// Notes with halfnotes for iterations
	var notes = [
		{
			full: 'C',
			half: 'C#'
		},
		{
			full: 'D',
			half: 'D#',
		},
		{
			full: 'E',
			half: null
		},
		{
			full: 'F',
			half: 'F#'
		},
		{
			full: 'G',
			half: 'G#'
		},
		{
			full: 'A',
			half: 'A#'
		},
		{
			full: 'B',
			half: null
		}
	];
	/**
	 * Keyboard identifier. Adds notes id, halftone data and label
	 * @param  {string} key  Object key
	 * @param  {object} keys Keys object
	 */
	var initialIteration = function(key, keys) {
		var labelElement = document.createElement('b');
		var halftone = null;
		var note = {};
		var button = keys[key];

		if (button.className == undefined && button.className !== 'key') {
			return;
		}
		// TODO: Write an ES6 iterator here
		if (counter == notes.length) {
			counter = 0;
			octave++;
		}

		note = notes[counter];

		if (note.half !== null) {
			halftone = note.half + octave;
			button.parentNode.querySelector('span').id = halftone;
		}

		labelElement.innerHtml = note.full;
		button.parentNode.appendChild(labelElement);

		button.id = note.full + octave;
		labelElement.innerHTML = note.full + octave;
		counter++;
	}

	var keys = document.querySelectorAll('.key');

	// Goes through .key elements add add notes
	for (var key in keys) {
		initialIteration(key, keys);
	}
})();<|endoftext|>


<commit_before>var debug = require('debug')('connect:cachify-static');
var find = require('find');
var minimatch = require('minimatch');
var calculateHash = require('./hash');

// switch off  'Do not use String as a constructor'
/* jshint -W053 */

module.exports = function hashStore(root, match, formatPathFn) {
  var my = {
    hashes2paths: Object.create(null),
    paths2hashes: Object.create(null)
  };

  function format(path, file) {
    var hash = calculateHash(file);

    return {
      path: formatPathFn(path, hash.value),
      integrity: hash.integrity
    };
  }

  function getPath(hash) {
    return hash && my.hashes2paths[hash];
  }

  function getHash(path, integrity) {
    var v = my.paths2hashes[path];
    if (v) {
      return integrity ? v : v.path;
    }
  }

  function cachify(path, integrity) {
    var hash = getHash(path, integrity);
    if (!hash) {
      debug('cachify called for unknown path %s', path);
      return path;
    }
    return hash;
  }

  function filter(pattern, integrity) {
    return Object.keys(my.paths2hashes)
      .filter(minimatch.filter(pattern))
      .map(function(path) {
        return getHash(path, integrity);
      });
  }

  debug('Calculating hashes for files in %s.', root);
  find.fileSync(match, root).forEach(function(file) {
    var
      path = file.slice(root.length),
      hash = format(path, file);
    my.hashes2paths[hash.path] = path;
    my.paths2hashes[path] = hash;
  });
  debug('Calculating hashes for %d files', Object.keys(my.paths2hashes).length);
  debug('Calculated %j', my);

  return {
    getPath: getPath,
    getHash: getHash,
    cachify: cachify,
    filter: filter
  };
};
<commit_msg>fix `cachify` result for unknown paths when integrity param set<commit_after>var debug = require('debug')('connect:cachify-static');
var find = require('find');
var minimatch = require('minimatch');
var calculateHash = require('./hash');

// switch off  'Do not use String as a constructor'
/* jshint -W053 */

module.exports = function hashStore(root, match, formatPathFn) {
  var my = {
    hashes2paths: Object.create(null),
    paths2hashes: Object.create(null)
  };

  function format(path, file) {
    var hash = calculateHash(file);

    return {
      path: formatPathFn(path, hash.value),
      integrity: hash.integrity
    };
  }

  function getPath(hash) {
    return hash && my.hashes2paths[hash];
  }

  function getHash(path, integrity) {
    var v = my.paths2hashes[path];
    if (v) {
      return integrity ? v : v.path;
    }
  }

  function cachify(path, integrity) {
    var hash = getHash(path, integrity);
    if (!hash) {
      debug('cachify called for unknown path %s', path);
      return integrity ? { path: path } : path;
    }
    return hash;
  }

  function filter(pattern, integrity) {
    return Object.keys(my.paths2hashes)
      .filter(minimatch.filter(pattern))
      .map(function(path) {
        return getHash(path, integrity);
      });
  }

  debug('Calculating hashes for files in %s.', root);
  find.fileSync(match, root).forEach(function(file) {
    var
      path = file.slice(root.length),
      hash = format(path, file);
    my.hashes2paths[hash.path] = path;
    my.paths2hashes[path] = hash;
  });
  debug('Calculating hashes for %d files', Object.keys(my.paths2hashes).length);
  debug('Calculated %j', my);

  return {
    getPath: getPath,
    getHash: getHash,
    cachify: cachify,
    filter: filter
  };
};
<|endoftext|>


<commit_before>'use strict';

var React = require('react');
var ReactDOM = require('react-dom-polyfill')(React);
var findDOMNode = ReactDOM.findDOMNode;
var className = require('classnames');
var debounce = require('lodash.debounce');

var CodeMirror = React.createClass({
	displayName: 'CodeMirror',

	propTypes: {
		className: React.PropTypes.any,
		codeMirrorInstance: React.PropTypes.func,
		defaultValue: React.PropTypes.string,
		onChange: React.PropTypes.func,
		onFocusChange: React.PropTypes.func,
		onScroll: React.PropTypes.func,
		onCursorActivity: React.PropTypes.func,
		options: React.PropTypes.object,
		path: React.PropTypes.string,
		value: React.PropTypes.string,
		cursor: React.PropTypes.object,
		preserveScrollPosition: React.PropTypes.bool
	},
	getDefaultProps: function getDefaultProps() {
		return {
			preserveScrollPosition: false
		};
	},
	getCodeMirrorInstance: function getCodeMirrorInstance() {
		return this.props.codeMirrorInstance || require('codemirror');
	},
	getInitialState: function getInitialState() {
		return {
			isFocused: false
		};
	},
	componentWillMount: function componentWillMount() {
		this.componentWillReceiveProps = debounce(this.componentWillReceiveProps, 0);
	},
	componentDidMount: function componentDidMount() {
		var textareaNode = findDOMNode(this.refs.textarea);
		var codeMirrorInstance = this.getCodeMirrorInstance();
		this.codeMirror = codeMirrorInstance.fromTextArea(textareaNode, this.props.options);
		this.codeMirror.on('change', this.codemirrorValueChanged);
		this.codeMirror.on('focus', this.focusChanged.bind(this, true));
		this.codeMirror.on('blur', this.focusChanged.bind(this, false));
		this.codeMirror.on('cursorActivity', this.cursorActivity);
		this.codeMirror.on('scroll', this.scrollChanged);
		this.codeMirror.setValue(this.props.defaultValue || this.props.value || '');
	},
	componentWillUnmount: function componentWillUnmount() {
		// is there a lighter-weight way to remove the cm instance?
		if (this.codeMirror) {
			this.codeMirror.toTextArea();
		}
	},
	componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
		if (this.codeMirror && nextProps.value !== undefined && this.codeMirror.getValue() !== nextProps.value) {
			if (this.props.preserveScrollPosition) {
				var prevScrollPosition = this.codeMirror.getScrollInfo();
				this.codeMirror.setValue(nextProps.value);
				this.codeMirror.scrollTo(prevScrollPosition.left, prevScrollPosition.top);
			} else {
				this.codeMirror.setValue(nextProps.value);
			}
		}
		var cur = this.codeMirror.getCursor();
		if (nexProps.cursor && (cur.ch != nextProps.cursor.ch || cur.line != nextProps.cursor.line)) {
			this.codeMirror.setCursor(nextProps.cursor);
		}
		if (typeof nextProps.options === 'object') {
			for (var optionName in nextProps.options) {
				if (nextProps.options.hasOwnProperty(optionName)) {
					this.codeMirror.setOption(optionName, nextProps.options[optionName]);
				}
			}
		}
	},
	getCodeMirror: function getCodeMirror() {
		return this.codeMirror;
	},
	focus: function focus() {
		if (this.codeMirror) {
			this.codeMirror.focus();
		}
	},
	focusChanged: function focusChanged(focused) {
		this.setState({
			isFocused: focused
		});
		this.props.onFocusChange && this.props.onFocusChange(focused);
	},
	cursorActivity: function cursorActivity(cm) {
		this.props.onCursorActivity && this.props.onCursorActivity(cm.getCursor(), cm.cursorCoords(true, 'window'), cm);
	},
	scrollChanged: function scrollChanged(cm) {
		this.props.onScroll && this.props.onScroll(cm.getScrollInfo());
	},
	codemirrorValueChanged: function codemirrorValueChanged(doc, change) {
		if (this.props.onChange && change.origin !== 'setValue') {
			this.props.onChange(doc.getValue());
		}
	},
	render: function render() {
		var editorClassName = className('ReactCodeMirror', this.state.isFocused ? 'ReactCodeMirror--focused' : null, this.props.className);
		return React.createElement(
			'div',
			{ className: editorClassName },
			React.createElement('textarea', { ref: 'textarea', name: this.props.path, defaultValue: this.props.value, autoComplete: 'off' })
		);
	}
});

module.exports = CodeMirror;<commit_msg>fixed cursor<commit_after>'use strict';

var React = require('react');
var ReactDOM = require('react-dom-polyfill')(React);
var findDOMNode = ReactDOM.findDOMNode;
var className = require('classnames');
var debounce = require('lodash.debounce');

var CodeMirror = React.createClass({
	displayName: 'CodeMirror',

	propTypes: {
		className: React.PropTypes.any,
		codeMirrorInstance: React.PropTypes.func,
		defaultValue: React.PropTypes.string,
		onChange: React.PropTypes.func,
		onFocusChange: React.PropTypes.func,
		onScroll: React.PropTypes.func,
		onCursorActivity: React.PropTypes.func,
		options: React.PropTypes.object,
		path: React.PropTypes.string,
		value: React.PropTypes.string,
		cursor: React.PropTypes.object,
		preserveScrollPosition: React.PropTypes.bool
	},
	getDefaultProps: function getDefaultProps() {
		return {
			preserveScrollPosition: false
		};
	},
	getCodeMirrorInstance: function getCodeMirrorInstance() {
		return this.props.codeMirrorInstance || require('codemirror');
	},
	getInitialState: function getInitialState() {
		return {
			isFocused: false
		};
	},
	componentWillMount: function componentWillMount() {
		this.componentWillReceiveProps = debounce(this.componentWillReceiveProps, 0);
	},
	componentDidMount: function componentDidMount() {
		var textareaNode = findDOMNode(this.refs.textarea);
		var codeMirrorInstance = this.getCodeMirrorInstance();
		this.codeMirror = codeMirrorInstance.fromTextArea(textareaNode, this.props.options);
		this.codeMirror.on('change', this.codemirrorValueChanged);
		this.codeMirror.on('focus', this.focusChanged.bind(this, true));
		this.codeMirror.on('blur', this.focusChanged.bind(this, false));
		this.codeMirror.on('cursorActivity', this.cursorActivity);
		this.codeMirror.on('scroll', this.scrollChanged);
		this.codeMirror.setValue(this.props.defaultValue || this.props.value || '');
	},
	componentWillUnmount: function componentWillUnmount() {
		// is there a lighter-weight way to remove the cm instance?
		if (this.codeMirror) {
			this.codeMirror.toTextArea();
		}
	},
	componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
		if (this.codeMirror && nextProps.value !== undefined && this.codeMirror.getValue() !== nextProps.value) {
			if (this.props.preserveScrollPosition) {
				var prevScrollPosition = this.codeMirror.getScrollInfo();
				this.codeMirror.setValue(nextProps.value);
				this.codeMirror.scrollTo(prevScrollPosition.left, prevScrollPosition.top);
			} else {
				this.codeMirror.setValue(nextProps.value);
			}
		}
		var cur = this.codeMirror.getCursor();
		if (nextProps.cursor && (cur.ch != nextProps.cursor.ch || cur.line != nextProps.cursor.line)) {
			this.codeMirror.setCursor(nextProps.cursor);
		}
		if (typeof nextProps.options === 'object') {
			for (var optionName in nextProps.options) {
				if (nextProps.options.hasOwnProperty(optionName)) {
					this.codeMirror.setOption(optionName, nextProps.options[optionName]);
				}
			}
		}
	},
	getCodeMirror: function getCodeMirror() {
		return this.codeMirror;
	},
	focus: function focus() {
		if (this.codeMirror) {
			this.codeMirror.focus();
		}
	},
	focusChanged: function focusChanged(focused) {
		this.setState({
			isFocused: focused
		});
		this.props.onFocusChange && this.props.onFocusChange(focused);
	},
	cursorActivity: function cursorActivity(cm) {
		this.props.onCursorActivity && this.props.onCursorActivity(cm.getCursor(), cm.cursorCoords(true, 'window'), cm);
	},
	scrollChanged: function scrollChanged(cm) {
		this.props.onScroll && this.props.onScroll(cm.getScrollInfo());
	},
	codemirrorValueChanged: function codemirrorValueChanged(doc, change) {
		if (this.props.onChange && change.origin !== 'setValue') {
			this.props.onChange(doc.getValue());
		}
	},
	render: function render() {
		var editorClassName = className('ReactCodeMirror', this.state.isFocused ? 'ReactCodeMirror--focused' : null, this.props.className);
		return React.createElement(
			'div',
			{ className: editorClassName },
			React.createElement('textarea', { ref: 'textarea', name: this.props.path, defaultValue: this.props.value, autoComplete: 'off' })
		);
	}
});

module.exports = CodeMirror;<|endoftext|>


<commit_before>"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var uuid = require('uuid');

var Collection = function () {
	function Collection(name, schema, indexByProp) {
		_classCallCheck(this, Collection);

		this._id = uuid();

		this.$name = name;
		this.setSchema(schema);
		this.indexingProp = indexByProp;
		this.entries = new Map();
	}

	_createClass(Collection, [{
		key: "validateSchema",
		value: function validateSchema(schema) {
			if (typeof schema != "object" && !Array.isArray(schema)) return false;
			var validTypes = new Set(["string", "object", "number", "boolean", "[string]", "[object]", "[number]", "[boolean]" /*, not used: "symbol", "function"*/]);
			var _iteratorNormalCompletion = true;
			var _didIteratorError = false;
			var _iteratorError = undefined;

			try {
				for (var _iterator = schema[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
					var propDefinition = _step.value;

					if (!validTypes.has(propDefinition.type)) return false;
					if (propDefinition.optional !== true && propDefinition.optional !== false && propDefinition.optional !== undefined) return false;
					if (typeof propDefinition.defaultValue != "undefined" && !validTypes.has(typeof propDefinition.defaultValue)) return false;
				}
			} catch (err) {
				_didIteratorError = true;
				_iteratorError = err;
			} finally {
				try {
					if (!_iteratorNormalCompletion && _iterator.return) {
						_iterator.return();
					}
				} finally {
					if (_didIteratorError) {
						throw _iteratorError;
					}
				}
			}

			;
			return true;
		}
	}, {
		key: "setSchema",
		value: function setSchema(schema) {
			if (!this.validateSchema(schema)) throw new Error(`Invalid schema: ${schema}`);;
			var old = this.schema;
			this.schema = schema;
			return old;
		}
	}, {
		key: "validateAgainstSchema",
		value: function validateAgainstSchema(o) {}
	}, {
		key: "get",
		value: function get(key, value) {
			if (key === this.indexingProp) {
				return this.entries.get(value);
			} else {
				var entries = this.entries.entries();
				var _iteratorNormalCompletion2 = true;
				var _didIteratorError2 = false;
				var _iteratorError2 = undefined;

				try {
					for (var _iterator2 = entries[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
						var entry = _step2.value;

						if (entry[0] == key && entry[1] == value) return true;
					}
				} catch (err) {
					_didIteratorError2 = true;
					_iteratorError2 = err;
				} finally {
					try {
						if (!_iteratorNormalCompletion2 && _iterator2.return) {
							_iterator2.return();
						}
					} finally {
						if (_didIteratorError2) {
							throw _iteratorError2;
						}
					}
				}
			};
			return;
		}
	}, {
		key: "findOne",
		value: function findOne(matchObj) {
			var key = Object.keys(matchObj)[0];
			return this.get(key, matchObj[key]);
		}
	}, {
		key: "findAll",
		value: function findAll() {
			return this.entries.values();
		}
	}, {
		key: "insert",
		value: function insert(o) {
			if (!this.validateAgainstSchema(o)) throw new Error('Invalid insertion item.');
			var key = o[this.indexingProp];
			return this.entries.set(key, o);
		}
	}, {
		key: "remove",
		value: function remove(key, value) {
			if (key === this.indexingProp) {
				return this.entries.delete(value);
			} else {
				var entries = this.entries.entries();
				var _iteratorNormalCompletion3 = true;
				var _didIteratorError3 = false;
				var _iteratorError3 = undefined;

				try {
					for (var _iterator3 = entries[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
						var entry = _step3.value;

						if (entry[0] == key && entry[1] == value) return this.entries.delete(entry[this.indexingProp]);
					}
				} catch (err) {
					_didIteratorError3 = true;
					_iteratorError3 = err;
				} finally {
					try {
						if (!_iteratorNormalCompletion3 && _iterator3.return) {
							_iterator3.return();
						}
					} finally {
						if (_didIteratorError3) {
							throw _iteratorError3;
						}
					}
				}
			};
			return;
		}
	}, {
		key: "id",
		get: function get() {
			return this._id;
		}
	}, {
		key: "name",
		get: function get() {
			return this.$name;
		}
	}]);

	return Collection;
}();<commit_msg>think i'm done collection class<commit_after>"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var uuid = require('uuid');

var Collection = function () {
	/**
  * @param name: unique name for collection
  * @param schema: schema definition for validation in colleciton
  * @param indexByProp: unique index for each collection entry. this is going to be required.
  * @throws Error if invalid schema
  */
	function Collection(name, schema, indexByProp) {
		_classCallCheck(this, Collection);

		this._id = uuid();

		this.$name = name;
		this.setSchema(schema);
		this.indexingProp = indexByProp;
		this.entries = new Map();
	}

	_createClass(Collection, [{
		key: "validateSchema",

		/**
   * validate formate of a schema object
   * @param schema: object -- schema
  	EX.
  		{
  			"name": {
  				"type": "string",
  				"required": true,
  				"defaultValue": "Monet",
  			},
  			"emailAdresses": {
  				"type": "[string]",
  				"required": true,
  			},
  			"preferredOpera": {
  				"type": "object",
  				"required": false,
  			},
  		}
   * @return true if valid
   */
		value: function validateSchema(schema) {
			if (typeof schema != "object" && !Array.isArray(schema)) return false;
			var validTypes = new Set(["string", "object", "number", "boolean", "[string]", "[object]", "[number]", "[boolean]" /*, not used: "symbol", "function"*/]);
			var _iteratorNormalCompletion = true;
			var _didIteratorError = false;
			var _iteratorError = undefined;

			try {
				for (var _iterator = schema[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
					var propDefinition = _step.value;

					if (!validTypes.has(propDefinition.type)) return false;
					if (propDefinition.required !== true && propDefinition.required !== false && propDefinition.required !== undefined) return false;
					if (typeof propDefinition.defaultValue != "undefined" && !validTypes.has(typeof propDefinition.defaultValue)) return false;
				}
			} catch (err) {
				_didIteratorError = true;
				_iteratorError = err;
			} finally {
				try {
					if (!_iteratorNormalCompletion && _iterator.return) {
						_iterator.return();
					}
				} finally {
					if (_didIteratorError) {
						throw _iteratorError;
					}
				}
			}

			;
			return true;
		}

		/*
   * update schema
   * @param schema: object -- schema
   * @throws Error if invalid schema
   * @return old schema
   */

	}, {
		key: "setSchema",
		value: function setSchema(schema) {
			if (!this.validateSchema(schema)) throw new Error(`Invalid schema: ${schema}`);;
			var old = this.schema;
			this.schema = schema;
			return old;
		}

		/**
   * validate an entry against currently set schema
   */

	}, {
		key: "validateAgainstSchema",
		value: function validateAgainstSchema(o) {}

		/**
   * get an entry by key and value
   * Note: if key is the unique indexing property, then retrieval by value will be quicker
   * @param key: string -- key to compare value to for entry retrieval
   * @param value: value to match entry with
   * @return matching entry if found. undefined otherwise
   */

	}, {
		key: "get",
		value: function get(key, value) {
			if (key === this.indexingProp) {
				return this.entries.get(value);
			} else {
				var entries = this.entries.entries();
				var _iteratorNormalCompletion2 = true;
				var _didIteratorError2 = false;
				var _iteratorError2 = undefined;

				try {
					for (var _iterator2 = entries[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
						var entry = _step2.value;

						if (entry[0] == key && entry[1] == value) return entry;
					}
				} catch (err) {
					_didIteratorError2 = true;
					_iteratorError2 = err;
				} finally {
					try {
						if (!_iteratorNormalCompletion2 && _iterator2.return) {
							_iterator2.return();
						}
					} finally {
						if (_didIteratorError2) {
							throw _iteratorError2;
						}
					}
				}
			};
			return;
		}

		/**
   * find an entry
   * @param matchObj: object - with one property (key), and associated value to retrieve entry by
   * @return matching entry or undefined
   */

	}, {
		key: "findOne",
		value: function findOne(matchObj) {
			var key = Object.keys(matchObj)[0];
			return this.get(key, matchObj[key]);
		}

		/**
   * @return iterable of all entries stored in collection
   */

	}, {
		key: "findAll",
		value: function findAll() {
			return this.entries.values();
		}

		/**
   * insert entry to collection
   * @param o: item to insert into collection
   * @throws Error if item does not validate against collection's schema
   * @return previous entry with the same value for its 'indexingProp' if exists
   */

	}, {
		key: "insert",
		value: function insert(o) {
			if (!this.validateAgainstSchema(o)) throw new Error(`Invalid insertion item. ${o}`);
			var key = o[this.indexingProp];
			return this.entries.set(key, o);
		}

		/**
   * remove entry from collection
   * Note: removal would be quicker if key is the unique indexing property
   * @param key: key to match value with
   * @param value: value to match against
   * @return deleted entry or undefined
   */

	}, {
		key: "remove",
		value: function remove(key, value) {
			if (key === this.indexingProp) {
				return this.entries.delete(value);
			} else {
				var entries = this.entries.entries();
				var _iteratorNormalCompletion3 = true;
				var _didIteratorError3 = false;
				var _iteratorError3 = undefined;

				try {
					for (var _iterator3 = entries[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
						var entry = _step3.value;

						if (entry[0] == key && entry[1] == value) return this.entries.delete(entry[this.indexingProp]);
					}
				} catch (err) {
					_didIteratorError3 = true;
					_iteratorError3 = err;
				} finally {
					try {
						if (!_iteratorNormalCompletion3 && _iterator3.return) {
							_iterator3.return();
						}
					} finally {
						if (_didIteratorError3) {
							throw _iteratorError3;
						}
					}
				}
			};
			return;
		}
	}, {
		key: "id",
		get: function get() {
			return this._id;
		}
	}, {
		key: "name",
		get: function get() {
			return this.$name;
		}
	}]);

	return Collection;
}();<|endoftext|>


<commit_before>module.exports = function ( opt )
{
	opt = opt || {};

	var vfs = require('vinyl-fs'),
		Promise = require('promise');

	// Hook function
	return function ( context )
	{
		var targetPath = opt.targetPath || context.targetPath;

		// Package hook function
		return function ( pkg, globs )
		{
			// Promise
			return new Promise(function ( resolve, reject )
			{
				context.invokedPromise.then(function ( )
				{
					console.log(pkg);
					vfs.src(globs, {cwd: pkg.exportsAbsolutePath})
						.pipe(vfs.dest(targetPath))
						.on('end', resolve)
						.on('error', reject);
				},
				reject);
			});
		}
	};
}<commit_msg>Remove debug logging and rejection on invoke promise rejection<commit_after>module.exports = function ( opt )
{
	opt = opt || {};

	var vfs = require('vinyl-fs'),
		Promise = require('promise');

	// Hook function
	return function ( context )
	{
		var targetPath = opt.targetPath || context.targetPath;

		// Package hook function
		return function ( pkg, globs )
		{
			// Promise
			return new Promise(function ( resolve, reject )
			{
				context.invokedPromise.then(function ( )
				{
					vfs.src(globs, {cwd: pkg.exportsAbsolutePath})
						.pipe(vfs.dest(targetPath))
						.on('end', resolve)
						.on('error', reject);
				});
			});
		}
	};
}<|endoftext|>


<commit_before>"use strict";
var
  extend = require("extend"),
  querystring = require("querystring"),
  objectPath = require("object-path"),
  util = require("util"),
  assert = require("chai").assert;

/**
 * Generates http client; wrapper of http/https library.
 *
 * `defaults` expect have two keys: params and headers
 *
 * @param {string} host
 * @param {boolean} ssl use to switch using `https` and `http`
 * @param {object} defaults will set unmodifiable default value
 * @return {object}
 */
function HttpClient(host, ssl, defaults) {
  function buildCookie(cookie) {
    var ret = cookie;
    if (typeof(cookie) === "object") {
      ret = cookie[0];
    }
    var idx = ret.indexOf(" expires=");
    if (idx != -1) {
      ret = ret.substring(0, idx);
    }
    return ret;
  }
  function urlencode(params) {
    function getValue(value) {
      if (typeof(value) === "function") {
        value = value(params);
      }
      return querystring.escape(value);
    }
    if (typeof(params) === "function") {
      params = params();
    }
    var ret = "";
    for (var key in params) {
      if (params.hasOwnProperty(key)) {
        var value = params[key];
        if (Array.isArray(value)) {
          for (var i=0; i<value.length; i++) {
            if (ret.length > 0) ret += "&";
            ret += querystring.escape(key) + "=" + getValue(value[i]);
          }
        } else {
          if (ret.length > 0) ret += "&";
          ret += querystring.escape(key) + "=" + getValue(value);
        }
      }
    }
    return ret;
  }
  function toJson(params) {
    function normalize(p) {
      var
        type = typeof(p),
        ret = p;
      if (type === "function") {
        p = p();
        type = typeof(p);
      }
      if (type === "object") {
        if (Array.isArray(type)) {
          ret = [];
          for (var i=0; i<p.length; i++) {
            ret.push(normalize(p[i]));
          }
        } else {
          ret = {};
          for (var key in p) {
            if (p.hasOwnProperty(key)) {
              ret[key] = normalize(p[key]);
            }
          }
        }
      }
      return ret;
    }
    if (typeof(params) === "function") {
      params = params();
    }
    params = normalize(params);
    return JSON.stringify(params);
  }
  function withAPI(v) {
    api = v;
    return this;
  }
  function withParams(v) {
    params = v;
    return this;
  }
  function withHeaders(v) {
    headers = v;
    return this;
  }
  function done(callback, data, res, req) {
    function isDone(func) {
      return callback.toString().indexOf("done() invoked with non-Error") !== -1;
    }
    if (!callback) {
      return;
    }
    if (isDone(callback)) {
      callback();
    } else {
      callback(data, res, req);
    }
  }
  function login(params) {
    return self.api(api.login).params(params);
  }
  function success(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isSuccess(data, res), "Response isn't success.");
      api.validateResponse(data, res, req);
      done(callback, data, res, req);
    });
  }
  function badRequest(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isBadRequest(data, res), "Response isn't badRequest.");
      done(callback, data, res, req);
    });
  }
  function notFound(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isNotFound(data, res), "Response isn't notFound.");
      done(callback, data, res, req);
    });
  }
  function unauthorized(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isUnauthorized(data, res), "Response isn't unauthorized.");
      done(callback, data, res, req);
    });
  }
  function clientError(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isClientError(data, res), "Response isn't clientError.");
      if (callback) {
        callback(data, res, req);
      }
    });
  }
  function doTest(callback) {
    function isJson(contentType) {
      if (!contentType) return false;
      var ct = contentType.toLowerCase();
      return ct.indexOf("/json") > 0 || ct.indexOf("+json") > 0;
    }
    function doCallback(data, res, req) {
      if (currentApi.verbose()) {
        console.log("**** Response Data ****");
        console.log("statusCode = " + res.statusCode);
        console.log("data = ");
        console.log(data);
      }
      if (!callback) {
        return;
      }
      var ct = res.headers["content-type"];
      if (isJson(ct)) {
        data = JSON.parse(data);
      }
      callback(data, res, req);
    }
    function buildEndpoint() {
      var ret = currentApi.endpoint;
      if (currentApi.urlParams) {
        currentApi.urlParams.forEach(function(key) {
          ret = ret.replace("[" + key + "]", currentParams[key]);
          delete currentParams[key];
        });
      }
      return ret;
    }
    var
      currentApi = api,
      currentParams = extend({}, defaults.params, params),
      currentHeaders = extend({}, defaults.headers, headers);
    params = null;
    headers = null;
    if (!currentApi) {
      throw "api isn't set.";
    }
    var requestParams = {
      "method": currentApi.method,
      "headers": currentHeaders,
      "path": buildEndpoint(),
      "data": Object.keys(currentParams).length > 0 ? currentParams : null,
      "log": currentApi.verbose()
    };
    if (currentApi.request && currentApi.request.contentType) {
      requestParams.headers["Content-Type"] = currentApi.request.contentType;
    }
    request(requestParams, doCallback);
    return self;
  }
  function request(config, callback, log) {
    var data = null;

    config.headers = config.headers || {};

    if (config.method == "GET" && config.data && !config.params) {
      config.params = config.data;
      delete config.data;
    }
    if (config.data) {
      var ct = config.headers["Content-Type"];
      if (!ct) {
        ct = "application/x-www-form-urlencoded";
        config.headers["Content-Type"] = ct;
      }
      if (ct === "application/x-www-form-urlencoded") {
        data = urlencode(config.data);
      } else if (ct === "application/json") {
        data = toJson(config.data);
      }
      config.headers["Content-Length"] = data.length;
    }
    if (cookie) {
      config.headers.Cookie = buildCookie(cookie);
    }
    if (config.params) {
      config.path += "?" + urlencode(config.params);
    }
    if (config.log) {
      console.log("**** Request Data ****");
      console.log(config.path);
      if (data) {
        console.log(data);
      }
    }
    config.hostname = host;
    config.port = port;
    var req = con.request(config, function(res) {
      var body = "";
      res.setEncoding("utf-8");
      if (res.headers && res.headers["set-cookie"]) {
        cookie = res.headers["set-cookie"];
      }
      res.on("data", function(data) { body += data;});
      res.on("end", function() {
        if (callback) {
          callback(body, res, req);
        }
      });
    });
    req.on("error", function(e) {
      console.log("!!!!! error !!!!!", e);
    });
    if (data) {
      req.write(data);
    }
    req.end();
  }
  function copy() {
    var ret = new HttpClient(host + ":" + port, ssl);
    ret.assign(cookie, api, params, headers);
    return ret;
  }
  function assign(cookie_, api_, params_, headers_) {
    cookie = cookie_;
    api = api_;
    params = params_;
    headers = headers_;
  }
  var
    self = this,
    con = ssl ? require("https") : require("http"),
    port = ssl ? 443 : 80,
    cookie = null,
    api = null,
    params = null,
    headers = null;

  // Initialize default parameter object
  defaults = defaults || {};
  defaults.params = defaults.params || {};
  defaults.headers = defaults.headers || {};

  if (host.indexOf(":") != -1) {
    port = parseInt(host.split(":")[1], 10);
    host = host.split(":")[0];
  }
  function badRequestAll(runDefaults, optionParams) {
    function doIt(desc, data) {
      it(desc, function(done) {
        copy().params(data).badRequest(done);
      });
    }
    function processValue(desc, key, value) {
      var
        data = extend({}, params),
        orgValue = objectPath.get(data, key);
      if (util.isArray(orgValue)) {
        orgValue[0] = value;
      } else {
        objectPath.set(data, key, value);
      }
      doIt(desc, data);
    }
    function process(prefix, reqParams) {
      reqParams.forEach(function(p) {
        var
          fullName = prefix ? prefix + "." + p.name : p.name,
          options = {};
        if (p.hasRule("email")) {
          options.email = true;
        }
        if (p.hasRule("url")) {
          options.url = true;
        }
        if (runDefaults) {
          var invalidTypeValue = p.generateInvalidTypeValue();
          if (invalidTypeValue) {
            processValue(fullName + " - invalid datatype(" + invalidTypeValue + ")",
              fullName, invalidTypeValue);
          }
          p.rules.forEach(function(r) {
            var data = r.generateBadRequest(fullName, params, options);
            if (data) {
              doIt(fullName + " - " + r.name　+ "(" + objectPath.get(data, fullName) + ")", data);
            }
          });
        }
        var optionValue = objectPath.get(optionParams, fullName);
        if (optionValue) {
          if (util.isArray(optionValue)) {
            optionValue.forEach(function(v) {
              processValue(fullName + " - " + v, fullName, v);
            });
          } else {
            processValue(fullName + " - " + optionValue, fullName, optionValue);
          }
        }
        process(fullName, p.childParams());

      });
    }
    if (!api || !params) {
      throw "Must specify api and params";
    }
    switch (arguments.length) {
      case 0:
        runDefaults = true;
        optionParams = {};
        break;
      case 1:
        if (typeof(runDefaults) === "object") {
          optionParams = runDefaults;
          runDefaults = true;
        }
        break;
    }
    optionParams = optionParams || {};
    describe("BadRequest test for", function() {
      process("", api.request.params.childParams());
    });
  }
  extend(this, {
    "api": withAPI,
    "params": withParams,
    "headers": withHeaders,
    "login": login,
    "success": success,
    "badRequest": badRequest,
    "notFound": notFound,
    "unauthorized": unauthorized,
    "clientError": clientError,
    "request": request,
    "assign": assign,
    "badRequestAll": badRequestAll
  });
}

module.exports = HttpClient;<commit_msg>fix: pass default parameters on `copy` method<commit_after>"use strict";
var
  extend = require("extend"),
  querystring = require("querystring"),
  objectPath = require("object-path"),
  util = require("util"),
  assert = require("chai").assert;

/**
 * Generates http client; wrapper of http/https library.
 *
 * `defaults` expect have two keys: params and headers
 *
 * @param {string} host
 * @param {boolean} ssl use to switch using `https` and `http`
 * @param {object} defaults will set unmodifiable default value
 * @return {object}
 */
function HttpClient(host, ssl, defaults) {
  function buildCookie(cookie) {
    var ret = cookie;
    if (typeof(cookie) === "object") {
      ret = cookie[0];
    }
    var idx = ret.indexOf(" expires=");
    if (idx != -1) {
      ret = ret.substring(0, idx);
    }
    return ret;
  }
  function urlencode(params) {
    function getValue(value) {
      if (typeof(value) === "function") {
        value = value(params);
      }
      return querystring.escape(value);
    }
    if (typeof(params) === "function") {
      params = params();
    }
    var ret = "";
    for (var key in params) {
      if (params.hasOwnProperty(key)) {
        var value = params[key];
        if (Array.isArray(value)) {
          for (var i=0; i<value.length; i++) {
            if (ret.length > 0) ret += "&";
            ret += querystring.escape(key) + "=" + getValue(value[i]);
          }
        } else {
          if (ret.length > 0) ret += "&";
          ret += querystring.escape(key) + "=" + getValue(value);
        }
      }
    }
    return ret;
  }
  function toJson(params) {
    function normalize(p) {
      var
        type = typeof(p),
        ret = p;
      if (type === "function") {
        p = p();
        type = typeof(p);
      }
      if (type === "object") {
        if (Array.isArray(type)) {
          ret = [];
          for (var i=0; i<p.length; i++) {
            ret.push(normalize(p[i]));
          }
        } else {
          ret = {};
          for (var key in p) {
            if (p.hasOwnProperty(key)) {
              ret[key] = normalize(p[key]);
            }
          }
        }
      }
      return ret;
    }
    if (typeof(params) === "function") {
      params = params();
    }
    params = normalize(params);
    return JSON.stringify(params);
  }
  function withAPI(v) {
    api = v;
    return this;
  }
  function withParams(v) {
    params = v;
    return this;
  }
  function withHeaders(v) {
    headers = v;
    return this;
  }
  function done(callback, data, res, req) {
    function isDone(func) {
      return callback.toString().indexOf("done() invoked with non-Error") !== -1;
    }
    if (!callback) {
      return;
    }
    if (isDone(callback)) {
      callback();
    } else {
      callback(data, res, req);
    }
  }
  function login(params) {
    return self.api(api.login).params(params);
  }
  function success(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isSuccess(data, res), "Response isn't success.");
      api.validateResponse(data, res, req);
      done(callback, data, res, req);
    });
  }
  function badRequest(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isBadRequest(data, res), "Response isn't badRequest.");
      done(callback, data, res, req);
    });
  }
  function notFound(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isNotFound(data, res), "Response isn't notFound.");
      done(callback, data, res, req);
    });
  }
  function unauthorized(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isUnauthorized(data, res), "Response isn't unauthorized.");
      done(callback, data, res, req);
    });
  }
  function clientError(callback) {
    return doTest(function(data, res, req) {
      assert.ok(api.isClientError(data, res), "Response isn't clientError.");
      if (callback) {
        callback(data, res, req);
      }
    });
  }
  function doTest(callback) {
    function isJson(contentType) {
      if (!contentType) return false;
      var ct = contentType.toLowerCase();
      return ct.indexOf("/json") > 0 || ct.indexOf("+json") > 0;
    }
    function doCallback(data, res, req) {
      if (currentApi.verbose()) {
        console.log("**** Response Data ****");
        console.log("statusCode = " + res.statusCode);
        console.log("data = ");
        console.log(data);
      }
      if (!callback) {
        return;
      }
      var ct = res.headers["content-type"];
      if (isJson(ct)) {
        data = JSON.parse(data);
      }
      callback(data, res, req);
    }
    function buildEndpoint() {
      var ret = currentApi.endpoint;
      if (currentApi.urlParams) {
        currentApi.urlParams.forEach(function(key) {
          ret = ret.replace("[" + key + "]", currentParams[key]);
          delete currentParams[key];
        });
      }
      return ret;
    }
    var
      currentApi = api,
      currentParams = extend({}, defaults.params, params),
      currentHeaders = extend({}, defaults.headers, headers);
    params = null;
    headers = null;
    if (!currentApi) {
      throw "api isn't set.";
    }
    var requestParams = {
      "method": currentApi.method,
      "headers": currentHeaders,
      "path": buildEndpoint(),
      "data": Object.keys(currentParams).length > 0 ? currentParams : null,
      "log": currentApi.verbose()
    };
    if (currentApi.request && currentApi.request.contentType) {
      requestParams.headers["Content-Type"] = currentApi.request.contentType;
    }
    request(requestParams, doCallback);
    return self;
  }
  function request(config, callback, log) {
    var data = null;

    config.headers = config.headers || {};

    if (config.method == "GET" && config.data && !config.params) {
      config.params = config.data;
      delete config.data;
    }
    if (config.data) {
      var ct = config.headers["Content-Type"];
      if (!ct) {
        ct = "application/x-www-form-urlencoded";
        config.headers["Content-Type"] = ct;
      }
      if (ct === "application/x-www-form-urlencoded") {
        data = urlencode(config.data);
      } else if (ct === "application/json") {
        data = toJson(config.data);
      }
      config.headers["Content-Length"] = data.length;
    }
    if (cookie) {
      config.headers.Cookie = buildCookie(cookie);
    }
    if (config.params) {
      config.path += "?" + urlencode(config.params);
    }
    if (config.log) {
      console.log("**** Request Data ****");
      console.log(config.path);
      if (data) {
        console.log(data);
      }
    }
    config.hostname = host;
    config.port = port;
    var req = con.request(config, function(res) {
      var body = "";
      res.setEncoding("utf-8");
      if (res.headers && res.headers["set-cookie"]) {
        cookie = res.headers["set-cookie"];
      }
      res.on("data", function(data) { body += data;});
      res.on("end", function() {
        if (callback) {
          callback(body, res, req);
        }
      });
    });
    req.on("error", function(e) {
      console.log("!!!!! error !!!!!", e);
    });
    if (data) {
      req.write(data);
    }
    req.end();
  }
  function copy() {
    var ret = new HttpClient(host + ":" + port, ssl, defaults);
    ret.assign(cookie, api, params, headers);
    return ret;
  }
  function assign(cookie_, api_, params_, headers_) {
    cookie = cookie_;
    api = api_;
    params = params_;
    headers = headers_;
  }
  var
    self = this,
    con = ssl ? require("https") : require("http"),
    port = ssl ? 443 : 80,
    cookie = null,
    api = null,
    params = null,
    headers = null;

  // Initialize default parameter object
  defaults = defaults || {};
  defaults.params = defaults.params || {};
  defaults.headers = defaults.headers || {};

  if (host.indexOf(":") != -1) {
    port = parseInt(host.split(":")[1], 10);
    host = host.split(":")[0];
  }
  function badRequestAll(runDefaults, optionParams) {
    function doIt(desc, data) {
      it(desc, function(done) {
        copy().params(data).badRequest(done);
      });
    }
    function processValue(desc, key, value) {
      var
        data = extend({}, params),
        orgValue = objectPath.get(data, key);
      if (util.isArray(orgValue)) {
        orgValue[0] = value;
      } else {
        objectPath.set(data, key, value);
      }
      doIt(desc, data);
    }
    function process(prefix, reqParams) {
      reqParams.forEach(function(p) {
        var
          fullName = prefix ? prefix + "." + p.name : p.name,
          options = {};
        if (p.hasRule("email")) {
          options.email = true;
        }
        if (p.hasRule("url")) {
          options.url = true;
        }
        if (runDefaults) {
          var invalidTypeValue = p.generateInvalidTypeValue();
          if (invalidTypeValue) {
            processValue(fullName + " - invalid datatype(" + invalidTypeValue + ")",
              fullName, invalidTypeValue);
          }
          p.rules.forEach(function(r) {
            var data = r.generateBadRequest(fullName, params, options);
            if (data) {
              doIt(fullName + " - " + r.name　+ "(" + objectPath.get(data, fullName) + ")", data);
            }
          });
        }
        var optionValue = objectPath.get(optionParams, fullName);
        if (optionValue) {
          if (util.isArray(optionValue)) {
            optionValue.forEach(function(v) {
              processValue(fullName + " - " + v, fullName, v);
            });
          } else {
            processValue(fullName + " - " + optionValue, fullName, optionValue);
          }
        }
        process(fullName, p.childParams());

      });
    }
    if (!api || !params) {
      throw "Must specify api and params";
    }
    switch (arguments.length) {
      case 0:
        runDefaults = true;
        optionParams = {};
        break;
      case 1:
        if (typeof(runDefaults) === "object") {
          optionParams = runDefaults;
          runDefaults = true;
        }
        break;
    }
    optionParams = optionParams || {};
    describe("BadRequest test for", function() {
      process("", api.request.params.childParams());
    });
  }
  extend(this, {
    "api": withAPI,
    "params": withParams,
    "headers": withHeaders,
    "login": login,
    "success": success,
    "badRequest": badRequest,
    "notFound": notFound,
    "unauthorized": unauthorized,
    "clientError": clientError,
    "request": request,
    "assign": assign,
    "badRequestAll": badRequestAll
  });
}

module.exports = HttpClient;
<|endoftext|>


<commit_before>var mysql = require('mysql');
var async = require('async');
var Util = require('util');
var EventEmitter = require('events').EventEmitter;

module.exports = Connection;
Util.inherits(Connection, EventEmitter);
function Connection(options) {
    EventEmitter.call(this);

    this.mysqlConnectionPool = mysql.createPool(options.config);
    return this;
}

Connection.prototype.exec_raw_query = function exec_raw_query(sqlRawQuery, callback) {
    this.mysqlConnectionPool.getConnection(function(err, connection) {
        if(err) throw new Error(err);
        connection.query(sqlRawQuery, function(er, result) {
            connection.release();
            if(er) throw new Error(er);
            return callback(result);
        });
    });
}

Connection.prototype.Schema = function Schema(schemaObject) {
    for(var tableName in schemaObject) {
        var rowNamesObject = schemaObject[tableName];
        var sqlCreateQuery = 'CREATE TABLE IF NOT EXISTS ';
        for(var rowName in rowNamesObject) {
            if(rowName.toLowerCase() === 'foreign_key') {        // Handling FOREIGN KEYS
                attributes += ', FOREIGN KEY (' + rowNamesObject[rowName][0] + ') REFERENCES ' + rowNamesObject[rowName][1] + '(' + rowNamesObject[rowName][2] + ')';
            } else if(rowName.toLowerCase() === 'unique') {      // Handling UNIQUE KEYS
                attributes += ', UNIQUE (' + rowNamesObject[rowName].join(',') + ')';
            } else {
                if(attributes !== undefined) {
                    attributes += ', ' + rowName + ' ' + rowNamesObject[rowName].join(' ');
                } else {
                    var attributes = rowName + ' ' + rowNamesObject[rowName].join(' ');
                }
            }
        }
        sqlCreateQuery += tableName + ' (' + attributes + ') ENGINE=INNODB;';
        attributes = undefined;         // For next query
        this.exec_raw_query(sqlCreateQuery, function(createResponse) {
            return createResponse;
        });
    }
}<commit_msg>transaction added (to be tested)<commit_after>var mysql = require('mysql');
var async = require('async');
var Util = require('util');
var EventEmitter = require('events').EventEmitter;

module.exports = Connection;
Util.inherits(Connection, EventEmitter);
function Connection(options) {
    EventEmitter.call(this);

    this.mysqlConnectionPool = mysql.createPool(options.config);
    return this;
}

Connection.prototype.exec_raw_query = function exec_raw_query(sqlRawQuery, callback) {
    this.mysqlConnectionPool.getConnection(function(err, connection) {
        if(err) throw new Error(err);
        connection.query(sqlRawQuery, function(er, result) {
            connection.release();
            if(er) throw new Error(er);
            return callback(result);
        });
    });
}

// Needs to be tested for failure cases
Connection.prototype.exec_transaction = function exec_transaction(tran, callback) {     // array of transactions
    this.mysqlConnectionPool.getConnection(function(err, connection) {
        if(err) throw new Error(err);
        connection.beginTransaction(function(er) {
          if(er) throw new Error(er);
          for(var i; i<trans.length; i++) {
            connection.query(trans[i], function(e, result) {
                if(e) {
                    connection.rollback(function() {
                        throw new Error(e);
                    });
                }
            });
          }
          connection.commit(function(e) {
            if(e) {
                connection.rollback(function() {
                    throw new Error(e);
                });
            }
            connection.release();
            return callback("Transaction complete");
          });
        });
      });
}

Connection.prototype.Schema = function Schema(schemaObject) {
    for(var tableName in schemaObject) {
        var rowNamesObject = schemaObject[tableName];
        var sqlCreateQuery = 'CREATE TABLE IF NOT EXISTS ';
        for(var rowName in rowNamesObject) {
            if(rowName.toLowerCase() === 'foreign_key') {        // Handling FOREIGN KEYS
                attributes += ', FOREIGN KEY (' + rowNamesObject[rowName][0] + ') REFERENCES ' + rowNamesObject[rowName][1] + '(' + rowNamesObject[rowName][2] + ')';
            } else if(rowName.toLowerCase() === 'unique') {      // Handling UNIQUE KEYS
                attributes += ', UNIQUE (' + rowNamesObject[rowName].join(',') + ')';
            } else {
                if(attributes !== undefined) {
                    attributes += ', ' + rowName + ' ' + rowNamesObject[rowName].join(' ');
                } else {
                    var attributes = rowName + ' ' + rowNamesObject[rowName].join(' ');
                }
            }
        }
        sqlCreateQuery += tableName + ' (' + attributes + ') ENGINE=INNODB;';
        attributes = undefined;         // For next query
        this.exec_raw_query(sqlCreateQuery, function(createResponse) {
            return createResponse;
        });
    }
}<|endoftext|>


<commit_before>var dics_data = {
  'ar': require('../../i18n/ar.json'),
  'da': require('../../i18n/da.json'),
  'de': require('../../i18n/de.json'),
  'en': require('../../i18n/en.json'),
  'es': require('../../i18n/es.json'),
  'fr': require('../../i18n/fr-FR.json'),
  'fr-FR': require('../../i18n/fr-FR.json'),
  'he': require('../../i18n/he.json'),
  'it': require('../../i18n/it.json'),
  'ja': require('../../i18n/ja.json'),
  'nb-NO': require('../../i18n/nb-NO.json'),
  'nl': require('../../i18n/nl-NL.json'),
  'nl-NL': require('../../i18n/nl-NL.json'),
  'pt': require('../../i18n/pt.json'),
  'pt-BR': require('../../i18n/pt-BR.json'),
  'ru': require('../../i18n/ru.json'),
  'sv': require('../../i18n/sv.json'),
  'tlh': require('../../i18n/tlh.json'),
  'tr': require('../../i18n/tr.json'),
  'zh': require('../../i18n/zh.json'),
  'zh-TW': require('../../i18n/zh-TW.json')
};

var default_dict = dics_data['en'];

function findProp(o, s) {
    s = s.replace(/\[(\w+)\]/g, ':$1'); // convert indexes to properties
    s = s.replace(/^\:/, '');           // strip a leading dot
    var a = s.split(':');
    while (a.length) {
        var n = a.shift();
        if (n in o) {
            o = o[n];
        } else {
            return;
        }
    }
    return o;
}

function Dictionary (data) {
  this._data = data;
}

Dictionary.prototype.t = function (key) {
  return findProp(this._data, key) || findProp(default_dict, key);
};

module.exports.getDict = function ( langOrDict ) {

  if (!langOrDict) {
    return new Dictionary(default_dict);
  }

  if ( typeof langOrDict === 'string' ) {
    var dict = dics_data[langOrDict] || dics_data[langOrDict.split('-')[0]];
    return new Dictionary(dict);
  } else {
    return new Dictionary(langOrDict);
  }
};
<commit_msg>Add korean language<commit_after>var dics_data = {
  'ar': require('../../i18n/ar.json'),
  'da': require('../../i18n/da.json'),
  'de': require('../../i18n/de.json'),
  'en': require('../../i18n/en.json'),
  'es': require('../../i18n/es.json'),
  'fr': require('../../i18n/fr-FR.json'),
  'fr-FR': require('../../i18n/fr-FR.json'),
  'he': require('../../i18n/he.json'),
  'it': require('../../i18n/it.json'),
  'ja': require('../../i18n/ja.json'),
  'ko': require('../../i18n/ko.json'),
  'nb-NO': require('../../i18n/nb-NO.json'),
  'nl': require('../../i18n/nl-NL.json'),
  'nl-NL': require('../../i18n/nl-NL.json'),
  'pt': require('../../i18n/pt.json'),
  'pt-BR': require('../../i18n/pt-BR.json'),
  'ru': require('../../i18n/ru.json'),
  'sv': require('../../i18n/sv.json'),
  'tlh': require('../../i18n/tlh.json'),
  'tr': require('../../i18n/tr.json'),
  'zh': require('../../i18n/zh.json'),
  'zh-TW': require('../../i18n/zh-TW.json')
};

var default_dict = dics_data['en'];

function findProp(o, s) {
    s = s.replace(/\[(\w+)\]/g, ':$1'); // convert indexes to properties
    s = s.replace(/^\:/, '');           // strip a leading dot
    var a = s.split(':');
    while (a.length) {
        var n = a.shift();
        if (n in o) {
            o = o[n];
        } else {
            return;
        }
    }
    return o;
}

function Dictionary (data) {
  this._data = data;
}

Dictionary.prototype.t = function (key) {
  return findProp(this._data, key) || findProp(default_dict, key);
};

module.exports.getDict = function ( langOrDict ) {

  if (!langOrDict) {
    return new Dictionary(default_dict);
  }

  if ( typeof langOrDict === 'string' ) {
    var dict = dics_data[langOrDict] || dics_data[langOrDict.split('-')[0]];
    return new Dictionary(dict);
  } else {
    return new Dictionary(langOrDict);
  }
};
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var net = require('net'),
    http = require('http'),
    appRoot = process.cwd(),
    socketMedium = require(appRoot + '/api/services/socketMedium.js'),
    StringDecoder = require('string_decoder').StringDecoder,
    crypto = require('crypto');

/**
 * @param  {Sails} app
 * @return {Function}     [initialize]
 */
module.exports = function ToInitialize(app) {

  /**
   * This function is triggered when the hook is loaded.
   *
   * @param  {Function} done
   */

  return function initialize (done) {

    (function waitForOtherHooks(next){

      if (!app.hooks.http) {
        return next(console.log('Cannot use `sockets` hook without the `http` hook.'));
      }

      // If http hook is enabled, wait until the http hook is loaded
      // before trying to attach the socket.io server to our underlying
      // HTTP server.
      app.after('hook:http:loaded', function (){

        // Session hook is optional.
        if (app.hooks.session) {
          return app.after('hook:session:loaded', next);
        }
        return next();
      });
    })(function whenReady (err){
      if (err) return done(err);

      app.log.verbose('Preparing TCP...');

      // Get access to the http server instance in Sails
      //var sailsHttpServer = app.hooks.http.server;

      var sailsTcpServer = net.createServer(function (socket) {

        var salt = crypto.randomBytes(7).toString('hex');

        socket.on('data', function(chunk) {
          var ip = socket.remoteAddress,
              port = socket.remotePort,
              hex = chunk.toString('hex'),
              socketId = ip.split('.').join('') + port + salt;

          socket.id = socketId;
          socket.ip = ip;
          socket.port = port;

          console.log('CLIENT PORT: ', port);

          protocol.multiDecode(hex, function(responses){

            responses.forEach(function(response){

              if(response && response.hasOwnProperty('result') && response.result.command){
                console.log('COMMAND: ', response.result.command);
              }

              if(response !== 'Unknown first byte'){
                socket.result = {};
                var logData = response.data || response.result.data,
                    packetsNum = response.number_of_packets_contained_in_frame || response.result.number_of_packets_contained_in_frame,
                    dataLength = response.data_length || response.result.data_length,
                    opcode = response.opcode || response.result.opcode,
                    rotid = response.rotimatic_serial_number || response.result.rotimatic_serial_number,//check if exists
                    consoleId = response.QA_console_identifier || response.result.QA_console_identifier,
                    startIndex = response.starting_index_number || response.result.starting_index_number,
                    rotinum = response.number_of_rotimatics || response.result.number_of_rotimatics,
                    qaSessionRoti = response.serial_number || response.result.serial_number,
                    qaSessionNum = response.session_number || response.result.session_number;

                if(opcode){

                  if(rotid){
                    socket.rotimaticId = rotid;
                  }

                  socket.result.data = logData;
                  socket.result.dataLength = dataLength;
                  socket.result.packetsNum = packetsNum;

                  socket.qaIdentifier = consoleId;
                  socket.startIndex = startIndex;
                  socket.rotinum = rotinum;
                  socket.qaSessionNum = qaSessionNum;
                  socket.qaSessionRoti = qaSessionRoti;

                  if(response.callback){
                    response.callback(socket);
                    sails.io.emit(response.result.command, response.result);
                  }

                }

              }

            });

          });

        });

        socket.on('close', function(err){
          socketMedium.rTrigger('end' +  socket.id, socket);
          socketMedium.disconnect(['session', 'settings', 'end'], socket.id);
        });

        socket.on('error', function(err){
          console.log('SOCKET ERROR: ', err);
          /*socketMedium.rTrigger('end' +  socket.id, socket);
          socketMedium.disconnect(['session', 'settings', 'end'], socket.id);*/
        });

      });

      sailsTcpServer.listen(sails.config.tcp.port);

      done();

    });

  };
};
<commit_msg>combine to complete command<commit_after>/**
 * Module dependencies
 */
var net = require('net'),
    http = require('http'),
    appRoot = process.cwd(),
    socketMedium = require(appRoot + '/api/services/socketMedium.js'),
    StringDecoder = require('string_decoder').StringDecoder,
    crypto = require('crypto');

/**
 * @param  {Sails} app
 * @return {Function}     [initialize]
 */
module.exports = function ToInitialize(app) {

  /**
   * This function is triggered when the hook is loaded.
   *
   * @param  {Function} done
   */

  return function initialize (done) {

    (function waitForOtherHooks(next){

      if (!app.hooks.http) {
        return next(console.log('Cannot use `sockets` hook without the `http` hook.'));
      }

      // If http hook is enabled, wait until the http hook is loaded
      // before trying to attach the socket.io server to our underlying
      // HTTP server.
      app.after('hook:http:loaded', function (){

        // Session hook is optional.
        if (app.hooks.session) {
          return app.after('hook:session:loaded', next);
        }
        return next();
      });
    })(function whenReady (err){
      if (err) return done(err);

      app.log.verbose('Preparing TCP...');

      // Get access to the http server instance in Sails
      //var sailsHttpServer = app.hooks.http.server;

      var sailsTcpServer = net.createServer(function (socket) {

        var salt = crypto.randomBytes(7).toString('hex');

        socket.on('data', function(chunk) {
          var ip = socket.remoteAddress,
              port = socket.remotePort,
              hex = chunk.toString('hex'),
              odd,
              socketId = ip.split('.').join('') + port + salt;

          socket.id = socketId;
          socket.ip = ip;
          socket.port = port;

          console.log('CLIENT PORT: ', port);

          protocol.multiDecode({hex: hex, preframe: odd}, function(responses){

            var oddBytes = responses[responses.length - 1]['result']['bytes'];

            if(oddBytes && responses.length > 1){
              odd = oddBytes;
              console.log('ODD BYTES ::::: ', odd);

              processDecoded(responses, socket);

            }
            else if(oddBytes && responses.length === 1) {
              odd = oddBytes;
            } else {
              odd = undefined;

              processDecoded(responses, socket);

            }

          });

          function processDecoded(responses, socket){

              responses.forEach(function(response){

              if(response && response.hasOwnProperty('result') && response.result.command){
                console.log('COMMAND: ', response.result.command);
              }

              if(response !== 'Unknown first byte'){
                socket.result = {};
                var logData = response.data || response.result.data,
                    packetsNum = response.number_of_packets_contained_in_frame || response.result.number_of_packets_contained_in_frame,
                    dataLength = response.data_length || response.result.data_length,
                    opcode = response.opcode || response.result.opcode,
                    rotid = response.rotimatic_serial_number || response.result.rotimatic_serial_number,//check if exists
                    consoleId = response.QA_console_identifier || response.result.QA_console_identifier,
                    startIndex = response.starting_index_number || response.result.starting_index_number,
                    rotinum = response.number_of_rotimatics || response.result.number_of_rotimatics,
                    qaSessionRoti = response.serial_number || response.result.serial_number,
                    qaSessionNum = response.session_number || response.result.session_number;

                if(opcode){

                  if(rotid){
                    socket.rotimaticId = rotid;
                  }

                  socket.result.data = logData;
                  socket.result.dataLength = dataLength;
                  socket.result.packetsNum = packetsNum;

                  socket.qaIdentifier = consoleId;
                  socket.startIndex = startIndex;
                  socket.rotinum = rotinum;
                  socket.qaSessionNum = qaSessionNum;
                  socket.qaSessionRoti = qaSessionRoti;

                  if(response.callback){
                    response.callback(socket);
                    sails.io.emit(response.result.command, response.result);
                  }

                }

              }

            });

          }

        });

        socket.on('close', function(err){
          socketMedium.rTrigger('end' +  socket.id, socket);
          socketMedium.disconnect(['session', 'settings', 'end'], socket.id);
        });

        socket.on('error', function(err){
          console.log('SOCKET ERROR: ', err);
          /*socketMedium.rTrigger('end' +  socket.id, socket);
          socketMedium.disconnect(['session', 'settings', 'end'], socket.id);*/
        });

      });

      sailsTcpServer.listen(sails.config.tcp.port);

      done();

    });

  };
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes, Text, View, Animated } from 'react-native';
import { getColor } from './helpers';

export default class IconToggle extends Component {

    constructor(props) {
        super(props);
        this.state = {
            scaleValue: new Animated.Value(0.001),
            opacityValue: new Animated.Value(0.1),
            maxOpacity: props.opacity,
            size: null
        };
        this._responder = {
            onStartShouldSetResponder: (e) => true,
            onResponderGrant: this._highlight,
            onResponderRelease: this._handleResponderEnd,
            onResponderTerminate: this._unHighlight
        };
    }

    componentDidUpdate(prevProps) {
        if (this.props && this.props.badge) {
            if (this.props.badge.value !== prevProps.badge.value) {
                this._animateBadgeCounter();
            }
        }
    };

    static propTypes = {
        color: PropTypes.string.isRequired,
        opacity: PropTypes.number,
        disabled: PropTypes.bool,
        onPress: PropTypes.func,
        percent: PropTypes.number,
        children: PropTypes.element.isRequired,
        badge: PropTypes.shape({
            value: PropTypes.number,
            animate: PropTypes.bool,
            backgroundColor: PropTypes.string,
            textColor: PropTypes.string
        })
    };

    static defaultProps = {
        opacity: .1,
        disabled: false,
        percent: 90
    };

    setSize = (event) => {
        const { width, height } = event.nativeEvent.layout;

        this.setState({
            size: width > height ? width : height
        });
    };

    render() {
        const { scaleValue, opacityValue, size } = this.state;
        const { color, children } = this.props;

        let { badge } = this.props;
        let { percent } = this.props;

        if (percent < 0) {
            percent = 0;
        }
        if (percent > 100) {
            percent = 100;
        }

        percent = percent / 100;

        if (badge && typeof badge.value === 'number') {
            badge = Object.assign({},
                {value: badge.value},
                badge.backgroundColor ? {backgroundColor: badge.backgroundColor} : {backgroundColor: 'paperRed'},
                badge.textColor ? {textColor: badge.textColor} : {textColor: '#ffffff'}
            );
        }

        this.badgeAnim = this.badgeAnim || new Animated.Value(0);

        return (
            <View {...this._responder}>
                <View>
                    {size &&
                    <Animated.View
                        style={[{
                                position: 'absolute',
                                left: ((1 - percent) * size) / 2,
                                top: ((1 - percent) * size) / 2,
                                width: percent * size,
                                height: percent * size,
                                borderRadius: percent * size / 2,
                                transform: [{ scale: scaleValue }],
                                opacity: opacityValue,
                                backgroundColor: getColor(color)
                            }]}
                    />
                    }
                    <View onLayout={(event) => { this.setSize(event) }}>
                        {children}
                    </View>
                    {size && badge && typeof badge.value === 'number' &&
                    <Animated.View style={[
                            styles.badgeContainer, {
                                backgroundColor: getColor(badge.backgroundColor),
                                top: size / 10,
                                right: size / 10,
                                transform: [   // Array order matters
								{scale: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [1, 1.7]
								})},
								{translateX: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [0, -12]
								})},
								{translateY: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [0, 10]
								})},
								{rotate: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [
									'0deg', '45deg' // 'deg' or 'rad'
								  ]
								})}
							  ]
                            }]}
                    >
                        <Text style={[styles.badgeText, { color: getColor(badge.textColor) }]}>
                            {badge.value}
                        </Text>
                    </Animated.View>
                    }
                </View>
            </View>
        );
    };

    /**
     *
     * @private
     */
    _highlight = () => {
        if (!this.props.disabled) {
            Animated.timing(this.state.scaleValue, {
                toValue: 1,
                duration: 150
            }).start();
            Animated.timing(this.state.opacityValue, {
                toValue: this.state.maxOpacity,
                duration: 100
            }).start();
        }
    };

    /**
     *
     * @private
     */
    _unHighlight = () => {
        if (!this.props.disabled) {
            Animated.timing(this.state.scaleValue, {
                toValue: 0.001,
                duration: 1500
            }).start();
            Animated.timing(this.state.opacityValue, {
                toValue: 0
            }).start();
        }
    };

    /**
     *
     * @private
     */
    _animateBadgeCounter = () => {
        if (this.badgeAnim && this.props.badge && this.props.badge.animate !== false) {
            Animated.spring(this.badgeAnim, {
                toValue: 0,   // Returns to the start
                velocity: 8,  // Velocity makes it move
                tension: -5, // Slow
                friction: 1,  // Oscillate a lot
                duration: 300
            }).start();
        }
    };

    /**
     *
     * @private
     */
    _handleResponderEnd = () => {
        const { disabled, onPress } = this.props;

        if (!disabled) {
            this._unHighlight();
            onPress && onPress();
        }
    };
}

const styles = {
    badgeContainer: {
        position: 'absolute',
        borderRadius: 7,
        width: 15,
        height: 15
    },
    badgeText: {
        lineHeight: 10,
        textAlign: 'center',
        fontSize: 10,
        paddingTop: 8
    }
};<commit_msg>Tweaked toggle anim<commit_after>import React, { Component, PropTypes, Text, View, Animated } from 'react-native';
import { getColor } from './helpers';

export default class IconToggle extends Component {

    constructor(props) {
        super(props);
        this.state = {
            scaleValue: new Animated.Value(0.001),
            opacityValue: new Animated.Value(0.1),
            maxOpacity: props.opacity,
            size: null
        };
        this._responder = {
            onStartShouldSetResponder: (e) => true,
            onResponderGrant: this._highlight,
            onResponderRelease: this._handleResponderEnd,
            onResponderTerminate: this._unHighlight
        };
    }

    componentDidUpdate(prevProps) {
        if (this.props && this.props.badge) {
            if (this.props.badge.value !== prevProps.badge.value) {
                this._animateBadgeCounter();
            }
        }
    };

    static propTypes = {
        color: PropTypes.string.isRequired,
        opacity: PropTypes.number,
        disabled: PropTypes.bool,
        onPress: PropTypes.func,
        percent: PropTypes.number,
        children: PropTypes.element.isRequired,
        badge: PropTypes.shape({
            value: PropTypes.number,
            animate: PropTypes.bool,
            backgroundColor: PropTypes.string,
            textColor: PropTypes.string
        })
    };

    static defaultProps = {
        opacity: .1,
        disabled: false,
        percent: 90
    };

    setSize = (event) => {
        const { width, height } = event.nativeEvent.layout;

        this.setState({
            size: width > height ? width : height
        });
    };

    render() {
        const { scaleValue, opacityValue, size } = this.state;
        const { color, children } = this.props;

        let { badge } = this.props;
        let { percent } = this.props;

        if (percent < 0) {
            percent = 0;
        }
        if (percent > 100) {
            percent = 100;
        }

        percent = percent / 100;

        if (badge && typeof badge.value === 'number') {
            badge = Object.assign({},
                {value: badge.value},
                badge.backgroundColor ? {backgroundColor: badge.backgroundColor} : {backgroundColor: 'paperRed'},
                badge.textColor ? {textColor: badge.textColor} : {textColor: '#ffffff'}
            );
        }

        this.badgeAnim = this.badgeAnim || new Animated.Value(0);

        return (
            <View {...this._responder}>
                <View>
                    {size &&
                    <Animated.View
                        style={[{
                                position: 'absolute',
                                left: ((1 - percent) * size) / 2,
                                top: ((1 - percent) * size) / 2,
                                width: percent * size,
                                height: percent * size,
                                borderRadius: percent * size / 2,
                                transform: [{ scale: scaleValue }],
                                opacity: opacityValue,
                                backgroundColor: getColor(color)
                            }]}
                    />
                    }
                    <View onLayout={(event) => { this.setSize(event) }}>
                        {children}
                    </View>
                    {size && badge && typeof badge.value === 'number' &&
                    <Animated.View style={[
                            styles.badgeContainer, {
                                backgroundColor: getColor(badge.backgroundColor),
                                top: size / 10,
                                right: size / 10,
                                transform: [   // Array order matters
								{scale: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [1, 1.25]
								})},
								{translateX: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [0, -6]
								})},
								{translateY: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [0, 5]
								})},
								{rotate: this.badgeAnim.interpolate({
								  inputRange: [0, 1],
								  outputRange: [
									'0deg', '45deg' // 'deg' or 'rad'
								  ]
								})}
							  ]
                            }]}
                    >
                        <Text style={[styles.badgeText, { color: getColor(badge.textColor) }]}>
                            {badge.value}
                        </Text>
                    </Animated.View>
                    }
                </View>
            </View>
        );
    };

    /**
     *
     * @private
     */
    _highlight = () => {
        if (!this.props.disabled) {
            Animated.timing(this.state.scaleValue, {
                toValue: 1,
                duration: 150
            }).start();
            Animated.timing(this.state.opacityValue, {
                toValue: this.state.maxOpacity,
                duration: 100
            }).start();
        }
    };

    /**
     *
     * @private
     */
    _unHighlight = () => {
        if (!this.props.disabled) {
            Animated.timing(this.state.scaleValue, {
                toValue: 0.001,
                duration: 1500
            }).start();
            Animated.timing(this.state.opacityValue, {
                toValue: 0
            }).start();
        }
    };

    /**
     *
     * @private
     */
    _animateBadgeCounter = () => {
        if (this.badgeAnim && this.props.badge && this.props.badge.animate !== false) {
            Animated.spring(this.badgeAnim, {
                toValue: 0,   // Returns to the start
                velocity: 8,  // Velocity makes it move
                tension: -5, // Slow
                friction: 1,  // Oscillate a lot
                duration: 300
            }).start();
        }
    };

    /**
     *
     * @private
     */
    _handleResponderEnd = () => {
        const { disabled, onPress } = this.props;

        if (!disabled) {
            this._unHighlight();
            onPress && onPress();
        }
    };
}

const styles = {
    badgeContainer: {
        position: 'absolute',
        borderRadius: 7,
        width: 15,
        height: 15
    },
    badgeText: {
        lineHeight: 10,
        textAlign: 'center',
        fontSize: 10,
        paddingTop: 8
    }
};<|endoftext|>


<commit_before>var request = require('superagent');

module.exports = function(Model,options){

  var RestModel = Model.subclass();

  options = options || {};
  if(!options.idKey) options.idKey = '_id';

  RestModel.baseURL = options.baseURL;
  var idKey = options.idKey;
  var collection = RestModel.prototype.collection;

  var getURL = function(url){
    if(!RestModel.baseURL) return url;
    url = url.replace(/^\//,'');
    return RestModel.baseURL.replace(/\/*$/,'/') + url;
  }

  var handleResponse = function(err,res,callback,type){
    err = err || res.error || (res.body && res.body.error);
    if(err) return callback(err);
    var resp;
    switch(type){
      case 'array' :
        resp = res.body[collection].map(function(i){
          return new RestModel(i);
        });
        break;
      case 'raw' :
        resp = res.body;
        break;
      default :
        resp = new RestModel(res.body);
        break;
      }
      callback(null,resp);
    };

  RestModel.all = function(callback){
    request
    .get(getURL(collection))
    .end(function(err,res){
      handleResponse(err,res,callback,'array');
    });
  };
  RestModel.one = function(id,callback){
    request
    .get(getURL(collection + '/' + id))
    .end(function(err,res){
      handleResponse(err,res,callback);
    });
  };
  RestModel.prototype.save = function(callback){
    var data = this.toObject();
    var method = !!data[idKey] ? 'put' : 'post';
    request[method](getURL(collection + (data[idKey] ? '/' + data[idKey] : '')))
    .send(data)
    .end(function(err,res){
      handleResponse(err,res,callback);
    });
  };
  RestModel.prototype.destroy = function(callback){
    var data = this.toObject();
    request
    .del(getURL(collection + '/' + data[idKey]))
    .end(function(err,res){
      handleResponse(err,res,callback,'raw');
    });
  };

  return RestModel;
};
<commit_msg>expose id key<commit_after>var request = require('superagent');

module.exports = function(Model,options){

  var RestModel = Model.subclass();

  options = options || {};
  if(!options.idKey) options.idKey = '_id';

  RestModel.baseURL = options.baseURL;
  var idKey = options.idKey;
  var collection = RestModel.prototype.collection;

  var getURL = function(url){
    if(!RestModel.baseURL) return url;
    url = url.replace(/^\//,'');
    return RestModel.baseURL.replace(/\/*$/,'/') + url;
  }

  var handleResponse = function(err,res,callback,type){
    err = err || res.error || (res.body && res.body.error);
    if(err) return callback(err);
    var resp;
    switch(type){
      case 'array' :
        resp = res.body[collection].map(function(i){
          return new RestModel(i);
        });
        break;
      case 'raw' :
        resp = res.body;
        break;
      default :
        resp = new RestModel(res.body);
        break;
      }
      callback(null,resp);
    };

  RestModel.all = function(callback){
    request
    .get(getURL(collection))
    .end(function(err,res){
      handleResponse(err,res,callback,'array');
    });
  };
  RestModel.one = function(id,callback){
    request
    .get(getURL(collection + '/' + id))
    .end(function(err,res){
      handleResponse(err,res,callback);
    });
  };
  RestModel.prototype.save = function(callback){
    var data = this.toObject();
    var method = !!data[idKey] ? 'put' : 'post';
    request[method](getURL(collection + (data[idKey] ? '/' + data[idKey] : '')))
    .send(data)
    .end(function(err,res){
      handleResponse(err,res,callback);
    });
  };
  RestModel.prototype.destroy = function(callback){
    var data = this.toObject();
    request
    .del(getURL(collection + '/' + data[idKey]))
    .end(function(err,res){
      handleResponse(err,res,callback,'raw');
    });
  };

  RestModel.idKey = idKey;

  return RestModel;
};
<|endoftext|>


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

module.exports = PoolConfig;
function PoolConfig(options) {
  this.connectionConfig   = new ConnectionConfig(options);
  this.createConnection   = options.createConnection || undefined;
  this.waitForConnections = options.waitForConnections || true;
  this.connectionLimit    = (options.connectionLimit === undefined)
    ? 10
    : Number(options.connectionLimit)
}
<commit_msg>Fixed defaulting the waitForConnections config option<commit_after>
var ConnectionConfig = require('./ConnectionConfig');

module.exports = PoolConfig;
function PoolConfig(options) {
  this.connectionConfig   = new ConnectionConfig(options);
  this.createConnection   = options.createConnection || undefined;
  this.waitForConnections = (options.waitForConnections === undefined)
    ? true
    : Boolean(options.waitForConnections);
  this.connectionLimit    = (options.connectionLimit === undefined)
    ? 10
    : Number(options.connectionLimit);
}
<|endoftext|>