Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created August 18, 2015 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/2e56b4b81b3f4e99d610 to your computer and use it in GitHub Desktop.
Save tmcw/2e56b4b81b3f4e99d610 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<style>html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
body {
background-color: #222;
color: #D1D1D1;
font-family: "Fira Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
}
#container {
overflow: auto;
height: 100%;
}
#output {
padding: 10px;
}
pre {
margin: 0;
font-family: "Fira Mono", "Source Code Pro", Consolas, Menlo, monospace;
}
.error {
color: #D03535;
}
.warn {
color: #D0A135;
}
input {
margin-left: 10px;
margin-top: 10px;
}
/* Use :not to prevent IE8 from hiding all the messages */
#log-filter:not(:checked) ~ #output .log,
#debug-filter:not(:checked) ~ #output .debug,
#warning-filter:not(:checked) ~ #output .warn,
#error-filter:not(:checked) ~ #output .error {
display: none;
}
#log-filter:checked ~ #output .log,
#debug-filter:checked ~ #output .debug,
#warning-filter:checked ~ #output .warn,
#error-filter:checked ~ #output .error {
display: block;
}
</style>
</head>
<div id="container">
<input id="log-filter" type="checkbox" checked><label for="log-filter">Log</label>
<input id="debug-filter" type="checkbox" checked><label for="debug-filter">Debug</label>
<input id="warning-filter" type="checkbox" checked><label for="warning-filter">Warning</label>
<input id="error-filter" type="checkbox" checked><label for="error-filter">Errors</label>
<div id="output"></div>
</div>
<script>(function() {
var container = document.getElementById('container'),
output = document.getElementById('output'),
console = (window.console || (window.console = {}));
function bind(func, context) {
if (typeof func.bind === 'function') {
// ES5 browsers
return func.bind(context);
} else if (typeof func.apply === 'function') {
// Pre-ES5 browsers
return function() { func.apply(context, arguments); };
} else {
// Old IE doesn't care about context
// and has no `.apply` on native functions
return func;
}
}
function logger(type, oldLog) {
oldLog = bind(oldLog || function() { }, console);
return function() {
var isScrolled = (container.scrollTop ===
(container.scrollHeight - container.offsetHeight));
var message = Array.prototype.join.call(arguments, ' ');
oldLog(message);
var node = document.createElement('pre');
node.className = type;
node.appendChild(document.createTextNode(message));
output.appendChild(node);
output.appendChild(document.createTextNode('\r\n'));
// Scroll to bottom if it was previously scrolled to the bottom
if (isScrolled) {
container.scrollTop = container.scrollHeight - container.offsetHeight;
}
};
}
console.log = logger('log', console.log);
console.debug = logger('debug', console.debug);
console.info = logger('info', console.info);
console.warn = logger('warn', console.warn);
console.error = logger('error', console.error);
})();
</script>
<script src="script.js"></script>
</html>
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
// # simple-statistics
//
// A simple, literate statistics system.
var ss = module.exports = {};
// Linear Regression
ss.linearRegression = require('./src/linear_regression');
ss.linearRegressionLine = require('./src/linear_regression_line');
ss.standardDeviation = require('./src/standard_deviation');
ss.rSquared = require('./src/r_squared');
ss.mode = require('./src/mode');
ss.min = require('./src/min');
ss.max = require('./src/max');
ss.sum = require('./src/sum');
ss.quantile = require('./src/quantile');
ss.quantileSorted = require('./src/quantile_sorted');
ss.iqr = ss.interquartileRange = require('./src/interquartile_range');
ss.medianAbsoluteDeviation = ss.mad = require('./src/mad');
ss.chunk = require('./src/chunk');
ss.shuffle = require('./src/shuffle');
ss.shuffleInPlace = require('./src/shuffle_in_place');
ss.sample = require('./src/sample');
ss.ckmeans = require('./src/ckmeans');
ss.sortedUniqueCount = require('./src/sorted_unique_count');
ss.sumNthPowerDeviations = require('./src/sum_nth_power_deviations');
// sample statistics
ss.sampleCovariance = require('./src/sample_covariance');
ss.sampleCorrelation = require('./src/sample_correlation');
ss.sampleVariance = require('./src/sample_variance');
ss.sampleStandardDeviation = require('./src/sample_standard_deviation');
ss.sampleSkewness = require('./src/sample_skewness');
// measures of centrality
ss.geometricMean = require('./src/geometric_mean');
ss.harmonicMean = require('./src/harmonic_mean');
ss.mean = ss.average = require('./src/mean');
ss.median = require('./src/median');
ss.rootMeanSquare = ss.rms = require('./src/root_mean_square');
ss.variance = require('./src/variance');
ss.tTest = require('./src/t_test');
ss.tTestTwoSample = require('./src/t_test_two_sample');
// ss.jenks = require('./src/jenks');
// Classifiers
ss.bayesian = require('./src/bayesian_classifier');
ss.perceptron = require('./src/perceptron');
// Distribution-related methods
ss.epsilon = require('./src/epsilon'); // We make ε available to the test suite.
ss.factorial = require('./src/factorial');
ss.bernoulliDistribution = require('./src/bernoulli_distribution');
ss.binomialDistribution = require('./src/binomial_distribution');
ss.poissonDistribution = require('./src/poisson_distribution');
ss.chiSquaredGoodnessOfFit = require('./src/chi_squared_goodness_of_fit');
// Normal distribution
ss.zScore = require('./src/z_score');
ss.cumulativeStdNormalProbability = require('./src/cumulative_std_normal_probability');
ss.standardNormalTable = require('./src/standard_normal_table');
ss.errorFunction = ss.erf = require('./src/error_function');
ss.inverseErrorFunction = require('./src/inverse_error_function');
ss.probit = require('./src/probit');
ss.mixin = require('./src/mixin');
},{"./src/bayesian_classifier":40,"./src/bernoulli_distribution":41,"./src/binomial_distribution":42,"./src/chi_squared_goodness_of_fit":44,"./src/chunk":45,"./src/ckmeans":46,"./src/cumulative_std_normal_probability":47,"./src/epsilon":48,"./src/error_function":50,"./src/factorial":51,"./src/geometric_mean":52,"./src/harmonic_mean":53,"./src/interquartile_range":54,"./src/inverse_error_function":55,"./src/linear_regression":56,"./src/linear_regression_line":57,"./src/mad":58,"./src/max":59,"./src/mean":60,"./src/median":61,"./src/min":62,"./src/mixin":63,"./src/mode":64,"./src/perceptron":66,"./src/poisson_distribution":67,"./src/probit":68,"./src/quantile":69,"./src/quantile_sorted":70,"./src/r_squared":71,"./src/root_mean_square":72,"./src/sample":73,"./src/sample_correlation":74,"./src/sample_covariance":75,"./src/sample_skewness":76,"./src/sample_standard_deviation":77,"./src/sample_variance":78,"./src/shuffle":79,"./src/shuffle_in_place":80,"./src/sorted_unique_count":81,"./src/standard_deviation":82,"./src/standard_normal_table":83,"./src/sum":84,"./src/sum_nth_power_deviations":85,"./src/t_test":86,"./src/t_test_two_sample":87,"./src/variance":88,"./src/z_score":89}],2:[function(require,module,exports){
},{}],3:[function(require,module,exports){
arguments[4][2][0].apply(exports,arguments)
},{"dup":2}],4:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
* on objects.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
function Bar () {}
try {
var arr = new Uint8Array(1)
arr.foo = function () { return 42 }
arr.constructor = Bar
return arr.foo() === 42 && // typed array instances can be augmented
arr.constructor === Bar && // constructor can be set
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (arg) {
if (!(this instanceof Buffer)) {
// Avoid going through an ArgumentsAdaptorTrampoline in the common case.
if (arguments.length > 1) return new Buffer(arg, arguments[1])
return new Buffer(arg)
}
this.length = 0
this.parent = undefined
// Common case.
if (typeof arg === 'number') {
return fromNumber(this, arg)
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
}
// Unusual.
return fromObject(this, arg)
}
function fromNumber (that, length) {
that = allocate(that, length < 0 ? 0 : checked(length) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < length; i++) {
that[i] = 0
}
}
return that
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
// Assumption: byteLength() return value is always < kMaxLength.
var length = byteLength(string, encoding) | 0
that = allocate(that, length)
that.write(string, encoding)
return that
}
function fromObject (that, object) {
if (Buffer.isBuffer(object)) return fromBuffer(that, object)
if (isArray(object)) return fromArray(that, object)
if (object == null) {
throw new TypeError('must start with number, buffer, array or string')
}
if (typeof ArrayBuffer !== 'undefined') {
if (object.buffer instanceof ArrayBuffer) {
return fromTypedArray(that, object)
}
if (object instanceof ArrayBuffer) {
return fromArrayBuffer(that, object)
}
}
if (object.length) return fromArrayLike(that, object)
return fromJsonObject(that, object)
}
function fromBuffer (that, buffer) {
var length = checked(buffer.length) | 0
that = allocate(that, length)
buffer.copy(that, 0, 0, length)
return that
}
function fromArray (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
// Duplicate of fromArray() to keep fromArray() monomorphic.
function fromTypedArray (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
// Truncating the elements is probably not what people expect from typed
// arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
// of the old Buffer constructor.
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array) {
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
array.byteLength
that = Buffer._augment(new Uint8Array(array))
} else {
// Fallback: Return an object instance of the Buffer class
that = fromTypedArray(that, new Uint8Array(array))
}
return that
}
function fromArrayLike (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
// Returns a zero-length buffer for inputs that don't conform to the spec.
function fromJsonObject (that, object) {
var array
var length = 0
if (object.type === 'Buffer' && isArray(object.data)) {
array = object.data
length = checked(array.length) | 0
}
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function allocate (that, length) {
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = Buffer._augment(new Uint8Array(length))
} else {
// Fallback: Return an object instance of the Buffer class
that.length = length
that._isBuffer = true
}
var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
if (fromPool) that.parent = rootParent
return that
}
function checked (length) {
// Note: cannot use `length < kMaxLength` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (subject, encoding) {
if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
var buf = new Buffer(subject, encoding)
delete buf.parent
return buf
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
var i = 0
var len = Math.min(x, y)
while (i < len) {
if (a[i] !== b[i]) break
++i
}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; i++) {
length += list[i].length
}
}
var buf = new Buffer(length)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
function byteLength (string, encoding) {
if (typeof string !== 'string') string = '' + string
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'binary':
// Deprecated
case 'raw':
case 'raws':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
function slowToString (encoding, start, end) {
var loweredCase = false
start = start | 0
end = end === undefined || end === Infinity ? this.length : end | 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return 0
return Buffer.compare(this, b)
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
else if (byteOffset < -0x80000000) byteOffset = -0x80000000
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
if (val.length === 0) return -1 // special case: looking for empty string always fails
return String.prototype.indexOf.call(this, val, byteOffset)
}
if (Buffer.isBuffer(val)) {
return arrayIndexOf(this, val, byteOffset)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset)
}
function arrayIndexOf (arr, val, byteOffset) {
var foundIndex = -1
for (var i = 0; byteOffset + i < arr.length; i++) {
if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
} else {
foundIndex = -1
}
}
return -1
}
throw new TypeError('val must be string, number or Buffer')
}
// `get` is deprecated
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` is deprecated
Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) throw new Error('Invalid hex string')
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
var swap = encoding
encoding = offset
offset = length | 0
length = swap
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'binary':
return binaryWrite(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var firstByte
var secondByte
var thirdByte
var fourthByte
var bytesPerSequence
var tempCodePoint
var codePoint
var res = []
var i = start
for (; i < end; i += bytesPerSequence) {
firstByte = buf[i]
codePoint = 0xFFFD
if (firstByte > 0xEF) {
bytesPerSequence = 4
} else if (firstByte > 0xDF) {
bytesPerSequence = 3
} else if (firstByte > 0xBF) {
bytesPerSequence = 2
} else {
bytesPerSequence = 1
}
if (i + bytesPerSequence <= end) {
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === 0xFFFD) {
// we generated an invalid codePoint so make sure to only advance by 1 byte
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
}
return String.fromCharCode.apply(String, res)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
if (newBuf.length) newBuf.parent = this.parent || this
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; i--) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; i++) {
target[i + targetStart] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), targetStart)
}
return len
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array set method before overwriting
arr._set = arr.set
// deprecated
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUIntLE = BP.readUIntLE
arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readIntLE = BP.readIntLE
arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUIntLE = BP.writeUIntLE
arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeIntLE = BP.writeIntLE
arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
},{"base64-js":5,"ieee754":6,"is-array":7}],5:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],6:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],7:[function(require,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],8:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],9:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],10:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],11:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require('_process'))
},{"_process":12}],12:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],13:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":14}],14:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
forEach(objectKeys(Writable.prototype), function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(this.end.bind(this));
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
}).call(this,require('_process'))
},{"./_stream_readable":16,"./_stream_writable":18,"_process":12,"core-util-is":19,"inherits":9}],15:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":17,"core-util-is":19,"inherits":9}],16:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
var Stream = require('stream');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var StringDecoder;
/*<replacement>*/
var debug = require('util');
if (debug && debug.debuglog) {
debug = debug.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.readableObjectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
var Duplex = require('./_stream_duplex');
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (util.isString(chunk) && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (util.isNullOrUndefined(chunk)) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
if (!addToFront)
state.reading = false;
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront)
state.buffer.unshift(chunk);
else
state.buffer.push(chunk);
if (state.needReadable)
emitReadable(stream);
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (isNaN(n) || util.isNull(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
debug('read', n);
var state = this._readableState;
var nOrig = n;
if (!util.isNumber(n) || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended)
endReadable(this);
else
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0)
endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
}
if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (doRead && !state.reading)
n = howMuchToRead(nOrig, state);
var ret;
if (n > 0)
ret = fromList(n, state);
else
ret = null;
if (util.isNull(ret)) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended)
state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended && state.length === 0)
endReadable(this);
if (!util.isNull(ret))
this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync)
process.nextTick(function() {
emitReadable_(stream);
});
else
emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
process.nextTick(function() {
maybeReadMore_(stream, state);
});
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended &&
state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
else
len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function(dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
dest !== process.stdout &&
dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted)
process.nextTick(endFn);
else
src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain &&
(!dest._writableState || dest._writableState.needDrain))
ondrain();
}
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
if (false === ret) {
debug('false write response, pause',
src._readableState.awaitDrain);
src._readableState.awaitDrain++;
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
}
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS.
if (!dest._events || !dest._events.error)
dest.on('error', onerror);
else if (isArray(dest._events.error))
dest._events.error.unshift(onerror);
else
dest._events.error = [onerror, dest._events.error];
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function() {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain)
state.awaitDrain--;
if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function(dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0)
return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes)
return this;
if (!dest)
dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest)
dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++)
dests[i].emit('unpipe', this);
return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1)
return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1)
state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
// If listening to data, and it has not explicitly been paused,
// then call resume to start the flow of data on the next tick.
if (ev === 'data' && false !== this._readableState.flowing) {
this.resume();
}
if (ev === 'readable' && this.readable) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
var self = this;
process.nextTick(function() {
debug('readable nexttick read 0');
self.read(0);
});
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
if (!state.reading) {
debug('resume read 0');
this.read(0);
}
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
process.nextTick(function() {
resume_(stream, state);
});
}
}
function resume_(stream, state) {
state.resumeScheduled = false;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading)
stream.read(0);
}
Readable.prototype.pause = function() {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
if (state.flowing) {
do {
var chunk = stream.read();
} while (null !== chunk && state.flowing);
}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function() {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length)
self.push(chunk);
}
self.push(null);
});
stream.on('data', function(chunk) {
debug('wrapped data');
if (state.decoder)
chunk = state.decoder.write(chunk);
if (!chunk || !state.objectMode && !chunk.length)
return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments);
}}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function(ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function(n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0)
return null;
if (length === 0)
ret = null;
else if (objectMode)
ret = list.shift();
else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
else
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
if (stringMode)
ret = '';
else
ret = new Buffer(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var buf = list[0];
var cpy = Math.min(n - c, buf.length);
if (stringMode)
ret += buf.slice(0, cpy);
else
buf.copy(ret, c, 0, cpy);
if (cpy < buf.length)
list[0] = buf.slice(cpy);
else
list.shift();
c += cpy;
}
}
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0)
throw new Error('endReadable called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
process.nextTick(function() {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
});
}
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf (xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":14,"_process":12,"buffer":4,"core-util-is":19,"events":8,"inherits":9,"isarray":10,"stream":24,"string_decoder/":25,"util":3}],17:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (!util.isNullOrUndefined(data))
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('prefinish', function() {
if (util.isFunction(this._flush))
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":14,"core-util-is":19,"inherits":9}],18:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.writableObjectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (util.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (!util.isFunction(cb))
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function() {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function() {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing &&
!state.corked &&
!state.finished &&
!state.bufferProcessing &&
state.buffer.length)
clearBuffer(this, state);
}
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
util.isString(chunk)) {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev)
stream._writev(chunk, state.onwrite);
else
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
state.pendingcb--;
cb(er);
});
else {
state.pendingcb--;
cb(er);
}
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished &&
!state.corked &&
!state.bufferProcessing &&
state.buffer.length) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
if (stream._writev && state.buffer.length > 1) {
// Fast case, write everything using _writev()
var cbs = [];
for (var c = 0; c < state.buffer.length; c++)
cbs.push(state.buffer[c].callback);
// count the one we are adding, as well.
// TODO(isaacs) clean this up
state.pendingcb++;
doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
for (var i = 0; i < cbs.length; i++) {
state.pendingcb--;
cbs[i](err);
}
});
// Clear buffer
state.buffer = [];
} else {
// Slow case, write chunks one-by-one
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
state.bufferProcessing = false;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (util.isFunction(chunk)) {
cb = chunk;
chunk = null;
encoding = null;
} else if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (!util.isNullOrUndefined(chunk))
this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else
prefinish(stream, state);
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
process.nextTick(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
}).call(this,require('_process'))
},{"./_stream_duplex":14,"_process":12,"buffer":4,"core-util-is":19,"inherits":9,"stream":24}],19:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,require("buffer").Buffer)
},{"buffer":4}],20:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":15}],21:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = require('stream');
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":14,"./lib/_stream_passthrough.js":15,"./lib/_stream_readable.js":16,"./lib/_stream_transform.js":17,"./lib/_stream_writable.js":18,"stream":24}],22:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":17}],23:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":18}],24:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":8,"inherits":9,"readable-stream/duplex.js":13,"readable-stream/passthrough.js":20,"readable-stream/readable.js":21,"readable-stream/transform.js":22,"readable-stream/writable.js":23}],25:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":4}],26:[function(require,module,exports){
/*jshint eqnull:true*/
(function (root) {
"use strict";
var GLOBAL_KEY = "Random";
var imul = (typeof Math.imul !== "function" || Math.imul(0xffffffff, 5) !== -5 ?
function (a, b) {
var ah = (a >>> 16) & 0xffff;
var al = a & 0xffff;
var bh = (b >>> 16) & 0xffff;
var bl = b & 0xffff;
// the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0;
} :
Math.imul);
var stringRepeat = (typeof String.prototype.repeat === "function" && "x".repeat(3) === "xxx" ?
function (x, y) {
return x.repeat(y);
} : function (pattern, count) {
var result = "";
while (count > 0) {
if (count & 1) {
result += pattern;
}
count >>= 1;
pattern += pattern;
}
return result;
});
function Random(engine) {
if (!(this instanceof Random)) {
return new Random(engine);
}
if (engine == null) {
engine = Random.engines.nativeMath;
} else if (typeof engine !== "function") {
throw new TypeError("Expected engine to be a function, got " + typeof engine);
}
this.engine = engine;
}
var proto = Random.prototype;
Random.engines = {
nativeMath: function () {
return (Math.random() * 0x100000000) | 0;
},
mt19937: (function (Int32Array) {
// http://en.wikipedia.org/wiki/Mersenne_twister
function refreshData(data) {
var k = 0;
var tmp = 0;
for (;
(k | 0) < 227; k = (k + 1) | 0) {
tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);
data[k] = data[(k + 397) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);
}
for (;
(k | 0) < 623; k = (k + 1) | 0) {
tmp = (data[k] & 0x80000000) | (data[(k + 1) | 0] & 0x7fffffff);
data[k] = data[(k - 227) | 0] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);
}
tmp = (data[623] & 0x80000000) | (data[0] & 0x7fffffff);
data[623] = data[396] ^ (tmp >>> 1) ^ ((tmp & 0x1) ? 0x9908b0df : 0);
}
function temper(value) {
value ^= value >>> 11;
value ^= (value << 7) & 0x9d2c5680;
value ^= (value << 15) & 0xefc60000;
return value ^ (value >>> 18);
}
function seedWithArray(data, source) {
var i = 1;
var j = 0;
var sourceLength = source.length;
var k = Math.max(sourceLength, 624) | 0;
var previous = data[0] | 0;
for (;
(k | 0) > 0; --k) {
data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x0019660d)) + (source[j] | 0) + (j | 0)) | 0;
i = (i + 1) | 0;
++j;
if ((i | 0) > 623) {
data[0] = data[623];
i = 1;
}
if (j >= sourceLength) {
j = 0;
}
}
for (k = 623;
(k | 0) > 0; --k) {
data[i] = previous = ((data[i] ^ imul((previous ^ (previous >>> 30)), 0x5d588b65)) - i) | 0;
i = (i + 1) | 0;
if ((i | 0) > 623) {
data[0] = data[623];
i = 1;
}
}
data[0] = 0x80000000;
}
function mt19937() {
var data = new Int32Array(624);
var index = 0;
function next() {
if ((index | 0) >= 624) {
refreshData(data);
index = 0;
}
var value = data[index];
index = (index + 1) | 0;
return temper(value) | 0;
}
next.discard = function (count) {
while ((count - index) > 624) {
count -= 624 - index;
refreshData(data);
index = 0;
}
index = (index + count) | 0;
return next;
};
next.seed = function (initial) {
var previous = 0;
data[0] = previous = initial | 0;
for (var i = 1; i < 624; i = (i + 1) | 0) {
data[i] = previous = (imul((previous ^ (previous >>> 30)), 0x6c078965) + i) | 0;
}
index = 624;
return next;
};
next.seedWithArray = function (source) {
next.seed(0x012bd6aa);
seedWithArray(data, source);
return next;
};
next.autoSeed = function () {
return next.seedWithArray(Random.generateEntropyArray());
};
return next;
}
return mt19937;
}(typeof Int32Array === "function" ? Int32Array : Array)),
browserCrypto: (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function" && typeof Int32Array === "function") ? (function () {
var data = null;
var index = 128;
return function () {
if (index >= 128) {
if (data === null) {
data = new Int32Array(128);
}
crypto.getRandomValues(data);
index = 0;
}
return data[index++] | 0;
};
}()) : null
};
Random.generateEntropyArray = function () {
var array = [];
array.push(new Date().getTime() | 0);
var engine = Random.engines.nativeMath;
for (var i = 0; i < 16; ++i) {
array[i] = engine() | 0;
}
return array;
};
function returnValue(value) {
return function () {
return value;
};
}
// [-0x80000000, 0x7fffffff]
Random.int32 = function (engine) {
return engine() | 0;
};
proto.int32 = function () {
return Random.int32(this.engine);
};
// [0, 0xffffffff]
Random.uint32 = function (engine) {
return engine() >>> 0;
};
proto.uint32 = function () {
return Random.uint32(this.engine);
};
// [0, 0x1fffffffffffff]
Random.uint53 = function (engine) {
var high = engine() & 0x1fffff;
var low = engine() >>> 0;
return (high * 0x100000000) + low;
};
proto.uint53 = function () {
return Random.uint53(this.engine);
};
// [0, 0x20000000000000]
Random.uint53Full = function (engine) {
while (true) {
var high = engine() | 0;
if (high & 0x200000) {
if ((high & 0x3fffff) === 0x200000 && (engine() | 0) === 0) {
return 0x20000000000000;
}
} else {
var low = engine() >>> 0;
return ((high & 0x1fffff) * 0x100000000) + low;
}
}
};
proto.uint53Full = function () {
return Random.uint53Full(this.engine);
};
// [-0x20000000000000, 0x1fffffffffffff]
Random.int53 = function (engine) {
var high = engine() | 0;
var low = engine() >>> 0;
return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);
};
proto.int53 = function () {
return Random.int53(this.engine);
};
// [-0x20000000000000, 0x20000000000000]
Random.int53Full = function (engine) {
while (true) {
var high = engine() | 0;
if (high & 0x400000) {
if ((high & 0x7fffff) === 0x400000 && (engine() | 0) === 0) {
return 0x20000000000000;
}
} else {
var low = engine() >>> 0;
return ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);
}
}
};
proto.int53Full = function () {
return Random.int53Full(this.engine);
};
function add(generate, addend) {
if (addend === 0) {
return generate;
} else {
return function (engine) {
return generate(engine) + addend;
};
}
}
Random.integer = (function () {
function isPowerOfTwoMinusOne(value) {
return ((value + 1) & value) === 0;
}
function bitmask(masking) {
return function (engine) {
return engine() & masking;
};
}
function downscaleToLoopCheckedRange(range) {
var extendedRange = range + 1;
var maximum = extendedRange * Math.floor(0x100000000 / extendedRange);
return function (engine) {
var value = 0;
do {
value = engine() >>> 0;
} while (value >= maximum);
return value % extendedRange;
};
}
function downscaleToRange(range) {
if (isPowerOfTwoMinusOne(range)) {
return bitmask(range);
} else {
return downscaleToLoopCheckedRange(range);
}
}
function isEvenlyDivisibleByMaxInt32(value) {
return (value | 0) === 0;
}
function upscaleWithHighMasking(masking) {
return function (engine) {
var high = engine() & masking;
var low = engine() >>> 0;
return (high * 0x100000000) + low;
};
}
function upscaleToLoopCheckedRange(extendedRange) {
var maximum = extendedRange * Math.floor(0x20000000000000 / extendedRange);
return function (engine) {
var ret = 0;
do {
var high = engine() & 0x1fffff;
var low = engine() >>> 0;
ret = (high * 0x100000000) + low;
} while (ret >= maximum);
return ret % extendedRange;
};
}
function upscaleWithinU53(range) {
var extendedRange = range + 1;
if (isEvenlyDivisibleByMaxInt32(extendedRange)) {
var highRange = ((extendedRange / 0x100000000) | 0) - 1;
if (isPowerOfTwoMinusOne(highRange)) {
return upscaleWithHighMasking(highRange);
}
}
return upscaleToLoopCheckedRange(extendedRange);
}
function upscaleWithinI53AndLoopCheck(min, max) {
return function (engine) {
var ret = 0;
do {
var high = engine() | 0;
var low = engine() >>> 0;
ret = ((high & 0x1fffff) * 0x100000000) + low + (high & 0x200000 ? -0x20000000000000 : 0);
} while (ret < min || ret > max);
return ret;
};
}
return function (min, max) {
min = Math.floor(min);
max = Math.floor(max);
if (min < -0x20000000000000 || !isFinite(min)) {
throw new RangeError("Expected min to be at least " + (-0x20000000000000));
} else if (max > 0x20000000000000 || !isFinite(max)) {
throw new RangeError("Expected max to be at most " + 0x20000000000000);
}
var range = max - min;
if (range <= 0 || !isFinite(range)) {
return returnValue(min);
} else if (range === 0xffffffff) {
if (min === 0) {
return Random.uint32;
} else {
return add(Random.int32, min + 0x80000000);
}
} else if (range < 0xffffffff) {
return add(downscaleToRange(range), min);
} else if (range === 0x1fffffffffffff) {
return add(Random.uint53, min);
} else if (range < 0x1fffffffffffff) {
return add(upscaleWithinU53(range), min);
} else if (max - 1 - min === 0x1fffffffffffff) {
return add(Random.uint53Full, min);
} else if (min === -0x20000000000000 && max === 0x20000000000000) {
return Random.int53Full;
} else if (min === -0x20000000000000 && max === 0x1fffffffffffff) {
return Random.int53;
} else if (min === -0x1fffffffffffff && max === 0x20000000000000) {
return add(Random.int53, 1);
} else if (max === 0x20000000000000) {
return add(upscaleWithinI53AndLoopCheck(min - 1, max - 1), 1);
} else {
return upscaleWithinI53AndLoopCheck(min, max);
}
};
}());
proto.integer = function (min, max) {
return Random.integer(min, max)(this.engine);
};
// [0, 1] (floating point)
Random.realZeroToOneInclusive = function (engine) {
return Random.uint53Full(engine) / 0x20000000000000;
};
proto.realZeroToOneInclusive = function () {
return Random.realZeroToOneInclusive(this.engine);
};
// [0, 1) (floating point)
Random.realZeroToOneExclusive = function (engine) {
return Random.uint53(engine) / 0x20000000000000;
};
proto.realZeroToOneExclusive = function () {
return Random.realZeroToOneExclusive(this.engine);
};
Random.real = (function () {
function multiply(generate, multiplier) {
if (multiplier === 1) {
return generate;
} else if (multiplier === 0) {
return function () {
return 0;
};
} else {
return function (engine) {
return generate(engine) * multiplier;
};
}
}
return function (left, right, inclusive) {
if (!isFinite(left)) {
throw new RangeError("Expected left to be a finite number");
} else if (!isFinite(right)) {
throw new RangeError("Expected right to be a finite number");
}
return add(
multiply(
inclusive ? Random.realZeroToOneInclusive : Random.realZeroToOneExclusive,
right - left),
left);
};
}());
proto.real = function (min, max, inclusive) {
return Random.real(min, max, inclusive)(this.engine);
};
Random.bool = (function () {
function isLeastBitTrue(engine) {
return (engine() & 1) === 1;
}
function lessThan(generate, value) {
return function (engine) {
return generate(engine) < value;
};
}
function probability(percentage) {
if (percentage <= 0) {
return returnValue(false);
} else if (percentage >= 1) {
return returnValue(true);
} else {
var scaled = percentage * 0x100000000;
if (scaled % 1 === 0) {
return lessThan(Random.int32, (scaled - 0x80000000) | 0);
} else {
return lessThan(Random.uint53, Math.round(percentage * 0x20000000000000));
}
}
}
return function (numerator, denominator) {
if (denominator == null) {
if (numerator == null) {
return isLeastBitTrue;
}
return probability(numerator);
} else {
if (numerator <= 0) {
return returnValue(false);
} else if (numerator >= denominator) {
return returnValue(true);
}
return lessThan(Random.integer(0, denominator - 1), numerator);
}
};
}());
proto.bool = function (numerator, denominator) {
return Random.bool(numerator, denominator)(this.engine);
};
function toInteger(value) {
var number = +value;
if (number < 0) {
return Math.ceil(number);
} else {
return Math.floor(number);
}
}
function convertSliceArgument(value, length) {
if (value < 0) {
return Math.max(value + length, 0);
} else {
return Math.min(value, length);
}
}
Random.pick = function (engine, array, begin, end) {
var length = array.length;
var start = begin == null ? 0 : convertSliceArgument(toInteger(begin), length);
var finish = end === void 0 ? length : convertSliceArgument(toInteger(end), length);
if (start >= finish) {
return void 0;
}
var distribution = Random.integer(start, finish - 1);
return array[distribution(engine)];
};
proto.pick = function (array, begin, end) {
return Random.pick(this.engine, array, begin, end);
};
function returnUndefined() {
return void 0;
}
var slice = Array.prototype.slice;
Random.picker = function (array, begin, end) {
var clone = slice.call(array, begin, end);
if (!clone.length) {
return returnUndefined;
}
var distribution = Random.integer(0, clone.length - 1);
return function (engine) {
return clone[distribution(engine)];
};
};
Random.shuffle = function (engine, array, downTo) {
var length = array.length;
if (length) {
if (downTo == null) {
downTo = 0;
}
for (var i = (length - 1) >>> 0; i > downTo; --i) {
var distribution = Random.integer(0, i);
var j = distribution(engine);
if (i !== j) {
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
return array;
};
proto.shuffle = function (array) {
return Random.shuffle(this.engine, array);
};
Random.sample = function (engine, population, sampleSize) {
if (sampleSize < 0 || sampleSize > population.length || !isFinite(sampleSize)) {
throw new RangeError("Expected sampleSize to be within 0 and the length of the population");
}
if (sampleSize === 0) {
return [];
}
var clone = slice.call(population);
var length = clone.length;
if (length === sampleSize) {
return Random.shuffle(engine, clone, 0);
}
var tailLength = length - sampleSize;
return Random.shuffle(engine, clone, tailLength).slice(tailLength);
};
proto.sample = function (population, sampleSize) {
return Random.sample(this.engine, population, sampleSize);
};
Random.die = function (sideCount) {
return Random.integer(1, sideCount);
};
proto.die = function (sideCount) {
return Random.die(sideCount)(this.engine);
};
Random.dice = function (sideCount, dieCount) {
var distribution = Random.die(sideCount);
return function (engine) {
var result = [];
result.length = dieCount;
for (var i = 0; i < dieCount; ++i) {
result[i] = distribution(engine);
}
return result;
};
};
proto.dice = function (sideCount, dieCount) {
return Random.dice(sideCount, dieCount)(this.engine);
};
// http://en.wikipedia.org/wiki/Universally_unique_identifier
Random.uuid4 = (function () {
function zeroPad(string, zeroCount) {
return stringRepeat("0", zeroCount - string.length) + string;
}
return function (engine) {
var a = engine() >>> 0;
var b = engine() | 0;
var c = engine() | 0;
var d = engine() >>> 0;
return (
zeroPad(a.toString(16), 8) +
"-" +
zeroPad((b & 0xffff).toString(16), 4) +
"-" +
zeroPad((((b >> 4) & 0x0fff) | 0x4000).toString(16), 4) +
"-" +
zeroPad(((c & 0x3fff) | 0x8000).toString(16), 4) +
"-" +
zeroPad(((c >> 4) & 0xffff).toString(16), 4) +
zeroPad(d.toString(16), 8));
};
}());
proto.uuid4 = function () {
return Random.uuid4(this.engine);
};
Random.string = (function () {
// has 2**x chars, for faster uniform distribution
var DEFAULT_STRING_POOL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
return function (pool) {
if (pool == null) {
pool = DEFAULT_STRING_POOL;
}
var length = pool.length;
if (!length) {
throw new Error("Expected pool not to be an empty string");
}
var distribution = Random.integer(0, length - 1);
return function (engine, length) {
var result = "";
for (var i = 0; i < length; ++i) {
var j = distribution(engine);
result += pool.charAt(j);
}
return result;
};
};
}());
proto.string = function (length, pool) {
return Random.string(pool)(this.engine, length);
};
Random.hex = (function () {
var LOWER_HEX_POOL = "0123456789abcdef";
var lowerHex = Random.string(LOWER_HEX_POOL);
var upperHex = Random.string(LOWER_HEX_POOL.toUpperCase());
return function (upper) {
if (upper) {
return upperHex;
} else {
return lowerHex;
}
};
}());
proto.hex = function (length, upper) {
return Random.hex(upper)(this.engine, length);
};
Random.date = function (start, end) {
if (!(start instanceof Date)) {
throw new TypeError("Expected start to be a Date, got " + typeof start);
} else if (!(end instanceof Date)) {
throw new TypeError("Expected end to be a Date, got " + typeof end);
}
var distribution = Random.integer(start.getTime(), end.getTime());
return function (engine) {
return new Date(distribution(engine));
};
};
proto.date = function (start, end) {
return Random.date(start, end)(this.engine);
};
if (typeof define === "function" && define.amd) {
define(function () {
return Random;
});
} else if (typeof module !== "undefined" && typeof require === "function") {
module.exports = Random;
} else {
(function () {
var oldGlobal = root[GLOBAL_KEY];
Random.noConflict = function () {
root[GLOBAL_KEY] = oldGlobal;
return this;
};
}());
root[GLOBAL_KEY] = Random;
}
}(this));
},{}],27:[function(require,module,exports){
(function (process){
var defined = require('defined');
var createDefaultStream = require('./lib/default_stream');
var Test = require('./lib/test');
var createResult = require('./lib/results');
var through = require('through');
var canEmitExit = typeof process !== 'undefined' && process
&& typeof process.on === 'function' && process.browser !== true
;
var canExit = typeof process !== 'undefined' && process
&& typeof process.exit === 'function'
;
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
exports = module.exports = (function () {
var harness;
var lazyLoad = function () {
return getHarness().apply(this, arguments);
};
lazyLoad.only = function () {
return getHarness().only.apply(this, arguments);
};
lazyLoad.createStream = function (opts) {
if (!opts) opts = {};
if (!harness) {
var output = through();
getHarness({ stream: output, objectMode: opts.objectMode });
return output;
}
return harness.createStream(opts);
};
return lazyLoad
function getHarness (opts) {
if (!opts) opts = {};
opts.autoclose = !canEmitExit;
if (!harness) harness = createExitHarness(opts);
return harness;
}
})();
function createExitHarness (conf) {
if (!conf) conf = {};
var harness = createHarness({
autoclose: defined(conf.autoclose, false)
});
var stream = harness.createStream({ objectMode: conf.objectMode });
var es = stream.pipe(conf.stream || createDefaultStream());
if (canEmitExit) {
es.on('error', function (err) { harness._exitCode = 1 });
}
var ended = false;
stream.on('end', function () { ended = true });
if (conf.exit === false) return harness;
if (!canEmitExit || !canExit) return harness;
var inErrorState = false;
process.on('exit', function (code) {
// let the process exit cleanly.
if (code !== 0) {
return
}
if (!ended) {
var only = harness._results._only;
for (var i = 0; i < harness._tests.length; i++) {
var t = harness._tests[i];
if (only && t.name !== only) continue;
t._exit();
}
}
harness.close();
process.exit(code || harness._exitCode);
});
return harness;
}
exports.createHarness = createHarness;
exports.Test = Test;
exports.test = exports; // tap compat
exports.test.skip = Test.skip;
var exitInterval;
function createHarness (conf_) {
if (!conf_) conf_ = {};
var results = createResult();
if (conf_.autoclose !== false) {
results.once('done', function () { results.close() });
}
var test = function (name, conf, cb) {
var t = new Test(name, conf, cb);
test._tests.push(t);
(function inspectCode (st) {
st.on('test', function sub (st_) {
inspectCode(st_);
});
st.on('result', function (r) {
if (!r.ok && typeof r !== 'string') test._exitCode = 1
});
})(t);
results.push(t);
return t;
};
test._results = results;
test._tests = [];
test.createStream = function (opts) {
return results.createStream(opts);
};
var only = false;
test.only = function (name) {
if (only) throw new Error('there can only be one only test');
results.only(name);
only = true;
return test.apply(null, arguments);
};
test._exitCode = 0;
test.close = function () { results.close() };
return test;
}
}).call(this,require('_process'))
},{"./lib/default_stream":28,"./lib/results":29,"./lib/test":30,"_process":12,"defined":34,"through":38}],28:[function(require,module,exports){
(function (process){
var through = require('through');
var fs = require('fs');
module.exports = function () {
var line = '';
var stream = through(write, flush);
return stream;
function write (buf) {
for (var i = 0; i < buf.length; i++) {
var c = typeof buf === 'string'
? buf.charAt(i)
: String.fromCharCode(buf[i])
;
if (c === '\n') flush();
else line += c;
}
}
function flush () {
if (fs.writeSync && /^win/.test(process.platform)) {
try { fs.writeSync(1, line + '\n'); }
catch (e) { stream.emit('error', e) }
}
else {
try { console.log(line) }
catch (e) { stream.emit('error', e) }
}
line = '';
}
};
}).call(this,require('_process'))
},{"_process":12,"fs":2,"through":38}],29:[function(require,module,exports){
(function (process){
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
var through = require('through');
var resumer = require('resumer');
var inspect = require('object-inspect');
var hasOwn = Object.prototype.hasOwnProperty;
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
module.exports = Results;
inherits(Results, EventEmitter);
function Results () {
if (!(this instanceof Results)) return new Results;
this.count = 0;
this.fail = 0;
this.pass = 0;
this._stream = through();
this.tests = [];
}
Results.prototype.createStream = function (opts) {
if (!opts) opts = {};
var self = this;
var output, testId = 0;
if (opts.objectMode) {
output = through();
self.on('_push', function ontest (t, extra) {
if (!extra) extra = {};
var id = testId++;
t.once('prerun', function () {
var row = {
type: 'test',
name: t.name,
id: id
};
if (has(extra, 'parent')) {
row.parent = extra.parent;
}
output.queue(row);
});
t.on('test', function (st) {
ontest(st, { parent: id });
});
t.on('result', function (res) {
res.test = id;
res.type = 'assert';
output.queue(res);
});
t.on('end', function () {
output.queue({ type: 'end', test: id });
});
});
self.on('done', function () { output.queue(null) });
}
else {
output = resumer();
output.queue('TAP version 13\n');
self._stream.pipe(output);
}
nextTick(function next() {
var t;
while (t = getNextTest(self)) {
t.run();
if (!t.ended) return t.once('end', function(){ nextTick(next); });
}
self.emit('done');
});
return output;
};
Results.prototype.push = function (t) {
var self = this;
self.tests.push(t);
self._watch(t);
self.emit('_push', t);
};
Results.prototype.only = function (name) {
if (this._only) {
self.count ++;
self.fail ++;
write('not ok ' + self.count + ' already called .only()\n');
}
this._only = name;
};
Results.prototype._watch = function (t) {
var self = this;
var write = function (s) { self._stream.queue(s) };
t.once('prerun', function () {
write('# ' + t.name + '\n');
});
t.on('result', function (res) {
if (typeof res === 'string') {
write('# ' + res + '\n');
return;
}
write(encodeResult(res, self.count + 1));
self.count ++;
if (res.ok) self.pass ++
else self.fail ++
});
t.on('test', function (st) { self._watch(st) });
};
Results.prototype.close = function () {
var self = this;
if (self.closed) self._stream.emit('error', new Error('ALREADY CLOSED'));
self.closed = true;
var write = function (s) { self._stream.queue(s) };
write('\n1..' + self.count + '\n');
write('# tests ' + self.count + '\n');
write('# pass ' + self.pass + '\n');
if (self.fail) write('# fail ' + self.fail + '\n')
else write('\n# ok\n')
self._stream.queue(null);
};
function encodeResult (res, count) {
var output = '';
output += (res.ok ? 'ok ' : 'not ok ') + count;
output += res.name ? ' ' + res.name.toString().replace(/\s+/g, ' ') : '';
if (res.skip) output += ' # SKIP';
else if (res.todo) output += ' # TODO';
output += '\n';
if (res.ok) return output;
var outer = ' ';
var inner = outer + ' ';
output += outer + '---\n';
output += inner + 'operator: ' + res.operator + '\n';
if (has(res, 'expected') || has(res, 'actual')) {
var ex = inspect(res.expected);
var ac = inspect(res.actual);
if (Math.max(ex.length, ac.length) > 65) {
output += inner + 'expected:\n' + inner + ' ' + ex + '\n';
output += inner + 'actual:\n' + inner + ' ' + ac + '\n';
}
else {
output += inner + 'expected: ' + ex + '\n';
output += inner + 'actual: ' + ac + '\n';
}
}
if (res.at) {
output += inner + 'at: ' + res.at + '\n';
}
if (res.operator === 'error' && res.actual && res.actual.stack) {
var lines = String(res.actual.stack).split('\n');
output += inner + 'stack:\n';
output += inner + ' ' + lines[0] + '\n';
for (var i = 1; i < lines.length; i++) {
output += inner + lines[i] + '\n';
}
}
output += outer + '...\n';
return output;
}
function getNextTest (results) {
if (!results._only) {
return results.tests.shift();
}
do {
var t = results.tests.shift();
if (!t) continue;
if (results._only === t.name) {
return t;
}
} while (results.tests.length !== 0)
}
function has (obj, prop) {
return hasOwn.call(obj, prop);
}
}).call(this,require('_process'))
},{"_process":12,"events":8,"inherits":35,"object-inspect":36,"resumer":37,"through":38}],30:[function(require,module,exports){
(function (process,__dirname){
var deepEqual = require('deep-equal');
var defined = require('defined');
var path = require('path');
var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;
module.exports = Test;
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
inherits(Test, EventEmitter);
var getTestArgs = function (name_, opts_, cb_) {
var name = '(anonymous)';
var opts = {};
var cb;
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
var t = typeof arg;
if (t === 'string') {
name = arg;
}
else if (t === 'object') {
opts = arg || opts;
}
else if (t === 'function') {
cb = arg;
}
}
return { name: name, opts: opts, cb: cb };
};
function Test (name_, opts_, cb_) {
if (! (this instanceof Test)) {
return new Test(name_, opts_, cb_);
}
var args = getTestArgs(name_, opts_, cb_);
this.readable = true;
this.name = args.name || '(anonymous)';
this.assertCount = 0;
this.pendingCount = 0;
this._skip = args.opts.skip || false;
this._plan = undefined;
this._cb = args.cb;
this._progeny = [];
this._ok = true;
if (args.opts.timeout !== undefined) {
this.timeoutAfter(args.opts.timeout);
}
for (var prop in this) {
this[prop] = (function bind(self, val) {
if (typeof val === 'function') {
return function bound() {
return val.apply(self, arguments);
};
}
else return val;
})(this, this[prop]);
}
}
Test.prototype.run = function () {
if (!this._cb || this._skip) {
return this._end();
}
this.emit('prerun');
this._cb(this);
this.emit('run');
};
Test.prototype.test = function (name, opts, cb) {
var self = this;
var t = new Test(name, opts, cb);
this._progeny.push(t);
this.pendingCount++;
this.emit('test', t);
t.on('prerun', function () {
self.assertCount++;
})
if (!self._pendingAsserts()) {
nextTick(function () {
self._end();
});
}
nextTick(function() {
if (!self._plan && self.pendingCount == self._progeny.length) {
self._end();
}
});
};
Test.prototype.comment = function (msg) {
this.emit('result', msg.trim().replace(/^#\s*/, ''));
};
Test.prototype.plan = function (n) {
this._plan = n;
this.emit('plan', n);
};
Test.prototype.timeoutAfter = function(ms) {
if (!ms) throw new Error('timeoutAfter requires a timespan');
var self = this;
var timeout = setTimeout(function() {
self.fail('test timed out after ' + ms + 'ms');
self.end();
}, ms);
this.once('end', function() {
clearTimeout(timeout);
});
}
Test.prototype.end = function (err) {
var self = this;
if (arguments.length >= 1 && !!err) {
this.ifError(err);
}
if (this.calledEnd) {
this.fail('.end() called twice');
}
this.calledEnd = true;
this._end();
};
Test.prototype._end = function (err) {
var self = this;
if (this._progeny.length) {
var t = this._progeny.shift();
t.on('end', function () { self._end() });
t.run();
return;
}
if (!this.ended) this.emit('end');
var pendingAsserts = this._pendingAsserts();
if (!this._planError && this._plan !== undefined && pendingAsserts) {
this._planError = true;
this.fail('plan != count', {
expected : this._plan,
actual : this.assertCount
});
}
this.ended = true;
};
Test.prototype._exit = function () {
if (this._plan !== undefined &&
!this._planError && this.assertCount !== this._plan) {
this._planError = true;
this.fail('plan != count', {
expected : this._plan,
actual : this.assertCount,
exiting : true
});
}
else if (!this.ended) {
this.fail('test exited without ending', {
exiting: true
});
}
};
Test.prototype._pendingAsserts = function () {
if (this._plan === undefined) {
return 1;
}
else {
return this._plan - (this._progeny.length + this.assertCount);
}
};
Test.prototype._assert = function assert (ok, opts) {
var self = this;
var extra = opts.extra || {};
var res = {
id : self.assertCount ++,
ok : Boolean(ok),
skip : defined(extra.skip, opts.skip),
name : defined(extra.message, opts.message, '(unnamed assert)'),
operator : defined(extra.operator, opts.operator)
};
if (has(opts, 'actual') || has(extra, 'actual')) {
res.actual = defined(extra.actual, opts.actual);
}
if (has(opts, 'expected') || has(extra, 'expected')) {
res.expected = defined(extra.expected, opts.expected);
}
this._ok = Boolean(this._ok && ok);
if (!ok) {
res.error = defined(extra.error, opts.error, new Error(res.name));
}
if (!ok) {
var e = new Error('exception');
var err = (e.stack || '').split('\n');
var dir = path.dirname(__dirname) + '/';
for (var i = 0; i < err.length; i++) {
var m = /^[^\s]*\s*\bat\s+(.+)/.exec(err[i]);
if (!m) {
continue;
}
var s = m[1].split(/\s+/);
var filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[1]);
if (!filem) {
filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[2]);
if (!filem) {
filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[3]);
if (!filem) {
continue;
}
}
}
if (filem[1].slice(0, dir.length) === dir) {
continue;
}
res.functionName = s[0];
res.file = filem[1];
res.line = Number(filem[2]);
if (filem[3]) res.column = filem[3];
res.at = m[1];
break;
}
}
self.emit('result', res);
var pendingAsserts = self._pendingAsserts();
if (!pendingAsserts) {
if (extra.exiting) {
self._end();
} else {
nextTick(function () {
self._end();
});
}
}
if (!self._planError && pendingAsserts < 0) {
self._planError = true;
self.fail('plan != count', {
expected : self._plan,
actual : self._plan - pendingAsserts
});
}
};
Test.prototype.fail = function (msg, extra) {
this._assert(false, {
message : msg,
operator : 'fail',
extra : extra
});
};
Test.prototype.pass = function (msg, extra) {
this._assert(true, {
message : msg,
operator : 'pass',
extra : extra
});
};
Test.prototype.skip = function (msg, extra) {
this._assert(true, {
message : msg,
operator : 'skip',
skip : true,
extra : extra
});
};
Test.prototype.ok
= Test.prototype['true']
= Test.prototype.assert
= function (value, msg, extra) {
this._assert(value, {
message : msg,
operator : 'ok',
expected : true,
actual : value,
extra : extra
});
};
Test.prototype.notOk
= Test.prototype['false']
= Test.prototype.notok
= function (value, msg, extra) {
this._assert(!value, {
message : msg,
operator : 'notOk',
expected : false,
actual : value,
extra : extra
});
};
Test.prototype.error
= Test.prototype.ifError
= Test.prototype.ifErr
= Test.prototype.iferror
= function (err, msg, extra) {
this._assert(!err, {
message : defined(msg, String(err)),
operator : 'error',
actual : err,
extra : extra
});
};
Test.prototype.equal
= Test.prototype.equals
= Test.prototype.isEqual
= Test.prototype.is
= Test.prototype.strictEqual
= Test.prototype.strictEquals
= function (a, b, msg, extra) {
this._assert(a === b, {
message : defined(msg, 'should be equal'),
operator : 'equal',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype.notEqual
= Test.prototype.notEquals
= Test.prototype.notStrictEqual
= Test.prototype.notStrictEquals
= Test.prototype.isNotEqual
= Test.prototype.isNot
= Test.prototype.not
= Test.prototype.doesNotEqual
= Test.prototype.isInequal
= function (a, b, msg, extra) {
this._assert(a !== b, {
message : defined(msg, 'should not be equal'),
operator : 'notEqual',
actual : a,
notExpected : b,
extra : extra
});
};
Test.prototype.deepEqual
= Test.prototype.deepEquals
= Test.prototype.isEquivalent
= Test.prototype.same
= function (a, b, msg, extra) {
this._assert(deepEqual(a, b, { strict: true }), {
message : defined(msg, 'should be equivalent'),
operator : 'deepEqual',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype.deepLooseEqual
= Test.prototype.looseEqual
= Test.prototype.looseEquals
= function (a, b, msg, extra) {
this._assert(deepEqual(a, b), {
message : defined(msg, 'should be equivalent'),
operator : 'deepLooseEqual',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype.notDeepEqual
= Test.prototype.notEquivalent
= Test.prototype.notDeeply
= Test.prototype.notSame
= Test.prototype.isNotDeepEqual
= Test.prototype.isNotDeeply
= Test.prototype.isNotEquivalent
= Test.prototype.isInequivalent
= function (a, b, msg, extra) {
this._assert(!deepEqual(a, b, { strict: true }), {
message : defined(msg, 'should not be equivalent'),
operator : 'notDeepEqual',
actual : a,
notExpected : b,
extra : extra
});
};
Test.prototype.notDeepLooseEqual
= Test.prototype.notLooseEqual
= Test.prototype.notLooseEquals
= function (a, b, msg, extra) {
this._assert(!deepEqual(a, b), {
message : defined(msg, 'should be equivalent'),
operator : 'notDeepLooseEqual',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype['throws'] = function (fn, expected, msg, extra) {
if (typeof expected === 'string') {
msg = expected;
expected = undefined;
}
var caught = undefined;
try {
fn();
} catch (err) {
caught = { error : err };
var message = err.message;
delete err.message;
err.message = message;
}
var passed = caught;
if (expected instanceof RegExp) {
passed = expected.test(caught && caught.error);
expected = String(expected);
}
if (typeof expected === 'function' && caught) {
passed = caught.error instanceof expected;
caught.error = caught.error.constructor;
}
this._assert(passed, {
message : defined(msg, 'should throw'),
operator : 'throws',
actual : caught && caught.error,
expected : expected,
error: !passed && caught && caught.error,
extra : extra
});
};
Test.prototype.doesNotThrow = function (fn, expected, msg, extra) {
if (typeof expected === 'string') {
msg = expected;
expected = undefined;
}
var caught = undefined;
try {
fn();
}
catch (err) {
caught = { error : err };
}
this._assert(!caught, {
message : defined(msg, 'should not throw'),
operator : 'throws',
actual : caught && caught.error,
expected : expected,
error : caught && caught.error,
extra : extra
});
};
var hasOwn = Object.prototype.hasOwnProperty;
function has (obj, prop) {
return hasOwn.call(obj, prop);
}
Test.skip = function (name_, _opts, _cb) {
var args = getTestArgs.apply(null, arguments);
args.opts.skip = true;
return Test(args.name, args.opts, args.cb);
};
// vim: set softtabstop=4 shiftwidth=4:
}).call(this,require('_process'),"/node_modules/tape/lib")
},{"_process":12,"deep-equal":31,"defined":34,"events":8,"inherits":35,"path":11}],31:[function(require,module,exports){
var pSlice = Array.prototype.slice;
var objectKeys = require('./lib/keys.js');
var isArguments = require('./lib/is_arguments.js');
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return typeof a === typeof b;
}
},{"./lib/is_arguments.js":32,"./lib/keys.js":33}],32:[function(require,module,exports){
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
},{}],33:[function(require,module,exports){
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
},{}],34:[function(require,module,exports){
module.exports = function () {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] !== undefined) return arguments[i];
}
};
},{}],35:[function(require,module,exports){
arguments[4][9][0].apply(exports,arguments)
},{"dup":9}],36:[function(require,module,exports){
module.exports = function inspect_ (obj, opts, depth, seen) {
if (!opts) opts = {};
var maxDepth = opts.depth === undefined ? 5 : opts.depth;
if (depth === undefined) depth = 0;
if (depth >= maxDepth && maxDepth > 0
&& obj && typeof obj === 'object') {
return '[Object]';
}
if (seen === undefined) seen = [];
else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect (value, from) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'string') {
return inspectString(obj);
}
else if (typeof obj === 'function') {
var name = nameOf(obj);
return '[Function' + (name ? ': ' + name : '') + ']';
}
else if (obj === null) {
return 'null';
}
else if (isSymbol(obj)) {
var symString = Symbol.prototype.toString.call(obj);
return typeof obj === 'object' ? 'Object(' + symString + ')' : symString;
}
else if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
}
s += '>';
if (obj.childNodes && obj.childNodes.length) s += '...';
s += '</' + String(obj.nodeName).toLowerCase() + '>';
return s;
}
else if (isArray(obj)) {
if (obj.length === 0) return '[]';
var xs = Array(obj.length);
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
return '[ ' + xs.join(', ') + ' ]';
}
else if (isError(obj)) {
var parts = [];
for (var key in obj) {
if (!has(obj, key)) continue;
if (/[^\w$]/.test(key)) {
parts.push(inspect(key) + ': ' + inspect(obj[key]));
}
else {
parts.push(key + ': ' + inspect(obj[key]));
}
}
if (parts.length === 0) return '[' + obj + ']';
return '{ [' + obj + '] ' + parts.join(', ') + ' }';
}
else if (typeof obj === 'object' && typeof obj.inspect === 'function') {
return obj.inspect();
}
else if (typeof obj === 'object' && !isDate(obj) && !isRegExp(obj)) {
var xs = [], keys = [];
for (var key in obj) {
if (has(obj, key)) keys.push(key);
}
keys.sort();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (/[^\w$]/.test(key)) {
xs.push(inspect(key) + ': ' + inspect(obj[key], obj));
}
else xs.push(key + ': ' + inspect(obj[key], obj));
}
if (xs.length === 0) return '{}';
return '{ ' + xs.join(', ') + ' }';
}
else return String(obj);
};
function quote (s) {
return String(s).replace(/"/g, '&quot;');
}
function isArray (obj) { return toStr(obj) === '[object Array]' }
function isDate (obj) { return toStr(obj) === '[object Date]' }
function isRegExp (obj) { return toStr(obj) === '[object RegExp]' }
function isError (obj) { return toStr(obj) === '[object Error]' }
function isSymbol (obj) { return toStr(obj) === '[object Symbol]' }
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has (obj, key) {
return hasOwn.call(obj, key);
}
function toStr (obj) {
return Object.prototype.toString.call(obj);
}
function nameOf (f) {
if (f.name) return f.name;
var m = f.toString().match(/^function\s*([\w$]+)/);
if (m) return m[1];
}
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
function isElement (x) {
if (!x || typeof x !== 'object') return false;
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string'
&& typeof x.getAttribute === 'function'
;
}
function inspectString (str) {
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return "'" + s + "'";
function lowbyte (c) {
var n = c.charCodeAt(0);
var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
if (x) return '\\' + x;
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}
}
},{}],37:[function(require,module,exports){
(function (process){
var through = require('through');
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
module.exports = function (write, end) {
var tr = through(write, end);
tr.pause();
var resume = tr.resume;
var pause = tr.pause;
var paused = false;
tr.pause = function () {
paused = true;
return pause.apply(this, arguments);
};
tr.resume = function () {
paused = false;
return resume.apply(this, arguments);
};
nextTick(function () {
if (!paused) tr.resume();
});
return tr;
};
}).call(this,require('_process'))
},{"_process":12,"through":38}],38:[function(require,module,exports){
(function (process){
var Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end, opts) {
write = write || function (data) { this.queue(data) }
end = end || function () { this.queue(null) }
var ended = false, destroyed = false, buffer = [], _ended = false
var stream = new Stream()
stream.readable = stream.writable = true
stream.paused = false
// stream.autoPause = !(opts && opts.autoPause === false)
stream.autoDestroy = !(opts && opts.autoDestroy === false)
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
function drain() {
while(buffer.length && !stream.paused) {
var data = buffer.shift()
if(null === data)
return stream.emit('end')
else
stream.emit('data', data)
}
}
stream.queue = stream.push = function (data) {
// console.error(ended)
if(_ended) return stream
if(data === null) _ended = true
buffer.push(data)
drain()
return stream
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
//this is only a problem if end is not emitted synchronously.
//a nicer way to do this is to make sure this is the last listener for 'end'
stream.on('end', function () {
stream.readable = false
if(!stream.writable && stream.autoDestroy)
process.nextTick(function () {
stream.destroy()
})
})
function _end () {
stream.writable = false
end.call(stream)
if(!stream.readable && stream.autoDestroy)
stream.destroy()
}
stream.end = function (data) {
if(ended) return
ended = true
if(arguments.length) stream.write(data)
_end() // will emit or queue
return stream
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
buffer.length = 0
stream.writable = stream.readable = false
stream.emit('close')
return stream
}
stream.pause = function () {
if(stream.paused) return
stream.paused = true
return stream
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
stream.emit('resume')
}
drain()
//may have become paused again,
//as drain emits 'data'.
if(!stream.paused)
stream.emit('drain')
return stream
}
return stream
}
}).call(this,require('_process'))
},{"_process":12,"stream":24}],39:[function(require,module,exports){
require("../test/bayes.test.js");
require("../test/bernoulli_distribution.test.js");
require("../test/binomial_distribution.test.js");
require("../test/chi_squared_goodness_of_fit.test.js");
require("../test/chunks.test.js");
require("../test/ckmeans.test.js");
require("../test/cumulative.js");
require("../test/equal_interval_breaks.test.js");
require("../test/error_function.js");
require("../test/factorial.test.js");
require("../test/geometric_mean.test.js");
require("../test/harmonic_mean.test.js");
require("../test/iqr.test.js");
require("../test/linear_regression.test.js");
require("../test/mad.test.js");
require("../test/mean.test.js");
require("../test/median.test.js");
require("../test/minmax.test.js");
require("../test/mixin.test.js");
require("../test/mode.test.js");
require("../test/normal_distribution.test.js");
require("../test/numeric_sort.test.js");
require("../test/perceptron.test.js");
require("../test/poisson_distribution.test.js");
require("../test/quantile.test.js");
require("../test/quantilesorted.test.js");
require("../test/r_squared.test.js");
require("../test/root_mean_square.test.js");
require("../test/sample.test.js");
require("../test/sample_correlation.test.js");
require("../test/sample_covariance.test.js");
require("../test/sample_skewness.test.js");
require("../test/sample_standard_deviation.test.js");
require("../test/sample_variance.test.js");
require("../test/shuffle.test.js");
require("../test/sorted_unique_count.test.js");
require("../test/standard_deviation.test.js");
require("../test/standard_normal_table.js");
require("../test/sum.test.js");
require("../test/sum_nth_power_deviations.test.js");
require("../test/t_test.test.js");
require("../test/t_test_two_sample.test.js");
require("../test/variance.test.js");
require("../test/z_score.test.js");
},{"../test/bayes.test.js":90,"../test/bernoulli_distribution.test.js":91,"../test/binomial_distribution.test.js":92,"../test/chi_squared_goodness_of_fit.test.js":93,"../test/chunks.test.js":94,"../test/ckmeans.test.js":95,"../test/cumulative.js":96,"../test/equal_interval_breaks.test.js":97,"../test/error_function.js":98,"../test/factorial.test.js":99,"../test/geometric_mean.test.js":100,"../test/harmonic_mean.test.js":101,"../test/iqr.test.js":102,"../test/linear_regression.test.js":103,"../test/mad.test.js":104,"../test/mean.test.js":105,"../test/median.test.js":106,"../test/minmax.test.js":107,"../test/mixin.test.js":108,"../test/mode.test.js":109,"../test/normal_distribution.test.js":110,"../test/numeric_sort.test.js":111,"../test/perceptron.test.js":112,"../test/poisson_distribution.test.js":113,"../test/quantile.test.js":114,"../test/quantilesorted.test.js":115,"../test/r_squared.test.js":116,"../test/root_mean_square.test.js":117,"../test/sample.test.js":118,"../test/sample_correlation.test.js":119,"../test/sample_covariance.test.js":120,"../test/sample_skewness.test.js":121,"../test/sample_standard_deviation.test.js":122,"../test/sample_variance.test.js":123,"../test/shuffle.test.js":124,"../test/sorted_unique_count.test.js":125,"../test/standard_deviation.test.js":126,"../test/standard_normal_table.js":127,"../test/sum.test.js":128,"../test/sum_nth_power_deviations.test.js":129,"../test/t_test.test.js":130,"../test/t_test_two_sample.test.js":131,"../test/variance.test.js":132,"../test/z_score.test.js":133}],40:[function(require,module,exports){
'use strict';
/**
* [Bayesian Classifier](http://en.wikipedia.org/wiki/Naive_Bayes_classifier)
*
* This is a naïve bayesian classifier that takes
* singly-nested objects.
*
* @class
* @example
* var bayes = new BayesianClassifier();
* bayes.train({
* species: 'Cat'
* }, 'animal');
* var result = bayes.score({
* species: 'Cat'
* })
* // result
* // {
* // animal: 1
* // }
*/
function BayesianClassifier() {
// The number of items that are currently
// classified in the model
this.totalCount = 0;
// Every item classified in the model
this.data = {};
}
/**
* Train the classifier with a new item, which has a single
* dimension of Javascript literal keys and values.
*
* @param {Object} item an object with singly-deep properties
* @param {string} category the category this item belongs to
* @return {undefined} adds the item to the classifier
*/
BayesianClassifier.prototype.train = function(item, category) {
// If the data object doesn't have any values
// for this category, create a new object for it.
if (!this.data[category]) {
this.data[category] = {};
}
// Iterate through each key in the item.
for (var k in item) {
var v = item[k];
// Initialize the nested object `data[category][k][item[k]]`
// with an object of keys that equal 0.
if (this.data[category][k] === undefined) {
this.data[category][k] = {};
}
if (this.data[category][k][v] === undefined) {
this.data[category][k][v] = 0;
}
// And increment the key for this key/value combination.
this.data[category][k][item[k]]++;
}
// Increment the number of items classified
this.totalCount++;
};
/**
* Generate a score of how well this item matches all
* possible categories based on its attributes
*
* @param {Object} item an item in the same format as with train
* @returns {Object} of probabilities that this item belongs to a
* given category.
*/
BayesianClassifier.prototype.score = function(item) {
// Initialize an empty array of odds per category.
var odds = {}, category;
// Iterate through each key in the item,
// then iterate through each category that has been used
// in previous calls to `.train()`
for (var k in item) {
var v = item[k];
for (category in this.data) {
// Create an empty object for storing key - value combinations
// for this category.
if (odds[category] === undefined) { odds[category] = {}; }
// If this item doesn't even have a property, it counts for nothing,
// but if it does have the property that we're looking for from
// the item to categorize, it counts based on how popular it is
// versus the whole population.
if (this.data[category][k]) {
odds[category][k + '_' + v] = (this.data[category][k][v] || 0) / this.totalCount;
} else {
odds[category][k + '_' + v] = 0;
}
}
}
// Set up a new object that will contain sums of these odds by category
var oddsSums = {};
for (category in odds) {
// Tally all of the odds for each category-combination pair -
// the non-existence of a category does not add anything to the
// score.
for (var combination in odds[category]) {
if (oddsSums[category] === undefined) {
oddsSums[category] = 0;
}
oddsSums[category] += odds[category][combination];
}
}
return oddsSums;
};
module.exports = BayesianClassifier;
},{}],41:[function(require,module,exports){
'use strict';
var binomialDistribution = require('./binomial_distribution');
/**
* The [Bernoulli distribution](http://en.wikipedia.org/wiki/Bernoulli_distribution)
* is the probability discrete
* distribution of a random variable which takes value 1 with success
* probability `p` and value 0 with failure
* probability `q` = 1 - `p`. It can be used, for example, to represent the
* toss of a coin, where "1" is defined to mean "heads" and "0" is defined
* to mean "tails" (or vice versa). It is
* a special case of a Binomial Distribution
* where `n` = 1.
*
* @param {number} p input value, between 0 and 1 inclusive
* @returns {number} value of bernoulli distribution at this point
*/
function bernoulliDistribution(p) {
// Check that `p` is a valid probability (0 ≤ p ≤ 1)
if (p < 0 || p > 1 ) { return null; }
return binomialDistribution(1, p);
}
module.exports = bernoulliDistribution;
},{"./binomial_distribution":42}],42:[function(require,module,exports){
'use strict';
var epsilon = require('./epsilon');
var factorial = require('./factorial');
/**
* The [Binomial Distribution](http://en.wikipedia.org/wiki/Binomial_distribution) is the discrete probability
* distribution of the number of successes in a sequence of n independent yes/no experiments, each of which yields
* success with probability `probability`. Such a success/failure experiment is also called a Bernoulli experiment or
* Bernoulli trial; when trials = 1, the Binomial Distribution is a Bernoulli Distribution.
*
* @param {number} trials number of trials to simulate
* @param {number} probability
* @returns {number} output
*/
function binomialDistribution(trials, probability) {
// Check that `p` is a valid probability (0 ≤ p ≤ 1),
// that `n` is an integer, strictly positive.
if (probability < 0 || probability > 1 ||
trials <= 0 || trials % 1 !== 0) {
return null;
}
// We initialize `x`, the random variable, and `accumulator`, an accumulator
// for the cumulative distribution function to 0. `distribution_functions`
// is the object we'll return with the `probability_of_x` and the
// `cumulativeProbability_of_x`, as well as the calculated mean &
// variance. We iterate until the `cumulativeProbability_of_x` is
// within `epsilon` of 1.0.
var x = 0,
cumulativeProbability = 0,
cells = {};
// This algorithm iterates through each potential outcome,
// until the `cumulativeProbability` is very close to 1, at
// which point we've defined the vast majority of outcomes
do {
// a [probability mass function](https://en.wikipedia.org/wiki/Probability_mass_function)
cells[x] = factorial(trials) /
(factorial(x) * factorial(trials - x)) *
(Math.pow(probability, x) * Math.pow(1 - probability, trials - x));
cumulativeProbability += cells[x];
x++;
// when the cumulativeProbability is nearly 1, we've calculated
// the useful range of this distribution
} while (cumulativeProbability < 1 - epsilon);
return cells;
}
module.exports = binomialDistribution;
},{"./epsilon":48,"./factorial":51}],43:[function(require,module,exports){
'use strict';
/**
* **Percentage Points of the χ2 (Chi-Squared) Distribution**
*
* The [χ2 (Chi-Squared) Distribution](http://en.wikipedia.org/wiki/Chi-squared_distribution) is used in the common
* chi-squared tests for goodness of fit of an observed distribution to a theoretical one, the independence of two
* criteria of classification of qualitative data, and in confidence interval estimation for a population standard
* deviation of a normal distribution from a sample standard deviation.
*
* Values from Appendix 1, Table III of William W. Hines & Douglas C. Montgomery, "Probability and Statistics in
* Engineering and Management Science", Wiley (1980).
*/
var chiSquaredDistributionTable = {
1: { 0.995: 0.00, 0.99: 0.00, 0.975: 0.00, 0.95: 0.00, 0.9: 0.02, 0.5: 0.45, 0.1: 2.71, 0.05: 3.84, 0.025: 5.02, 0.01: 6.63, 0.005: 7.88 },
2: { 0.995: 0.01, 0.99: 0.02, 0.975: 0.05, 0.95: 0.10, 0.9: 0.21, 0.5: 1.39, 0.1: 4.61, 0.05: 5.99, 0.025: 7.38, 0.01: 9.21, 0.005: 10.60 },
3: { 0.995: 0.07, 0.99: 0.11, 0.975: 0.22, 0.95: 0.35, 0.9: 0.58, 0.5: 2.37, 0.1: 6.25, 0.05: 7.81, 0.025: 9.35, 0.01: 11.34, 0.005: 12.84 },
4: { 0.995: 0.21, 0.99: 0.30, 0.975: 0.48, 0.95: 0.71, 0.9: 1.06, 0.5: 3.36, 0.1: 7.78, 0.05: 9.49, 0.025: 11.14, 0.01: 13.28, 0.005: 14.86 },
5: { 0.995: 0.41, 0.99: 0.55, 0.975: 0.83, 0.95: 1.15, 0.9: 1.61, 0.5: 4.35, 0.1: 9.24, 0.05: 11.07, 0.025: 12.83, 0.01: 15.09, 0.005: 16.75 },
6: { 0.995: 0.68, 0.99: 0.87, 0.975: 1.24, 0.95: 1.64, 0.9: 2.20, 0.5: 5.35, 0.1: 10.65, 0.05: 12.59, 0.025: 14.45, 0.01: 16.81, 0.005: 18.55 },
7: { 0.995: 0.99, 0.99: 1.25, 0.975: 1.69, 0.95: 2.17, 0.9: 2.83, 0.5: 6.35, 0.1: 12.02, 0.05: 14.07, 0.025: 16.01, 0.01: 18.48, 0.005: 20.28 },
8: { 0.995: 1.34, 0.99: 1.65, 0.975: 2.18, 0.95: 2.73, 0.9: 3.49, 0.5: 7.34, 0.1: 13.36, 0.05: 15.51, 0.025: 17.53, 0.01: 20.09, 0.005: 21.96 },
9: { 0.995: 1.73, 0.99: 2.09, 0.975: 2.70, 0.95: 3.33, 0.9: 4.17, 0.5: 8.34, 0.1: 14.68, 0.05: 16.92, 0.025: 19.02, 0.01: 21.67, 0.005: 23.59 },
10: { 0.995: 2.16, 0.99: 2.56, 0.975: 3.25, 0.95: 3.94, 0.9: 4.87, 0.5: 9.34, 0.1: 15.99, 0.05: 18.31, 0.025: 20.48, 0.01: 23.21, 0.005: 25.19 },
11: { 0.995: 2.60, 0.99: 3.05, 0.975: 3.82, 0.95: 4.57, 0.9: 5.58, 0.5: 10.34, 0.1: 17.28, 0.05: 19.68, 0.025: 21.92, 0.01: 24.72, 0.005: 26.76 },
12: { 0.995: 3.07, 0.99: 3.57, 0.975: 4.40, 0.95: 5.23, 0.9: 6.30, 0.5: 11.34, 0.1: 18.55, 0.05: 21.03, 0.025: 23.34, 0.01: 26.22, 0.005: 28.30 },
13: { 0.995: 3.57, 0.99: 4.11, 0.975: 5.01, 0.95: 5.89, 0.9: 7.04, 0.5: 12.34, 0.1: 19.81, 0.05: 22.36, 0.025: 24.74, 0.01: 27.69, 0.005: 29.82 },
14: { 0.995: 4.07, 0.99: 4.66, 0.975: 5.63, 0.95: 6.57, 0.9: 7.79, 0.5: 13.34, 0.1: 21.06, 0.05: 23.68, 0.025: 26.12, 0.01: 29.14, 0.005: 31.32 },
15: { 0.995: 4.60, 0.99: 5.23, 0.975: 6.27, 0.95: 7.26, 0.9: 8.55, 0.5: 14.34, 0.1: 22.31, 0.05: 25.00, 0.025: 27.49, 0.01: 30.58, 0.005: 32.80 },
16: { 0.995: 5.14, 0.99: 5.81, 0.975: 6.91, 0.95: 7.96, 0.9: 9.31, 0.5: 15.34, 0.1: 23.54, 0.05: 26.30, 0.025: 28.85, 0.01: 32.00, 0.005: 34.27 },
17: { 0.995: 5.70, 0.99: 6.41, 0.975: 7.56, 0.95: 8.67, 0.9: 10.09, 0.5: 16.34, 0.1: 24.77, 0.05: 27.59, 0.025: 30.19, 0.01: 33.41, 0.005: 35.72 },
18: { 0.995: 6.26, 0.99: 7.01, 0.975: 8.23, 0.95: 9.39, 0.9: 10.87, 0.5: 17.34, 0.1: 25.99, 0.05: 28.87, 0.025: 31.53, 0.01: 34.81, 0.005: 37.16 },
19: { 0.995: 6.84, 0.99: 7.63, 0.975: 8.91, 0.95: 10.12, 0.9: 11.65, 0.5: 18.34, 0.1: 27.20, 0.05: 30.14, 0.025: 32.85, 0.01: 36.19, 0.005: 38.58 },
20: { 0.995: 7.43, 0.99: 8.26, 0.975: 9.59, 0.95: 10.85, 0.9: 12.44, 0.5: 19.34, 0.1: 28.41, 0.05: 31.41, 0.025: 34.17, 0.01: 37.57, 0.005: 40.00 },
21: { 0.995: 8.03, 0.99: 8.90, 0.975: 10.28, 0.95: 11.59, 0.9: 13.24, 0.5: 20.34, 0.1: 29.62, 0.05: 32.67, 0.025: 35.48, 0.01: 38.93, 0.005: 41.40 },
22: { 0.995: 8.64, 0.99: 9.54, 0.975: 10.98, 0.95: 12.34, 0.9: 14.04, 0.5: 21.34, 0.1: 30.81, 0.05: 33.92, 0.025: 36.78, 0.01: 40.29, 0.005: 42.80 },
23: { 0.995: 9.26, 0.99: 10.20, 0.975: 11.69, 0.95: 13.09, 0.9: 14.85, 0.5: 22.34, 0.1: 32.01, 0.05: 35.17, 0.025: 38.08, 0.01: 41.64, 0.005: 44.18 },
24: { 0.995: 9.89, 0.99: 10.86, 0.975: 12.40, 0.95: 13.85, 0.9: 15.66, 0.5: 23.34, 0.1: 33.20, 0.05: 36.42, 0.025: 39.36, 0.01: 42.98, 0.005: 45.56 },
25: { 0.995: 10.52, 0.99: 11.52, 0.975: 13.12, 0.95: 14.61, 0.9: 16.47, 0.5: 24.34, 0.1: 34.28, 0.05: 37.65, 0.025: 40.65, 0.01: 44.31, 0.005: 46.93 },
26: { 0.995: 11.16, 0.99: 12.20, 0.975: 13.84, 0.95: 15.38, 0.9: 17.29, 0.5: 25.34, 0.1: 35.56, 0.05: 38.89, 0.025: 41.92, 0.01: 45.64, 0.005: 48.29 },
27: { 0.995: 11.81, 0.99: 12.88, 0.975: 14.57, 0.95: 16.15, 0.9: 18.11, 0.5: 26.34, 0.1: 36.74, 0.05: 40.11, 0.025: 43.19, 0.01: 46.96, 0.005: 49.65 },
28: { 0.995: 12.46, 0.99: 13.57, 0.975: 15.31, 0.95: 16.93, 0.9: 18.94, 0.5: 27.34, 0.1: 37.92, 0.05: 41.34, 0.025: 44.46, 0.01: 48.28, 0.005: 50.99 },
29: { 0.995: 13.12, 0.99: 14.26, 0.975: 16.05, 0.95: 17.71, 0.9: 19.77, 0.5: 28.34, 0.1: 39.09, 0.05: 42.56, 0.025: 45.72, 0.01: 49.59, 0.005: 52.34 },
30: { 0.995: 13.79, 0.99: 14.95, 0.975: 16.79, 0.95: 18.49, 0.9: 20.60, 0.5: 29.34, 0.1: 40.26, 0.05: 43.77, 0.025: 46.98, 0.01: 50.89, 0.005: 53.67 },
40: { 0.995: 20.71, 0.99: 22.16, 0.975: 24.43, 0.95: 26.51, 0.9: 29.05, 0.5: 39.34, 0.1: 51.81, 0.05: 55.76, 0.025: 59.34, 0.01: 63.69, 0.005: 66.77 },
50: { 0.995: 27.99, 0.99: 29.71, 0.975: 32.36, 0.95: 34.76, 0.9: 37.69, 0.5: 49.33, 0.1: 63.17, 0.05: 67.50, 0.025: 71.42, 0.01: 76.15, 0.005: 79.49 },
60: { 0.995: 35.53, 0.99: 37.48, 0.975: 40.48, 0.95: 43.19, 0.9: 46.46, 0.5: 59.33, 0.1: 74.40, 0.05: 79.08, 0.025: 83.30, 0.01: 88.38, 0.005: 91.95 },
70: { 0.995: 43.28, 0.99: 45.44, 0.975: 48.76, 0.95: 51.74, 0.9: 55.33, 0.5: 69.33, 0.1: 85.53, 0.05: 90.53, 0.025: 95.02, 0.01: 100.42, 0.005: 104.22 },
80: { 0.995: 51.17, 0.99: 53.54, 0.975: 57.15, 0.95: 60.39, 0.9: 64.28, 0.5: 79.33, 0.1: 96.58, 0.05: 101.88, 0.025: 106.63, 0.01: 112.33, 0.005: 116.32 },
90: { 0.995: 59.20, 0.99: 61.75, 0.975: 65.65, 0.95: 69.13, 0.9: 73.29, 0.5: 89.33, 0.1: 107.57, 0.05: 113.14, 0.025: 118.14, 0.01: 124.12, 0.005: 128.30 },
100: { 0.995: 67.33, 0.99: 70.06, 0.975: 74.22, 0.95: 77.93, 0.9: 82.36, 0.5: 99.33, 0.1: 118.50, 0.05: 124.34, 0.025: 129.56, 0.01: 135.81, 0.005: 140.17 }
};
module.exports = chiSquaredDistributionTable;
},{}],44:[function(require,module,exports){
'use strict';
var mean = require('./mean');
var chiSquaredDistributionTable = require('./chi_squared_distribution_table');
/**
* The [χ2 (Chi-Squared) Goodness-of-Fit Test](http://en.wikipedia.org/wiki/Goodness_of_fit#Pearson.27s_chi-squared_test)
* uses a measure of goodness of fit which is the sum of differences between observed and expected outcome frequencies
* (that is, counts of observations), each squared and divided by the number of observations expected given the
* hypothesized distribution. The resulting χ2 statistic, `chiSquared`, can be compared to the chi-squared distribution
* to determine the goodness of fit. In order to determine the degrees of freedom of the chi-squared distribution, one
* takes the total number of observed frequencies and subtracts the number of estimated parameters. The test statistic
* follows, approximately, a chi-square distribution with (k − c) degrees of freedom where `k` is the number of non-empty
* cells and `c` is the number of estimated parameters for the distribution.
*
* @param {Array<number>} data
* @param {Function} distributionType a function that returns a point in a distribution:
* for instance, binomial, bernoulli, or poisson
* @param {number} significance
* @returns {number} chi squared goodness of fit
* @example
* // Data from Poisson goodness-of-fit example 10-19 in William W. Hines & Douglas C. Montgomery,
* // "Probability and Statistics in Engineering and Management Science", Wiley (1980).
* var data1019 = [
* 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
* 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
* 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
* 2, 2, 2, 2, 2, 2, 2, 2, 2,
* 3, 3, 3, 3
* ];
* ss.chiSquaredGoodnessOfFit(data1019, ss.poissonDistribution, 0.05)); //= false
*/
function chiSquaredGoodnessOfFit(data, distributionType, significance) {
// Estimate from the sample data, a weighted mean.
var inputMean = mean(data),
// Calculated value of the χ2 statistic.
chiSquared = 0,
// Degrees of freedom, calculated as (number of class intervals -
// number of hypothesized distribution parameters estimated - 1)
degreesOfFreedom,
// Number of hypothesized distribution parameters estimated, expected to be supplied in the distribution test.
// Lose one degree of freedom for estimating `lambda` from the sample data.
c = 1,
// The hypothesized distribution.
// Generate the hypothesized distribution.
hypothesizedDistribution = distributionType(inputMean),
observedFrequencies = [],
expectedFrequencies = [],
k;
// Create an array holding a histogram from the sample data, of
// the form `{ value: numberOfOcurrences }`
for (var i = 0; i < data.length; i++) {
if (observedFrequencies[data[i]] === undefined) {
observedFrequencies[data[i]] = 0;
}
observedFrequencies[data[i]]++;
}
// The histogram we created might be sparse - there might be gaps
// between values. So we iterate through the histogram, making
// sure that instead of undefined, gaps have 0 values.
for (i = 0; i < observedFrequencies.length; i++) {
if (observedFrequencies[i] === undefined) {
observedFrequencies[i] = 0;
}
}
// Create an array holding a histogram of expected data given the
// sample size and hypothesized distribution.
for (k in hypothesizedDistribution) {
if (k in observedFrequencies) {
expectedFrequencies[k] = hypothesizedDistribution[k] * data.length;
}
}
// Working backward through the expected frequencies, collapse classes
// if less than three observations are expected for a class.
// This transformation is applied to the observed frequencies as well.
for (k = expectedFrequencies.length - 1; k >= 0; k--) {
if (expectedFrequencies[k] < 3) {
expectedFrequencies[k - 1] += expectedFrequencies[k];
expectedFrequencies.pop();
observedFrequencies[k - 1] += observedFrequencies[k];
observedFrequencies.pop();
}
}
// Iterate through the squared differences between observed & expected
// frequencies, accumulating the `chiSquared` statistic.
for (k = 0; k < observedFrequencies.length; k++) {
chiSquared += Math.pow(
observedFrequencies[k] - expectedFrequencies[k], 2) /
expectedFrequencies[k];
}
// Calculate degrees of freedom for this test and look it up in the
// `chiSquaredDistributionTable` in order to
// accept or reject the goodness-of-fit of the hypothesized distribution.
degreesOfFreedom = observedFrequencies.length - c - 1;
return chiSquaredDistributionTable[degreesOfFreedom][significance] < chiSquared;
}
module.exports = chiSquaredGoodnessOfFit;
},{"./chi_squared_distribution_table":43,"./mean":60}],45:[function(require,module,exports){
'use strict';
/**
* Split an array into chunks of a specified size. This function
* has the same behavior as [PHP's array_chunk](http://php.net/manual/en/function.array-chunk.php)
* function, and thus will insert smaller-sized chunks at the end if
* the input size is not divisible by the chunk size.
*
* `sample` is expected to be an array, and `chunkSize` a number.
* The `sample` array can contain any kind of data.
*
* @param {Array} sample any array of values
* @param {number} chunkSize size of each output array
* @returns {Array<Array>} a chunked array
* @example
* console.log(chunk([1, 2, 3, 4], 2)); // [[1, 2], [3, 4]]
*/
function chunk(sample, chunkSize) {
// a list of result chunks, as arrays in an array
var output = [];
// `chunkSize` must be zero or higher - otherwise the loop below,
// in which we call `start += chunkSize`, will loop infinitely.
// So, we'll detect and return null in that case to indicate
// invalid input.
if (chunkSize <= 0) {
return null;
}
// `start` is the index at which `.slice` will start selecting
// new array elements
for (var start = 0; start < sample.length; start += chunkSize) {
// for each chunk, slice that part of the array and add it
// to the output. The `.slice` function does not change
// the original array.
output.push(sample.slice(start, start + chunkSize));
}
return output;
}
module.exports = chunk;
},{}],46:[function(require,module,exports){
'use strict';
var sortedUniqueCount = require('./sorted_unique_count'),
numericSort = require('./numeric_sort');
/**
* Create a new column x row matrix.
*
* @private
* @param {number} columns
* @param {number} rows
* @return {Array<Array<number>>} matrix
* @example
* makeMatrix(10, 10);
*/
function makeMatrix(columns, rows) {
var matrix = [];
for (var i = 0; i < columns; i++) {
var column = [];
for (var j = 0; j < rows; j++) {
column.push(0);
}
matrix.push(column);
}
return matrix;
}
/**
* Ckmeans clustering is an improvement on heuristic-based clustering
* approaches like Jenks. The algorithm was developed in
* [Haizhou Wang and Mingzhou Song](http://journal.r-project.org/archive/2011-2/RJournal_2011-2_Wang+Song.pdf)
* as a [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) approach
* to the problem of clustering numeric data into groups with the least
* within-group sum-of-squared-deviations.
*
* Minimizing the difference within groups - what Wang & Song refer to as
* `withinss`, or within sum-of-squares, means that groups are optimally
* homogenous within and the data is split into representative groups.
* This is very useful for visualization, where you may want to represent
* a continuous variable in discrete color or style groups. This function
* can provide groups that emphasize differences between data.
*
* Being a dynamic approach, this algorithm is based on two matrices that
* store incrementally-computed values for squared deviations and backtracking
* indexes.
*
* Unlike the [original implementation](https://cran.r-project.org/web/packages/Ckmeans.1d.dp/index.html),
* this implementation does not include any code to automatically determine
* the optimal number of clusters: this information needs to be explicitly
* provided.
*
* ### References
* _Ckmeans.1d.dp: Optimal k-means Clustering in One Dimension by Dynamic
* Programming_ Haizhou Wang and Mingzhou Song ISSN 2073-4859
*
* from The R Journal Vol. 3/2, December 2011
* @param {Array<number>} data input data, as an array of number values
* @param {number} nClusters number of desired classes. This cannot be
* greater than the number of values in the data array.
* @returns {Array<Array<number>>} clustered input
* @example
* ckmeans([-1, 2, -1, 2, 4, 5, 6, -1, 2, -1], 3);
* // The input, clustered into groups of similar numbers.
* //= [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]);
*/
function ckmeans(data, nClusters) {
if (nClusters > data.length) {
throw new Error('Cannot generate more classes than there are data values');
}
var sorted = numericSort(data),
// we'll use this as the maximum number of clusters
uniqueCount = sortedUniqueCount(sorted);
// if all of the input values are identical, there's one cluster
// with all of the input in it.
if (uniqueCount === 1) {
return [sorted];
}
// named 'D' originally
var matrix = makeMatrix(nClusters, sorted.length),
// named 'B' originally
backtrackMatrix = makeMatrix(nClusters, sorted.length);
// This is a dynamic programming way to solve the problem of minimizing
// within-cluster sum of squares. It's similar to linear regression
// in this way, and this calculation incrementally computes the
// sum of squares that are later read.
// The outer loop iterates through clusters, from 0 to nClusters.
for (var cluster = 0; cluster < nClusters; cluster++) {
// At the start of each loop, the mean starts as the first element
var firstClusterMean = sorted[0];
for (var sortedIdx = Math.max(cluster, 1);
sortedIdx < sorted.length;
sortedIdx++) {
if (cluster === 0) {
// Increase the running sum of squares calculation by this
// new value
var squaredDifference = Math.pow(
sorted[sortedIdx] - firstClusterMean, 2);
matrix[cluster][sortedIdx] = matrix[cluster][sortedIdx - 1] +
(sortedIdx / (sortedIdx + 1)) * squaredDifference;
// We're computing a running mean by taking the previous
// mean value, multiplying it by the number of elements
// seen so far, and then dividing it by the number of
// elements total.
var newSum = sortedIdx * firstClusterMean + sorted[sortedIdx];
firstClusterMean = newSum / (sortedIdx + 1);
} else {
var sumSquaredDistances = 0,
meanXJ = 0;
for (var j = sortedIdx; j >= cluster; j--) {
sumSquaredDistances += (sortedIdx - j) /
(sortedIdx - j + 1) *
Math.pow(sorted[j] - meanXJ, 2);
meanXJ = (sorted[j] + ((sortedIdx - j) * meanXJ)) /
(sortedIdx - j + 1);
if (j === sortedIdx) {
matrix[cluster][sortedIdx] = sumSquaredDistances;
backtrackMatrix[cluster][sortedIdx] = j;
if (j > 0) {
matrix[cluster][sortedIdx] += matrix[cluster - 1][j - 1];
}
} else {
if (j === 0) {
if (sumSquaredDistances <= matrix[cluster][sortedIdx]) {
matrix[cluster][sortedIdx] = sumSquaredDistances;
backtrackMatrix[cluster][sortedIdx] = j;
}
} else if (sumSquaredDistances + matrix[cluster - 1][j - 1] < matrix[cluster][sortedIdx]) {
matrix[cluster][sortedIdx] = sumSquaredDistances + matrix[cluster - 1][j - 1];
backtrackMatrix[cluster][sortedIdx] = j;
}
}
}
}
}
}
// The real work of Ckmeans clustering happens in the matrix generation:
// the generated matrices encode all possible clustering combinations, and
// once they're generated we can solve for the best clustering groups
// very quickly.
var clusters = [],
clusterRight = backtrackMatrix[0].length - 1;
// Backtrack the clusters from the dynamic programming matrix. This
// starts at the bottom-right corner of the matrix (if the top-left is 0, 0),
// and moves the cluster target with the loop.
for (cluster = backtrackMatrix.length - 1; cluster >= 0; cluster--) {
var clusterLeft = backtrackMatrix[cluster][clusterRight];
// fill the cluster from the sorted input by taking a slice of the
// array. the backtrack matrix makes this easy - it stores the
// indexes where the cluster should start and end.
clusters[cluster] = sorted.slice(clusterLeft, clusterRight + 1);
if (cluster > 0) {
clusterRight = clusterLeft - 1;
}
}
return clusters;
}
module.exports = ckmeans;
},{"./numeric_sort":65,"./sorted_unique_count":81}],47:[function(require,module,exports){
'use strict';
var standardNormalTable = require('./standard_normal_table');
/**
* **[Cumulative Standard Normal Probability](http://en.wikipedia.org/wiki/Standard_normal_table)**
*
* Since probability tables cannot be
* printed for every normal distribution, as there are an infinite variety
* of normal distributions, it is common practice to convert a normal to a
* standard normal and then use the standard normal table to find probabilities.
*
* You can use `.5 + .5 * errorFunction(x / Math.sqrt(2))` to calculate the probability
* instead of looking it up in a table.
*
* @param {number} z
* @returns {number} cumulative standard normal probability
*/
function cumulativeStdNormalProbability(z) {
// Calculate the position of this value.
var absZ = Math.abs(z),
// Each row begins with a different
// significant digit: 0.5, 0.6, 0.7, and so on. Each value in the table
// corresponds to a range of 0.01 in the input values, so the value is
// multiplied by 100.
index = Math.min(Math.round(absZ * 100), standardNormalTable.length - 1);
// The index we calculate must be in the table as a positive value,
// but we still pay attention to whether the input is positive
// or negative, and flip the output value as a last step.
if (z >= 0) {
return standardNormalTable[index];
} else {
// due to floating-point arithmetic, values in the table with
// 4 significant figures can nevertheless end up as repeating
// fractions when they're computed here.
return +(1 - standardNormalTable[index]).toFixed(4);
}
}
module.exports = cumulativeStdNormalProbability;
},{"./standard_normal_table":83}],48:[function(require,module,exports){
'use strict';
/**
* We use `ε`, epsilon, as a stopping criterion when we want to iterate
* until we're "close enough".
*
* This is used in calculations like the binomialDistribution, in which
* the process of finding a value is [iterative](https://en.wikipedia.org/wiki/Iterative_method):
* it progresses until it is close enough.
*/
var epsilon = 0.0001;
module.exports = epsilon;
},{}],49:[function(require,module,exports){
'use strict';
var max = require('./max'),
min = require('./min');
/**
* Given an array of data, this will find the extent of the
* data and return an array of breaks that can be used
* to categorize the data into a number of classes. The
* returned array will always be 1 longer than the number of
* classes because it includes the minimum value.
*
* @param {Array<number>} data input data, as an array of number values
* @param {number} nClasses number of desired classes
* @returns {Array<number>} array of class break positions
* @example
* equalIntervalBreaks([1, 2, 3, 4, 5, 6], 4); //= [1, 2.25, 3.5, 4.75, 6]
*/
function equalIntervalBreaks(data, nClasses) {
// the first break will always be the minimum value
// in the dataset
var breaks = [min(data)];
// The size of each break is the full range of the data
// divided by the number of classes requested
var breakSize = (max(data) - min(data)) / nClasses;
// In the case of nClasses = 1, this loop won't run
// and the returned breaks will be [min, max]
for (var i = 1; i < nClasses; i++) {
breaks.push(breaks[0] + breakSize * i);
}
// the last break will always be the
// maximum.
breaks.push(max(data));
return breaks;
}
module.exports = equalIntervalBreaks;
},{"./max":59,"./min":62}],50:[function(require,module,exports){
'use strict';
/**
* **[Gaussian error function](http://en.wikipedia.org/wiki/Error_function)**
*
* The `errorFunction(x/(sd * Math.sqrt(2)))` is the probability that a value in a
* normal distribution with standard deviation sd is within x of the mean.
*
* This function returns a numerical approximation to the exact value.
*
* @param {number} x input
* @return {number} error estimation
* @example
* errorFunction(1); //= 0.8427
*/
function errorFunction(x) {
var t = 1 / (1 + 0.5 * Math.abs(x));
var tau = t * Math.exp(-Math.pow(x, 2) -
1.26551223 +
1.00002368 * t +
0.37409196 * Math.pow(t, 2) +
0.09678418 * Math.pow(t, 3) -
0.18628806 * Math.pow(t, 4) +
0.27886807 * Math.pow(t, 5) -
1.13520398 * Math.pow(t, 6) +
1.48851587 * Math.pow(t, 7) -
0.82215223 * Math.pow(t, 8) +
0.17087277 * Math.pow(t, 9));
if (x >= 0) {
return 1 - tau;
} else {
return tau - 1;
}
}
module.exports = errorFunction;
},{}],51:[function(require,module,exports){
'use strict';
/**
* A [Factorial](https://en.wikipedia.org/wiki/Factorial), usually written n!, is the product of all positive
* integers less than or equal to n. Often factorial is implemented
* recursively, but this iterative approach is significantly faster
* and simpler.
*
* @param {number} n input
* @returns {number} factorial: n!
* @example
* console.log(factorial(5)); // 120
*/
function factorial(n) {
// factorial is mathematically undefined for negative numbers
if (n < 0 ) { return null; }
// typically you'll expand the factorial function going down, like
// 5! = 5 * 4 * 3 * 2 * 1. This is going in the opposite direction,
// counting from 2 up to the number in question, and since anything
// multiplied by 1 is itself, the loop only needs to start at 2.
var accumulator = 1;
for (var i = 2; i <= n; i++) {
// for each number up to and including the number `n`, multiply
// the accumulator my that number.
accumulator *= i;
}
return accumulator;
}
module.exports = factorial;
},{}],52:[function(require,module,exports){
'use strict';
/**
* The [Geometric Mean](https://en.wikipedia.org/wiki/Geometric_mean) is
* a mean function that is more useful for numbers in different
* ranges.
*
* This is the nth root of the input numbers multiplied by each other.
*
* The geometric mean is often useful for
* **[proportional growth](https://en.wikipedia.org/wiki/Geometric_mean#Proportional_growth)**: given
* growth rates for multiple years, like _80%, 16.66% and 42.85%_, a simple
* mean will incorrectly estimate an average growth rate, whereas a geometric
* mean will correctly estimate a growth rate that, over those years,
* will yield the same end value.
*
* This runs on `O(n)`, linear time in respect to the array
*
* @param {Array<number>} x input array
* @returns {number} geometric mean
* @example
* var growthRates = [1.80, 1.166666, 1.428571];
* var averageGrowth = geometricMean(growthRates);
* var averageGrowthRates = [averageGrowth, averageGrowth, averageGrowth];
* var startingValue = 10;
* var startingValueMean = 10;
* growthRates.forEach(function(rate) {
* startingValue *= rate;
* });
* averageGrowthRates.forEach(function(rate) {
* startingValueMean *= rate;
* });
* startingValueMean === startingValue;
*/
function geometricMean(x) {
// The mean of no numbers is null
if (x.length === 0) { return null; }
// the starting value.
var value = 1;
for (var i = 0; i < x.length; i++) {
// the geometric mean is only valid for positive numbers
if (x[i] <= 0) { return null; }
// repeatedly multiply the value by each number
value *= x[i];
}
return Math.pow(value, 1 / x.length);
}
module.exports = geometricMean;
},{}],53:[function(require,module,exports){
'use strict';
/**
* The [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) is
* a mean function typically used to find the average of rates.
* This mean is calculated by taking the reciprocal of the arithmetic mean
* of the reciprocals of the input numbers.
*
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs on `O(n)`, linear time in respect to the array.
*
* @param {Array<number>} x input
* @returns {number} harmonic mean
* @example
* ss.harmonicMean([2, 3]) //= 2.4
*/
function harmonicMean(x) {
// The mean of no numbers is null
if (x.length === 0) { return null; }
var reciprocalSum = 0;
for (var i = 0; i < x.length; i++) {
// the harmonic mean is only valid for positive numbers
if (x[i] <= 0) { return null; }
reciprocalSum += 1 / x[i];
}
// divide n by the the reciprocal sum
return x.length / reciprocalSum;
}
module.exports = harmonicMean;
},{}],54:[function(require,module,exports){
'use strict';
var quantile = require('./quantile');
/**
* The [Interquartile range](http://en.wikipedia.org/wiki/Interquartile_range) is
* a measure of statistical dispersion, or how scattered, spread, or
* concentrated a distribution is. It's computed as the difference between
* the third quartile and first quartile.
*
* @param {Array<number>} sample
* @returns {number} interquartile range: the span between lower and upper quartile,
* 0.25 and 0.75
* @example
* interquartileRange([0, 1, 2, 3]); //= 2
*/
function interquartileRange(sample) {
// We can't derive quantiles from an empty list
if (sample.length === 0) { return null; }
// Interquartile range is the span between the upper quartile,
// at `0.75`, and lower quartile, `0.25`
return quantile(sample, 0.75) - quantile(sample, 0.25);
}
module.exports = interquartileRange;
},{"./quantile":69}],55:[function(require,module,exports){
'use strict';
/**
* The Inverse [Gaussian error function](http://en.wikipedia.org/wiki/Error_function)
* returns a numerical approximation to the value that would have caused
* `errorFunction()` to return x.
*
* @param {number} x value of error function
* @returns {number} estimated inverted value
*/
function inverseErrorFunction(x) {
var a = (8 * (Math.PI - 3)) / (3 * Math.PI * (4 - Math.PI));
var inv = Math.sqrt(Math.sqrt(
Math.pow(2 / (Math.PI * a) + Math.log(1 - x * x) / 2, 2) -
Math.log(1 - x * x) / a) -
(2 / (Math.PI * a) + Math.log(1 - x * x) / 2));
if (x >= 0) {
return inv;
} else {
return -inv;
}
}
module.exports = inverseErrorFunction;
},{}],56:[function(require,module,exports){
'use strict';
/**
* [Simple linear regression](http://en.wikipedia.org/wiki/Simple_linear_regression)
* is a simple way to find a fitted line
* between a set of coordinates. This algorithm finds the slope and y-intercept of a regression line
* using the least sum of squares.
*
* @param {Array<Array<number>>} data an array of two-element of arrays,
* like `[[0, 1], [2, 3]]`
* @returns {Object} object containing slope and intersect of regression line
* @example
* linearRegression([[0, 0], [1, 1]]); // { m: 1, b: 0 }
*/
function linearRegression(data) {
var m, b;
// Store data length in a local variable to reduce
// repeated object property lookups
var dataLength = data.length;
//if there's only one point, arbitrarily choose a slope of 0
//and a y-intercept of whatever the y of the initial point is
if (dataLength === 1) {
m = 0;
b = data[0][1];
} else {
// Initialize our sums and scope the `m` and `b`
// variables that define the line.
var sumX = 0, sumY = 0,
sumXX = 0, sumXY = 0;
// Use local variables to grab point values
// with minimal object property lookups
var point, x, y;
// Gather the sum of all x values, the sum of all
// y values, and the sum of x^2 and (x*y) for each
// value.
//
// In math notation, these would be SS_x, SS_y, SS_xx, and SS_xy
for (var i = 0; i < dataLength; i++) {
point = data[i];
x = point[0];
y = point[1];
sumX += x;
sumY += y;
sumXX += x * x;
sumXY += x * y;
}
// `m` is the slope of the regression line
m = ((dataLength * sumXY) - (sumX * sumY)) /
((dataLength * sumXX) - (sumX * sumX));
// `b` is the y-intercept of the line.
b = (sumY / dataLength) - ((m * sumX) / dataLength);
}
// Return both values as an object.
return {
m: m,
b: b
};
}
module.exports = linearRegression;
},{}],57:[function(require,module,exports){
'use strict';
/**
* Given the output of `linearRegression`: an object
* with `m` and `b` values indicating slope and intercept,
* respectively, generate a line function that translates
* x values into y values.
*
* @param {Object} mb object with `m` and `b` members, representing
* slope and intersect of desired line
* @returns {Function} method that computes y-value at any given
* x-value on the line.
* @example
* var l = linearRegressionLine(linearRegression([[0, 0], [1, 1]]));
* l(0) //= 0
* l(2) //= 2
*/
function linearRegressionLine(mb) {
// Return a function that computes a `y` value for each
// x value it is given, based on the values of `b` and `a`
// that we just computed.
return function(x) {
return mb.b + (mb.m * x);
};
}
module.exports = linearRegressionLine;
},{}],58:[function(require,module,exports){
'use strict';
var median = require('./median');
/**
* The [Median Absolute Deviation](http://en.wikipedia.org/wiki/Median_absolute_deviation) is
* a robust measure of statistical
* dispersion. It is more resilient to outliers than the standard deviation.
*
* @param {Array<number>} x input array
* @returns {number} median absolute deviation
* @example
* mad([1, 1, 2, 2, 4, 6, 9]); //= 1
*/
function mad(x) {
// The mad of nothing is null
if (!x || x.length === 0) { return null; }
var medianValue = median(x),
medianAbsoluteDeviations = [];
// Make a list of absolute deviations from the median
for (var i = 0; i < x.length; i++) {
medianAbsoluteDeviations.push(Math.abs(x[i] - medianValue));
}
// Find the median value of that list
return median(medianAbsoluteDeviations);
}
module.exports = mad;
},{"./median":61}],59:[function(require,module,exports){
'use strict';
/**
* This computes the maximum number in an array.
*
* This runs on `O(n)`, linear time in respect to the array
*
* @param {Array<number>} x input
* @returns {number} maximum value
* @example
* console.log(max([1, 2, 3, 4])); // 4
*/
function max(x) {
var value;
for (var i = 0; i < x.length; i++) {
// On the first iteration of this loop, max is
// undefined and is thus made the maximum element in the array
if (x[i] > value || value === undefined) {
value = x[i];
}
}
return value;
}
module.exports = max;
},{}],60:[function(require,module,exports){
'use strict';
var sum = require('./sum');
/**
* The mean, _also known as average_,
* is the sum of all values over the number of values.
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs on `O(n)`, linear time in respect to the array
*
* @param {Array<number>} x input values
* @returns {number} mean
* @example
* console.log(mean([0, 10])); // 5
*/
function mean(x) {
// The mean of no numbers is null
if (x.length === 0) { return null; }
return sum(x) / x.length;
}
module.exports = mean;
},{"./sum":84}],61:[function(require,module,exports){
'use strict';
var numericSort = require('./numeric_sort');
/**
* The [median](http://en.wikipedia.org/wiki/Median) is
* the middle number of a list. This is often a good indicator of 'the middle'
* when there are outliers that skew the `mean()` value.
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* The median isn't necessarily one of the elements in the list: the value
* can be the average of two elements if the list has an even length
* and the two central values are different.
*
* @param {Array<number>} x input
* @returns {number} median value
* @example
* var incomes = [10, 2, 5, 100, 2, 1];
* median(incomes); //= 3.5
*/
function median(x) {
// The median of an empty list is null
if (x.length === 0) { return null; }
// Sorting the array makes it easy to find the center, but
// use `.slice()` to ensure the original array `x` is not modified
var sorted = numericSort(x);
// If the length of the list is odd, it's the central number
if (sorted.length % 2 === 1) {
return sorted[(sorted.length - 1) / 2];
// Otherwise, the median is the average of the two numbers
// at the center of the list
} else {
var a = sorted[(sorted.length / 2) - 1];
var b = sorted[(sorted.length / 2)];
return (a + b) / 2;
}
}
module.exports = median;
},{"./numeric_sort":65}],62:[function(require,module,exports){
'use strict';
/**
* The min is the lowest number in the array. This runs on `O(n)`, linear time in respect to the array
*
* @param {Array<number>} x input
* @returns {number} minimum value
* @example
* min([1, 5, -10, 100, 2]); // -100
*/
function min(x) {
var value;
for (var i = 0; i < x.length; i++) {
// On the first iteration of this loop, min is
// undefined and is thus made the minimum element in the array
if (x[i] < value || value === undefined) {
value = x[i];
}
}
return value;
}
module.exports = min;
},{}],63:[function(require,module,exports){
'use strict';
/**
* **Mixin** simple_statistics to a single Array instance if provided
* or the Array native object if not. This is an optional
* feature that lets you treat simple_statistics as a native feature
* of Javascript.
*
* @param {Object} ss simple statistics
* @param {Array} [array=] a single array instance which will be augmented
* with the extra methods. If omitted, mixin will apply to all arrays
* by changing the global `Array.prototype`.
* @returns {*} the extended Array, or Array.prototype if no object
* is given.
*
* @example
* var myNumbers = [1, 2, 3];
* mixin(ss, myNumbers);
* console.log(myNumbers.sum()); // 6
*/
function mixin(ss, array) {
var support = !!(Object.defineProperty && Object.defineProperties);
// Coverage testing will never test this error.
/* istanbul ignore next */
if (!support) {
throw new Error('without defineProperty, simple-statistics cannot be mixed in');
}
// only methods which work on basic arrays in a single step
// are supported
var arrayMethods = ['median', 'standardDeviation', 'sum',
'sampleSkewness',
'mean', 'min', 'max', 'quantile', 'geometricMean',
'harmonicMean', 'root_mean_square'];
// create a closure with a method name so that a reference
// like `arrayMethods[i]` doesn't follow the loop increment
function wrap(method) {
return function() {
// cast any arguments into an array, since they're
// natively objects
var args = Array.prototype.slice.apply(arguments);
// make the first argument the array itself
args.unshift(this);
// return the result of the ss method
return ss[method].apply(ss, args);
};
}
// select object to extend
var extending;
if (array) {
// create a shallow copy of the array so that our internal
// operations do not change it by reference
extending = array.slice();
} else {
extending = Array.prototype;
}
// for each array function, define a function that gets
// the array as the first argument.
// We use [defineProperty](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty)
// because it allows these properties to be non-enumerable:
// `for (var in x)` loops will not run into problems with this
// implementation.
for (var i = 0; i < arrayMethods.length; i++) {
Object.defineProperty(extending, arrayMethods[i], {
value: wrap(arrayMethods[i]),
configurable: true,
enumerable: false,
writable: true
});
}
return extending;
}
module.exports = mixin;
},{}],64:[function(require,module,exports){
'use strict';
var numericSort = require('./numeric_sort');
/**
* The [mode](http://bit.ly/W5K4Yt) is the number that appears in a list the highest number of times.
* There can be multiple modes in a list: in the event of a tie, this
* algorithm will return the most recently seen mode.
*
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs on `O(n)`, linear time in respect to the array.
*
* @param {Array<number>} x input
* @returns {number} mode
* @example
* mode([0, 0, 1]); //= 0
*/
function mode(x) {
// Handle edge cases:
// The median of an empty list is null
if (x.length === 0) { return null; }
else if (x.length === 1) { return x[0]; }
// Sorting the array lets us iterate through it below and be sure
// that every time we see a new number it's new and we'll never
// see the same number twice
var sorted = numericSort(x);
// This assumes it is dealing with an array of size > 1, since size
// 0 and 1 are handled immediately. Hence it starts at index 1 in the
// array.
var last = sorted[0],
// store the mode as we find new modes
value,
// store how many times we've seen the mode
maxSeen = 0,
// how many times the current candidate for the mode
// has been seen
seenThis = 1;
// end at sorted.length + 1 to fix the case in which the mode is
// the highest number that occurs in the sequence. the last iteration
// compares sorted[i], which is undefined, to the highest number
// in the series
for (var i = 1; i < sorted.length + 1; i++) {
// we're seeing a new number pass by
if (sorted[i] !== last) {
// the last number is the new mode since we saw it more
// often than the old one
if (seenThis > maxSeen) {
maxSeen = seenThis;
value = last;
}
seenThis = 1;
last = sorted[i];
// if this isn't a new number, it's one more occurrence of
// the potential mode
} else { seenThis++; }
}
return value;
}
module.exports = mode;
},{"./numeric_sort":65}],65:[function(require,module,exports){
'use strict';
/**
* Sort an array of numbers by their numeric value, ensuring that the
* array is not changed in place.
*
* This is necessary because the default behavior of .sort
* in JavaScript is to sort arrays as string values
*
* [1, 10, 12, 102, 20].sort()
* // output
* [1, 10, 102, 12, 20]
*
* @param {Array<number>} array input array
* @return {Array<number>} sorted array
* @private
* @example
* numericSort([3, 2, 1]) // [1, 2, 3]
*/
function numericSort(array) {
return array
// ensure the array is changed in-place
.slice()
// comparator function that treats input as numeric
.sort(function(a, b) {
return a - b;
});
}
module.exports = numericSort;
},{}],66:[function(require,module,exports){
'use strict';
/**
* This is a single-layer [Perceptron Classifier](http://en.wikipedia.org/wiki/Perceptron) that takes
* arrays of numbers and predicts whether they should be classified
* as either 0 or 1 (negative or positive examples).
* @class
* @example
* // Create the model
* var p = new PerceptronModel();
* // Train the model with input with a diagonal boundary.
* for (var i = 0; i < 5; i++) {
* p.train([1, 1], 1);
* p.train([0, 1], 0);
* p.train([1, 0], 0);
* p.train([0, 0], 0);
* }
* p.predict([0, 0]); // 0
* p.predict([0, 1]); // 0
* p.predict([1, 0]); // 0
* p.predict([1, 1]); // 1
*/
function PerceptronModel() {
// The weights, or coefficients of the model;
// weights are only populated when training with data.
this.weights = [];
// The bias term, or intercept; it is also a weight but
// it's stored separately for convenience as it is always
// multiplied by one.
this.bias = 0;
}
/**
* **Predict**: Use an array of features with the weight array and bias
* to predict whether an example is labeled 0 or 1.
*
* @param {Array<number>} features an array of features as numbers
* @returns {number} 1 if the score is over 0, otherwise 0
*/
PerceptronModel.prototype.predict = function(features) {
// Only predict if previously trained
// on the same size feature array(s).
if (features.length !== this.weights.length) { return null; }
// Calculate the sum of features times weights,
// with the bias added (implicitly times one).
var score = 0;
for (var i = 0; i < this.weights.length; i++) {
score += this.weights[i] * features[i];
}
score += this.bias;
// Classify as 1 if the score is over 0, otherwise 0.
if (score > 0) {
return 1;
} else {
return 0;
}
};
/**
* **Train** the classifier with a new example, which is
* a numeric array of features and a 0 or 1 label.
*
* @param {Array<number>} features an array of features as numbers
* @param {number} label either 0 or 1
* @returns {PerceptronModel} this
*/
PerceptronModel.prototype.train = function(features, label) {
// Require that only labels of 0 or 1 are considered.
if (label !== 0 && label !== 1) { return null; }
// The length of the feature array determines
// the length of the weight array.
// The perceptron will continue learning as long as
// it keeps seeing feature arrays of the same length.
// When it sees a new data shape, it initializes.
if (features.length !== this.weights.length) {
this.weights = features;
this.bias = 1;
}
// Make a prediction based on current weights.
var prediction = this.predict(features);
// Update the weights if the prediction is wrong.
if (prediction !== label) {
var gradient = label - prediction;
for (var i = 0; i < this.weights.length; i++) {
this.weights[i] += gradient * features[i];
}
this.bias += gradient;
}
return this;
};
module.exports = PerceptronModel;
},{}],67:[function(require,module,exports){
'use strict';
var epsilon = require('./epsilon');
var factorial = require('./factorial');
/**
* The [Poisson Distribution](http://en.wikipedia.org/wiki/Poisson_distribution)
* is a discrete probability distribution that expresses the probability
* of a given number of events occurring in a fixed interval of time
* and/or space if these events occur with a known average rate and
* independently of the time since the last event.
*
* The Poisson Distribution is characterized by the strictly positive
* mean arrival or occurrence rate, `λ`.
*
* @param {number} lambda location poisson distribution
* @returns {number} value of poisson distribution at that point
*/
function poissonDistribution(lambda) {
// Check that lambda is strictly positive
if (lambda <= 0) { return null; }
// our current place in the distribution
var x = 0,
// and we keep track of the current cumulative probability, in
// order to know when to stop calculating chances.
cumulativeProbability = 0,
// the calculated cells to be returned
cells = {};
// This algorithm iterates through each potential outcome,
// until the `cumulativeProbability` is very close to 1, at
// which point we've defined the vast majority of outcomes
do {
// a [probability mass function](https://en.wikipedia.org/wiki/Probability_mass_function)
cells[x] = (Math.pow(Math.E, -lambda) * Math.pow(lambda, x)) / factorial(x);
cumulativeProbability += cells[x];
x++;
// when the cumulativeProbability is nearly 1, we've calculated
// the useful range of this distribution
} while (cumulativeProbability < 1 - epsilon);
return cells;
}
module.exports = poissonDistribution;
},{"./epsilon":48,"./factorial":51}],68:[function(require,module,exports){
'use strict';
var epsilon = require('./epsilon');
var inverseErrorFunction = require('./inverse_error_function');
/**
* The [Probit](http://en.wikipedia.org/wiki/Probit)
* is the inverse of cumulativeStdNormalProbability(),
* and is also known as the normal quantile function.
*
* It returns the number of standard deviations from the mean
* where the p'th quantile of values can be found in a normal distribution.
* So, for example, probit(0.5 + 0.6827/2) ≈ 1 because 68.27% of values are
* normally found within 1 standard deviation above or below the mean.
*
* @param {number} p
* @returns {number} probit
*/
function probit(p) {
if (p === 0) {
p = epsilon;
} else if (p >= 1) {
p = 1 - epsilon;
}
return Math.sqrt(2) * inverseErrorFunction(2 * p - 1);
}
module.exports = probit;
},{"./epsilon":48,"./inverse_error_function":55}],69:[function(require,module,exports){
'use strict';
var quantileSorted = require('./quantile_sorted');
var numericSort = require('./numeric_sort');
/**
* The [quantile](https://en.wikipedia.org/wiki/Quantile):
* this is a population quantile, since we assume to know the entire
* dataset in this library. This is an implementation of the
* [Quantiles of a Population](http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population)
* algorithm from wikipedia.
*
* Sample is a one-dimensional array of numbers,
* and p is either a decimal number from 0 to 1 or an array of decimal
* numbers from 0 to 1.
* In terms of a k/q quantile, p = k/q - it's just dealing with fractions or dealing
* with decimal values.
* When p is an array, the result of the function is also an array containing the appropriate
* quantiles in input order
*
* @param {Array<number>} sample a sample from the population
* @param {number} p the desired quantile, as a number between 0 and 1
* @returns {number} quantile
* @example
* var data = [3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20];
* quantile(data, 1); //= max(data);
* quantile(data, 0); //= min(data);
* quantile(data, 0.5); //= 9
*/
function quantile(sample, p) {
// We can't derive quantiles from an empty list
if (sample.length === 0) { return null; }
// Sort a copy of the array. We'll need a sorted array to index
// the values in sorted order.
var sorted = numericSort(sample);
if (p.length) {
// Initialize the result array
var results = [];
// For each requested quantile
for (var i = 0; i < p.length; i++) {
results[i] = quantileSorted(sorted, p[i]);
}
return results;
} else {
return quantileSorted(sorted, p);
}
}
module.exports = quantile;
},{"./numeric_sort":65,"./quantile_sorted":70}],70:[function(require,module,exports){
'use strict';
/**
* This is the internal implementation of quantiles: when you know
* that the order is sorted, you don't need to re-sort it, and the computations
* are faster.
*
* @param {Array<number>} sample input data
* @param {number} p desired quantile: a number between 0 to 1, inclusive
* @returns {number} quantile value
* @example
* var data = [3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20];
* quantileSorted(data, 1); //= max(data);
* quantileSorted(data, 0); //= min(data);
* quantileSorted(data, 0.5); //= 9
*/
function quantileSorted(sample, p) {
var idx = (sample.length) * p;
if (p < 0 || p > 1) {
return null;
} else if (p === 1) {
// If p is 1, directly return the last element
return sample[sample.length - 1];
} else if (p === 0) {
// If p is 0, directly return the first element
return sample[0];
} else if (idx % 1 !== 0) {
// If p is not integer, return the next element in array
return sample[Math.ceil(idx) - 1];
} else if (sample.length % 2 === 0) {
// If the list has even-length, we'll take the average of this number
// and the next value, if there is one
return (sample[idx - 1] + sample[idx]) / 2;
} else {
// Finally, in the simple case of an integer value
// with an odd-length list, return the sample value at the index.
return sample[idx];
}
}
module.exports = quantileSorted;
},{}],71:[function(require,module,exports){
'use strict';
/**
* The [R Squared](http://en.wikipedia.org/wiki/Coefficient_of_determination)
* value of data compared with a function `f`
* is the sum of the squared differences between the prediction
* and the actual value.
*
* @param {Array<Array<number>>} data input data: this should be doubly-nested
* @param {Function} func function called on `[i][0]` values within the dataset
* @returns {number} r-squared value
* @example
* var samples = [[0, 0], [1, 1]];
* var regressionLine = linearRegressionLine(linearRegression(samples));
* rSquared(samples, regressionLine); //= 1 this line is a perfect fit
*/
function rSquared(data, func) {
if (data.length < 2) { return 1; }
// Compute the average y value for the actual
// data set in order to compute the
// _total sum of squares_
var sum = 0, average;
for (var i = 0; i < data.length; i++) {
sum += data[i][1];
}
average = sum / data.length;
// Compute the total sum of squares - the
// squared difference between each point
// and the average of all points.
var sumOfSquares = 0;
for (var j = 0; j < data.length; j++) {
sumOfSquares += Math.pow(average - data[j][1], 2);
}
// Finally estimate the error: the squared
// difference between the estimate and the actual data
// value at each point.
var err = 0;
for (var k = 0; k < data.length; k++) {
err += Math.pow(data[k][1] - func(data[k][0]), 2);
}
// As the error grows larger, its ratio to the
// sum of squares increases and the r squared
// value grows lower.
return 1 - (err / sumOfSquares);
}
module.exports = rSquared;
},{}],72:[function(require,module,exports){
'use strict';
/**
* The Root Mean Square (RMS) is
* a mean function used as a measure of the magnitude of a set
* of numbers, regardless of their sign.
* This is the square root of the mean of the squares of the
* input numbers.
* This runs on `O(n)`, linear time in respect to the array
*
* @param {Array<number>} x input
* @returns {number} root mean square
* @example
* rootMeanSquare([-1, 1, -1, 1]); //= 1
*/
function rootMeanSquare(x) {
if (x.length === 0) { return null; }
var sumOfSquares = 0;
for (var i = 0; i < x.length; i++) {
sumOfSquares += Math.pow(x[i], 2);
}
return Math.sqrt(sumOfSquares / x.length);
}
module.exports = rootMeanSquare;
},{}],73:[function(require,module,exports){
'use strict';
var shuffle = require('./shuffle');
/**
* Create a [simple random sample](http://en.wikipedia.org/wiki/Simple_random_sample)
* from a given array of `n` elements.
*
* The sampled values will be in any order, not necessarily the order
* they appear in the input.
*
* @param {Array} array input array. can contain any type
* @param {number} n count of how many elements to take
* @param {Function} [randomSource=Math.random] an optional source of entropy
* instead of Math.random
* @return {Array} subset of n elements in original array
* @example
* var values = [1, 2, 4, 5, 6, 7, 8, 9];
* sample(values, 3); // returns 3 random values, like [2, 5, 8];
*/
function sample(array, n, randomSource) {
// shuffle the original array using a fisher-yates shuffle
var shuffled = shuffle(array, randomSource);
// and then return a subset of it - the first `n` elements.
return shuffled.slice(0, n);
}
module.exports = sample;
},{"./shuffle":79}],74:[function(require,module,exports){
'use strict';
var sampleCovariance = require('./sample_covariance');
var sampleStandardDeviation = require('./sample_standard_deviation');
/**
* The [correlation](http://en.wikipedia.org/wiki/Correlation_and_dependence) is
* a measure of how correlated two datasets are, between -1 and 1
*
* @param {Array<number>} x first input
* @param {Array<number>} y second input
* @returns {number} sample correlation
* @example
* var a = [1, 2, 3, 4, 5, 6];
* var b = [2, 2, 3, 4, 5, 60];
* sampleCorrelation(a, b); //= 0.691
*/
function sampleCorrelation(x, y) {
var cov = sampleCovariance(x, y),
xstd = sampleStandardDeviation(x),
ystd = sampleStandardDeviation(y);
if (cov === null || xstd === null || ystd === null) {
return null;
}
return cov / xstd / ystd;
}
module.exports = sampleCorrelation;
},{"./sample_covariance":75,"./sample_standard_deviation":77}],75:[function(require,module,exports){
'use strict';
var mean = require('./mean');
/**
* [Sample covariance](https://en.wikipedia.org/wiki/Sample_mean_and_sampleCovariance) of two datasets:
* how much do the two datasets move together?
* x and y are two datasets, represented as arrays of numbers.
*
* @param {Array<number>} x first input
* @param {Array<number>} y second input
* @returns {number} sample covariance
* @example
* var x = [1, 2, 3, 4, 5, 6];
* var y = [6, 5, 4, 3, 2, 1];
* sampleCovariance(x, y); //= -3.5
*/
function sampleCovariance(x, y) {
// The two datasets must have the same length which must be more than 1
if (x.length <= 1 || x.length !== y.length) {
return null;
}
// determine the mean of each dataset so that we can judge each
// value of the dataset fairly as the difference from the mean. this
// way, if one dataset is [1, 2, 3] and [2, 3, 4], their covariance
// does not suffer because of the difference in absolute values
var xmean = mean(x),
ymean = mean(y),
sum = 0;
// for each pair of values, the covariance increases when their
// difference from the mean is associated - if both are well above
// or if both are well below
// the mean, the covariance increases significantly.
for (var i = 0; i < x.length; i++) {
sum += (x[i] - xmean) * (y[i] - ymean);
}
// this is Bessels' Correction: an adjustment made to sample statistics
// that allows for the reduced degree of freedom entailed in calculating
// values from samples rather than complete populations.
var besselsCorrection = x.length - 1;
// the covariance is weighted by the length of the datasets.
return sum / besselsCorrection;
}
module.exports = sampleCovariance;
},{"./mean":60}],76:[function(require,module,exports){
'use strict';
var sumNthPowerDeviations = require('./sum_nth_power_deviations');
var sampleStandardDeviation = require('./sample_standard_deviation');
/**
* [Skewness](http://en.wikipedia.org/wiki/Skewness) is
* a measure of the extent to which a probability distribution of a
* real-valued random variable "leans" to one side of the mean.
* The skewness value can be positive or negative, or even undefined.
*
* Implementation is based on the adjusted Fisher-Pearson standardized
* moment coefficient, which is the version found in Excel and several
* statistical packages including Minitab, SAS and SPSS.
*
* @param {Array<number>} x input
* @returns {number} sample skewness
* @example
* var data = [2, 4, 6, 3, 1];
* sampleSkewness(data); //= 0.5901286564
*/
function sampleSkewness(x) {
// The skewness of less than three arguments is null
if (x.length < 3) { return null; }
var n = x.length,
cubedS = Math.pow(sampleStandardDeviation(x), 3),
sumCubedDeviations = sumNthPowerDeviations(x, 3);
return n * sumCubedDeviations / ((n - 1) * (n - 2) * cubedS);
}
module.exports = sampleSkewness;
},{"./sample_standard_deviation":77,"./sum_nth_power_deviations":85}],77:[function(require,module,exports){
'use strict';
var sampleVariance = require('./sample_variance');
/**
* The [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation)
* is the square root of the variance.
*
* @param {Array<number>} x input array
* @returns {number} sample standard deviation
* @example
* ss.sampleStandardDeviation([2, 4, 4, 4, 5, 5, 7, 9]);
* //= 2.138
*/
function sampleStandardDeviation(x) {
// The standard deviation of no numbers is null
if (x.length <= 1) { return null; }
return Math.sqrt(sampleVariance(x));
}
module.exports = sampleStandardDeviation;
},{"./sample_variance":78}],78:[function(require,module,exports){
'use strict';
var sumNthPowerDeviations = require('./sum_nth_power_deviations');
/*
* The [sample variance](https://en.wikipedia.org/wiki/Variance#Sample_variance)
* is the sum of squared deviations from the mean. The sample variance
* is distinguished from the variance by the usage of [Bessel's Correction](https://en.wikipedia.org/wiki/Bessel's_correction):
* instead of dividing the sum of squared deviations by the length of the input,
* it is divided by the length minus one. This corrects the bias in estimating
* a value from a set that you don't know if full.
*
* References:
* * [Wolfram MathWorld on Sample Variance](http://mathworld.wolfram.com/SampleVariance.html)
*
* @param {Array<number>} x input array
* @return {number} sample variance
* @example
* sampleVariance([1, 2, 3, 4, 5]); //= 2.5
*/
function sampleVariance(x) {
// The variance of no numbers is null
if (x.length <= 1) { return null; }
var sumSquaredDeviationsValue = sumNthPowerDeviations(x, 2);
// this is Bessels' Correction: an adjustment made to sample statistics
// that allows for the reduced degree of freedom entailed in calculating
// values from samples rather than complete populations.
var besselsCorrection = x.length - 1;
// Find the mean value of that list
return sumSquaredDeviationsValue / besselsCorrection;
}
module.exports = sampleVariance;
},{"./sum_nth_power_deviations":85}],79:[function(require,module,exports){
'use strict';
var shuffleInPlace = require('./shuffle_in_place');
/*
* A [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
* is a fast way to create a random permutation of a finite set. This is
* a function around `shuffle_in_place` that adds the guarantee that
* it will not modify its input.
*
* @param {Array} sample an array of any kind of element
* @param {Function} [randomSource=Math.random] an optional entropy source
* @return {Array} shuffled version of input
* @example
* var shuffled = shuffle([1, 2, 3, 4]);
* shuffled; // = [2, 3, 1, 4] or any other random permutation
*/
function shuffle(sample, randomSource) {
// slice the original array so that it is not modified
sample = sample.slice();
// and then shuffle that shallow-copied array, in place
return shuffleInPlace(sample.slice(), randomSource);
}
module.exports = shuffle;
},{"./shuffle_in_place":80}],80:[function(require,module,exports){
'use strict';
/*
* A [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
* in-place - which means that it **will change the order of the original
* array by reference**.
*
* This is an algorithm that generates a random [permutation](https://en.wikipedia.org/wiki/Permutation)
* of a set.
*
* @param {Array} sample input array
* @param {Function} [randomSource=Math.random] an optional source of entropy
* @returns {Array} sample
* @example
* var sample = [1, 2, 3, 4];
* shuffleInPlace(sample);
* // sample is shuffled to a value like [2, 1, 4, 3]
*/
function shuffleInPlace(sample, randomSource) {
// a custom random number source can be provided if you want to use
// a fixed seed or another random number generator, like
// [random-js](https://www.npmjs.org/package/random-js)
randomSource = randomSource || Math.random;
// store the current length of the sample to determine
// when no elements remain to shuffle.
var length = sample.length;
// temporary is used to hold an item when it is being
// swapped between indices.
var temporary;
// The index to swap at each stage.
var index;
// While there are still items to shuffle
while (length > 0) {
// chose a random index within the subset of the array
// that is not yet shuffled
index = Math.floor(randomSource() * length--);
// store the value that we'll move temporarily
temporary = sample[length];
// swap the value at `sample[length]` with `sample[index]`
sample[length] = sample[index];
sample[index] = temporary;
}
return sample;
}
module.exports = shuffleInPlace;
},{}],81:[function(require,module,exports){
'use strict';
/**
* For a sorted input, counting the number of unique values
* is possible in constant time and constant memory. This is
* a simple implementation of the algorithm.
*
* Values are compared with `===`, so objects and non-primitive objects
* are not handled in any special way.
*
* @param {Array} input an array of primitive values.
* @returns {number} count of unique values
* @example
* sortedUniqueCount([1, 2, 3]); // 3
* sortedUniqueCount([1, 1, 1]); // 1
*/
function sortedUniqueCount(input) {
var uniqueValueCount = 0,
lastSeenValue;
for (var i = 0; i < input.length; i++) {
if (i === 0 || input[i] !== lastSeenValue) {
lastSeenValue = input[i];
uniqueValueCount++;
}
}
return uniqueValueCount;
}
module.exports = sortedUniqueCount;
},{}],82:[function(require,module,exports){
'use strict';
var variance = require('./variance');
/**
* The [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation)
* is the square root of the variance. It's useful for measuring the amount
* of variation or dispersion in a set of values.
*
* Standard deviation is only appropriate for full-population knowledge: for
* samples of a population, {@link sampleStandardDeviation} is
* more appropriate.
*
* @param {Array<number>} x input
* @returns {number} standard deviation
* @example
* var scores = [2, 4, 4, 4, 5, 5, 7, 9];
* variance(scores); //= 4
* standardDeviation(scores); //= 2
*/
function standardDeviation(x) {
// The standard deviation of no numbers is null
if (x.length === 0) { return null; }
return Math.sqrt(variance(x));
}
module.exports = standardDeviation;
},{"./variance":88}],83:[function(require,module,exports){
'use strict';
var SQRT_2PI = Math.sqrt(2 * Math.PI);
function cumulativeDistribution(z) {
var sum = z,
tmp = z;
// 15 iterations are enough for 4-digit precision
for (var i = 1; i < 15; i++) {
tmp *= z * z / (2 * i + 1);
sum += tmp;
}
return Math.round((0.5 + (sum / SQRT_2PI) * Math.exp(-z * z / 2)) * 1e4) / 1e4;
}
/**
* A standard normal table, also called the unit normal table or Z table,
* is a mathematical table for the values of Φ (phi), which are the values of
* the cumulative distribution function of the normal distribution.
* It is used to find the probability that a statistic is observed below,
* above, or between values on the standard normal distribution, and by
* extension, any normal distribution.
*
* The probabilities are calculated using the
* [Cumulative distribution function](https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function).
* The table used is the cumulative, and not cumulative from 0 to mean
* (even though the latter has 5 digits precision, instead of 4).
*/
var standardNormalTable = [];
for (var z = 0; z <= 3.09; z += 0.01) {
standardNormalTable.push(cumulativeDistribution(z));
}
module.exports = standardNormalTable;
},{}],84:[function(require,module,exports){
'use strict';
/**
* The [sum](https://en.wikipedia.org/wiki/Summation) of an array
* is the result of adding all numbers together, starting from zero.
*
* This runs on `O(n)`, linear time in respect to the array
*
* @param {Array<number>} x input
* @return {number} sum of all input numbers
* @example
* console.log(sum([1, 2, 3])); // 6
*/
function sum(x) {
var value = 0;
for (var i = 0; i < x.length; i++) {
value += x[i];
}
return value;
}
module.exports = sum;
},{}],85:[function(require,module,exports){
'use strict';
var mean = require('./mean');
/**
* The sum of deviations to the Nth power.
* When n=2 it's the sum of squared deviations.
* When n=3 it's the sum of cubed deviations.
*
* @param {Array<number>} x
* @param {number} n power
* @returns {number} sum of nth power deviations
* @example
* var input = [1, 2, 3];
* // since the variance of a set is the mean squared
* // deviations, we can calculate that with sumNthPowerDeviations:
* var variance = sumNthPowerDeviations(input) / input.length;
*/
function sumNthPowerDeviations(x, n) {
var meanValue = mean(x),
sum = 0;
for (var i = 0; i < x.length; i++) {
sum += Math.pow(x[i] - meanValue, n);
}
return sum;
}
module.exports = sumNthPowerDeviations;
},{"./mean":60}],86:[function(require,module,exports){
'use strict';
var standardDeviation = require('./standard_deviation');
var mean = require('./mean');
/**
* This is to compute [a one-sample t-test](https://en.wikipedia.org/wiki/Student%27s_t-test#One-sample_t-test), comparing the mean
* of a sample to a known value, x.
*
* in this case, we're trying to determine whether the
* population mean is equal to the value that we know, which is `x`
* here. usually the results here are used to look up a
* [p-value](http://en.wikipedia.org/wiki/P-value), which, for
* a certain level of significance, will let you determine that the
* null hypothesis can or cannot be rejected.
*
* @param {Array<number>} sample an array of numbers as input
* @param {number} x expected vale of the population mean
* @returns {number} value
* @example
* tTest([1, 2, 3, 4, 5, 6], 3.385); //= 0.16494154
*/
function tTest(sample, x) {
// The mean of the sample
var sampleMean = mean(sample);
// The standard deviation of the sample
var sd = standardDeviation(sample);
// Square root the length of the sample
var rootN = Math.sqrt(sample.length);
// Compute the known value against the sample,
// returning the t value
return (sampleMean - x) / (sd / rootN);
}
module.exports = tTest;
},{"./mean":60,"./standard_deviation":82}],87:[function(require,module,exports){
'use strict';
var mean = require('./mean');
var sampleVariance = require('./sample_variance');
/**
* This is to compute [two sample t-test](http://en.wikipedia.org/wiki/Student's_t-test).
* Tests whether "mean(X)-mean(Y) = difference", (
* in the most common case, we often have `difference == 0` to test if two samples
* are likely to be taken from populations with the same mean value) with
* no prior knowledge on standard deviations of both samples
* other than the fact that they have the same standard deviation.
*
* Usually the results here are used to look up a
* [p-value](http://en.wikipedia.org/wiki/P-value), which, for
* a certain level of significance, will let you determine that the
* null hypothesis can or cannot be rejected.
*
* `diff` can be omitted if it equals 0.
*
* [This is used to confirm or deny](http://www.monarchlab.org/Lab/Research/Stats/2SampleT.aspx)
* a null hypothesis that the two populations that have been sampled into
* `sampleX` and `sampleY` are equal to each other.
*
* @param {Array<number>} sampleX a sample as an array of numbers
* @param {Array<number>} sampleY a sample as an array of numbers
* @param {number} [difference=0]
* @returns {number} test result
* @example
* ss.tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6], 0); //= -2.1908902300206643
*/
function tTestTwoSample(sampleX, sampleY, difference) {
var n = sampleX.length,
m = sampleY.length;
// If either sample doesn't actually have any values, we can't
// compute this at all, so we return `null`.
if (!n || !m) { return null; }
// default difference (mu) is zero
if (!difference) {
difference = 0;
}
var meanX = mean(sampleX),
meanY = mean(sampleY);
var weightedVariance = ((n - 1) * sampleVariance(sampleX) +
(m - 1) * sampleVariance(sampleY)) / (n + m - 2);
return (meanX - meanY - difference) /
Math.sqrt(weightedVariance * (1 / n + 1 / m));
}
module.exports = tTestTwoSample;
},{"./mean":60,"./sample_variance":78}],88:[function(require,module,exports){
'use strict';
var sumNthPowerDeviations = require('./sum_nth_power_deviations');
/**
* The [variance](http://en.wikipedia.org/wiki/Variance)
* is the sum of squared deviations from the mean.
*
* This is an implementation of variance, not sample variance:
* see the `sampleVariance` method if you want a sample measure.
*
* @param {Array<number>} x a population
* @returns {number} variance: a value greater than or equal to zero.
* zero indicates that all values are identical.
* @example
* ss.variance([1, 2, 3, 4, 5, 6]); //= 2.917
*/
function variance(x) {
// The variance of no numbers is null
if (x.length === 0) { return null; }
// Find the mean of squared deviations between the
// mean value and each value.
return sumNthPowerDeviations(x, 2) / x.length;
}
module.exports = variance;
},{"./sum_nth_power_deviations":85}],89:[function(require,module,exports){
'use strict';
/**
* The [Z-Score, or Standard Score](http://en.wikipedia.org/wiki/Standard_score).
*
* The standard score is the number of standard deviations an observation
* or datum is above or below the mean. Thus, a positive standard score
* represents a datum above the mean, while a negative standard score
* represents a datum below the mean. It is a dimensionless quantity
* obtained by subtracting the population mean from an individual raw
* score and then dividing the difference by the population standard
* deviation.
*
* The z-score is only defined if one knows the population parameters;
* if one only has a sample set, then the analogous computation with
* sample mean and sample standard deviation yields the
* Student's t-statistic.
*
* @param {number} x
* @param {number} mean
* @param {number} standardDeviation
* @return {number} z score
* @example
* ss.zScore(78, 80, 5); //= -0.4
*/
function zScore(x, mean, standardDeviation) {
return (x - mean) / standardDeviation;
}
module.exports = zScore;
},{}],90:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var BayesianClassifier = require('../src/bayesian_classifier');
var test = require('tape');
test('BayesianClassifier', function(t) {
t.test('makes an easy call with one training round', function(t) {
var bayes = new BayesianClassifier();
bayes.train({
species: 'Cat'
}, 'animal');
t.deepEqual(bayes.score({
species: 'Cat'
}), {
animal: 1
});
t.end();
});
t.test('makes fify-fifty call', function(t) {
var bayes = new BayesianClassifier();
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'chair');
t.deepEqual(bayes.score({
species: 'Cat'
}), {
animal: 0.5,
chair: 0.5
});
t.end();
});
t.test('makes seventy-five/twenty-five call', function(t) {
var bayes = new BayesianClassifier();
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'chair');
t.deepEqual(bayes.score({
species: 'Cat'
}), {
animal: 0.75,
chair: 0.25
});
t.end();
});
t.test('tests multiple properties', function(t) {
var bayes = new BayesianClassifier();
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'chair');
bayes.train({
species: 'Cat',
color: 'white'
}, 'chair');
t.deepEqual(bayes.score({
color: 'white'
}), {
animal: 0,
chair: 0.2
});
t.end();
});
t.test('classifies multiple things', function(t) {
var bayes = new BayesianClassifier();
bayes.train({
species: 'Cat'
}, 'animal');
bayes.train({
species: 'Dog'
}, 'animal');
bayes.train({
species: 'Dog'
}, 'animal');
bayes.train({
species: 'Cat'
}, 'chair');
t.deepEqual(bayes.score({
species: 'Cat'
}), {
animal: 0.25,
chair: 0.25
});
t.deepEqual(bayes.score({
species: 'Dog'
}), {
animal: 0.5,
chair: 0
});
t.end();
});
t.end();
});
},{"../src/bayesian_classifier":40,"tape":27}],91:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('bernoulliDistribution', function(t) {
t.test('can return generate probability and cumulative probability distributions for p = 0.3', function(t) {
t.equal('object', typeof ss.bernoulliDistribution(0.3));
t.equal(ss.bernoulliDistribution(0.3)[0], 0.7, ss.epsilon);
t.equal(ss.bernoulliDistribution(0.3)[1], 0.3, ss.epsilon);
t.end();
});
t.test('can return null when p is not a valid probability', function(t) {
t.equal(null, ss.bernoulliDistribution(-0.01), 'p should be greater than 0.0');
t.equal(null, ss.bernoulliDistribution(1.5), 'p should be less than 1.0');
t.end();
});
t.end();
});
},{"../":1,"tape":27}],92:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(n) {
return parseFloat(n.toFixed(4));
}
test('binomialDistribution', function(t) {
// Data given in the [Wikipedia example](http://en.wikipedia.org/wiki/Binomial_distribution#Example) retrieved 29 Mar 2014
// Cumulative probabilities worked by hand to mitigate accumulated rounding errors.
t.test('can return generate probability and cumulative probability distributions for n = 6, p = 0.3', function(t) {
t.equal('object', typeof ss.binomialDistribution(6, 0.3));
t.equal(rnd(ss.binomialDistribution(6, 0.3)[0]), 0.1176, ss.epsilon);
t.equal(rnd(ss.binomialDistribution(6, 0.3)[1]), 0.3025, ss.epsilon);
t.equal(rnd(ss.binomialDistribution(6, 0.3)[2]), 0.3241, ss.epsilon);
t.equal(rnd(ss.binomialDistribution(6, 0.3)[3]), 0.1852, ss.epsilon);
t.equal(rnd(ss.binomialDistribution(6, 0.3)[4]), 0.0595, ss.epsilon);
t.equal(rnd(ss.binomialDistribution(6, 0.3)[5]), 0.0102, ss.epsilon);
t.equal(rnd(ss.binomialDistribution(6, 0.3)[6]), 0.0007, ss.epsilon);
t.end();
});
t.test('can return null when p or n are not valid parameters', function(t) {
t.equal(null, ss.binomialDistribution(0, 0.5), 'n should be strictly positive');
t.equal(null, ss.binomialDistribution(1.5, 0.5), 'n should be an integer');
t.equal(null, ss.binomialDistribution(2, -0.01), 'p should be greater than 0.0');
t.equal(null, ss.binomialDistribution(2, 1.5), 'p should be less than 1.0');
t.end();
});
t.end();
});
},{"../":1,"tape":27}],93:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
// Data from Poisson goodness-of-fit example 10-19 in William W. Hines & Douglas C. Montgomery,
// "Probability and Statistics in Engineering and Management Science", Wiley (1980).
var data1019 = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3
];
test('chiSquaredGoodnessOfFit', function(t) {
t.test('can reject the null hypothesis with level of confidence specified at 0.05', function(t) {
t.equal(false, ss.chiSquaredGoodnessOfFit(data1019, ss.poissonDistribution, 0.05));
t.end();
});
t.test('can accept the null hypothesis with level of confidence specified at 0.10', function(t) {
t.equal(true, ss.chiSquaredGoodnessOfFit(data1019, ss.poissonDistribution, 0.10));
t.end();
});
t.test('can tolerate gaps in distribution', function(t) {
t.equal(true, ss.chiSquaredGoodnessOfFit([0, 2, 3, 7, 7, 7, 7, 7, 7, 9, 10], ss.poissonDistribution, 0.10));
t.end();
});
t.end();
});
},{"../":1,"tape":27}],94:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('chunks', function(t) {
t.test('can get chunks of an array', function(t) {
t.deepEqual(ss.chunk([1, 2], 1), [[1], [2]]);
t.deepEqual(ss.chunk([1, 2], 2), [[1, 2]]);
t.deepEqual(ss.chunk([1, 2, 3, 4], 4), [[1, 2, 3, 4]]);
t.deepEqual(ss.chunk([1, 2, 3, 4], 2), [[1, 2], [3, 4]]);
t.deepEqual(ss.chunk([1, 2, 3, 4], 3), [[1, 2, 3], [4]]);
t.deepEqual(ss.chunk([1, 2, 3, 4, 5, 6, 7], 2), [[1, 2], [3, 4], [5, 6], [7]]);
t.deepEqual(ss.chunk([], 2), []);
t.deepEqual(ss.chunk([], 0), null);
t.deepEqual(ss.chunk([1, 2], 0), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],95:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var cK = require('../src/ckmeans');
test('C k-means', function(t) {
t.ok(cK, 'exports fn');
t.throws(function() {
cK([], 10);
}, 'Cannot generate more values than input');
t.deepEqual(cK([1], 1), [[1]], 'single-value case');
t.deepEqual(cK([1, 1, 1, 1], 1), [[1, 1, 1, 1]], 'same-value case');
var exampleInput = [-1, 2, -1, 2, 4, 5, 6, -1, 2, -1];
var example = cK(exampleInput, 3);
t.deepEqual(example, [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]);
t.deepEqual(cK([1, 2, 3], 3), [[1], [2], [3]]);
t.deepEqual(cK([0, 3, 4], 2), [[0], [3, 4]]),
t.deepEqual(cK([-3, 0, 4], 2), [[-3, 0], [4]]),
t.deepEqual(cK([1, 2, 2, 3], 3), [[1], [2, 2], [3]]);
t.deepEqual(cK([1, 2, 2, 3, 3], 3), [[1], [2, 2], [3, 3]]);
t.deepEqual(cK([1, 2, 3, 2, 3], 3), [[1], [2, 2], [3, 3]]);
t.deepEqual(cK([3, 2, 3, 2, 1], 3), [[1], [2, 2], [3, 3]]);
t.deepEqual(cK([3, 2, 3, 5, 2, 1], 3), [[1, 2, 2], [3, 3], [5]]);
t.deepEqual(cK([0, 1, 2, 100, 101, 103], 2), [[0, 1, 2], [100, 101, 103]]);
t.deepEqual(cK([0, 1, 2, 50, 100, 101, 103], 3), [[0, 1, 2], [50], [100, 101, 103]]);
t.end();
});
},{"../src/ckmeans":46,"tape":27}],96:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('cumulativeStdNormalProbability', function(t) {
// https://en.wikipedia.org/wiki/Standard_normal_table#Examples_of_use
t.test('wikipedia test example works', function(t) {
t.equal(ss.cumulativeStdNormalProbability(0.4), 0.6554);
t.end();
});
t.test('nondecreasing', function(t) {
for (var i = 0; i < ss.standardNormalTable.length; i++) {
if (!ss.cumulativeStdNormalProbability(i / 100) >= ss.cumulativeStdNormalProbability((i - 1) / 100)) {
t.fail('non-decreasing failure on ' + i);
}
}
t.end();
});
t.test('matches errorFunction', function(t) {
for (var i = 0; i < ss.standardNormalTable.length; i++) {
if (!(Math.abs(ss.cumulativeStdNormalProbability(i / 100) - (.5 + .5 * ss.errorFunction(i / 100 / Math.sqrt(2)))) < ss.epsilon)) {
t.fail('error-fn failure on ' + i);
}
}
t.end();
});
t.test('symmetry', function(t) {
t.equal(Math.abs(ss.cumulativeStdNormalProbability(-1) - (1 - ss.cumulativeStdNormalProbability(1))) < ss.epsilon, true);
t.end();
});
t.test('inverse', function(t) {
for (var i = 0; i <= 1 + ss.epsilon; i += .01) {
t.equal(Math.abs(ss.cumulativeStdNormalProbability(ss.probit(i)) - i) < 21 * ss.epsilon, true);
}
t.end();
});
t.end();
});
},{"../":1,"tape":27}],97:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var equalIntervalBreaks = require('../src/equal_interval_breaks');
test('equalIntervalBreaks', function(t) {
t.deepEqual(equalIntervalBreaks([1, 2, 3, 4, 5, 6], 4), [ 1, 2.25, 3.5, 4.75, 6 ], 'three breaks');
t.deepEqual(equalIntervalBreaks([1, 2, 3, 4, 5, 6], 2), [1, 3.5, 6], 'two breaks');
t.deepEqual(equalIntervalBreaks([1, 2, 3, 4, 5, 6], 1), [1, 6], 'one break');
t.end();
});
},{"../src/equal_interval_breaks":49,"tape":27}],98:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('errorFunction', function(t) {
test('symmetry', function(t) {
t.equal(ss.errorFunction(-1), -ss.errorFunction(1));
t.end();
});
t.end();
test('inverse', function(t) {
for (var i = -1; i <= 1; i += .01) {
t.equal(Math.abs(ss.errorFunction(ss.inverseErrorFunction(i)) - i) < 4 * ss.epsilon, true);
}
t.end();
});
});
},{"../":1,"tape":27}],99:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('factorial', function(t) {
t.test('can return null given a negative number', function(t) {
t.equal(null, ss.factorial(-1));
t.end();
});
t.test('can calculate 0! = 1', function(t) {
t.equal(ss.factorial(0), 1);
t.end();
});
t.test('can calculate 1! = 1', function(t) {
t.equal(ss.factorial(1), 1);
t.end();
});
t.test('can calculate 100! = 1', function(t) {
t.equal(ss.factorial(100), 9.33262154439441e+157);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],100:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('geometric mean', function(t) {
// From http://en.wikipedia.org/wiki/Geometric_mean
t.test('can get the mean of two numbers', function(t) {
t.equal(ss.geometricMean([2, 8]), 4);
t.equal(ss.geometricMean([4, 1, 1 / 32]), 0.5);
t.equal(Math.round(ss.geometricMean([2, 32, 1])), 4);
t.end();
});
t.test('returns null for empty lists', function(t) {
t.equal(ss.geometricMean([]), null);
t.end();
});
t.test('returns null for lists with negative numbers', function(t) {
t.equal(ss.geometricMean([-1]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],101:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('harmonicMean', function(t) {
// From http://en.wikipedia.org/wiki/Harmonic_mean
t.test('can get the mean of two or more numbers', function(t) {
t.equal(ss.harmonicMean([1, 1]), 1);
t.equal(rnd(ss.harmonicMean([2, 3])), 2.4);
t.equal(ss.harmonicMean([1, 2, 4]), 12 / 7);
t.end();
});
t.test('returns null for empty lists', function(t) {
t.equal(ss.harmonicMean([]), null);
t.end();
});
t.test('returns null for lists with negative numbers', function(t) {
t.equal(ss.harmonicMean([-1]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],102:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('interquartile range (iqr)', function(t) {
// Data and results from
// [Wikipedia](http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population)
t.test('can get proper iqr of an even-length list', function(t) {
var even = [3, 6, 7, 8, 8, 10, 13, 15, 16, 20];
t.equal(ss.quantile(even, 0.75) - ss.quantile(even, 0.25), ss.iqr(even));
t.end();
});
t.test('can get proper iqr of an odd-length list', function(t) {
var odd = [3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20];
t.equal(ss.quantile(odd, 0.75) - ss.quantile(odd, 0.25), ss.iqr(odd));
t.end();
});
t.test('an iqr of a zero-length list produces null', function(t) {
t.equal(ss.iqr([]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],103:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var linearRegression = require('../src/linear_regression');
var linearRegressionLine = require('../src/linear_regression_line');
test('linear regression', function(t) {
t.test('correctly generates a line for a 0, 0 to 1, 1 dataset', function(t) {
var l = linearRegressionLine(linearRegression([[0, 0], [1, 1]]));
t.equal(l(0), 0);
t.equal(l(0.5), 0.5);
t.equal(l(1), 1);
t.end();
});
t.test('correctly generates a line for a 0, 0 to 1, 0 dataset', function(t) {
var l = linearRegressionLine(linearRegression([[0, 0], [1, 0]]));
t.equal(l(0), 0);
t.equal(l(0.5), 0);
t.equal(l(1), 0);
t.end();
});
t.test('handles a single-point sample', function(t) {
var l = linearRegressionLine(linearRegression([[0, 0]]));
t.deepEqual(l(10), 0);
t.end();
});
t.test('a straight line will have a slope of 0', function(t) {
t.deepEqual(linearRegression([[0, 0], [1, 0]]), { m: 0, b: 0 });
t.end();
});
t.test('a line at 50% grade', function(t) {
t.deepEqual(linearRegression([[0, 0], [1, 0.5]]), { m: 0.5, b: 0 });
t.end();
});
t.test('a line with a high y-intercept', function(t) {
t.deepEqual(linearRegression([[0, 20], [1, 10]]), { m: -10, b: 20 });
t.end();
});
t.end();
});
},{"../src/linear_regression":56,"../src/linear_regression_line":57,"tape":27}],104:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('median absolute deviation (mad)', function(t) {
t.test('median absolute deviation of an example on wikipedia', function(t) {
t.equal(ss.mad([1, 1, 2, 2, 4, 6, 9]), 1);
t.end();
});
// wolfram alpha: median absolute deviation {0,1,2,3,4,5,6,7,8,9,10}
t.test('median absolute deviation of 0-10', function(t) {
t.equal(ss.mad([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3);
t.end();
});
t.test('median absolute deviation of one number is zero', function(t) {
t.equal(ss.mad([1]), 0);
t.end();
});
t.test('zero-length corner case', function(t) {
t.equal(ss.mad([]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],105:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('mean', function(t) {
t.test('can get the mean of two numbers', function(t) {
t.equal(ss.mean([1, 2]), 1.5);
t.end();
});
t.test('can get the mean of one number', function(t) {
t.equal(ss.mean([1]), 1);
t.end();
});
t.test('an empty list has no average', function(t) {
t.equal(ss.mean([]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],106:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('median', function(t) {
t.test('can get the median of three numbers', function(t) {
t.equal(ss.median([1, 2, 3]), 2);
t.end();
});
t.test('can get the median of two numbers', function(t) {
t.equal(ss.median([1, 2]), 1.5);
t.end();
});
t.test('can get the median of four numbers', function(t) {
t.equal(ss.median([1, 2, 3, 4]), 2.5);
t.end();
});
t.test('gives null for the median of an empty list', function(t) {
t.equal(ss.median([]), null);
t.end();
});
t.test('sorts numbers numerically', function(t) {
t.equal(ss.median([8, 9, 10]), 9);
t.end();
});
t.test('does not change the sorting order of its input', function(t) {
var x = [1, 0];
t.equal(ss.median(x), 0.5);
t.equal(x[0], 1);
t.equal(x[1], 0);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],107:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('min', function(t) {
t.test('can get the minimum of one number', function(t) {
t.equal(ss.min([1]), 1);
t.end();
});
t.test('can get the minimum of three numbers', function(t) {
t.equal(ss.min([1, 7, -1000]), -1000);
t.end();
});
t.end();
});
test('max', function(t) {
t.test('can get the maximum of three numbers', function(t) {
t.equal(ss.max([1, 7, -1000]), 7);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],108:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('mixin', function(t) {
t.test('can mix into a single array', function(t) {
var even = ss.mixin(ss, [2, 4, 6, 8]);
t.equal(even.sum(), 20);
t.equal(even.mean(), 5);
t.equal(even.max(), 8);
t.equal(even.min(), 2);
t.equal(even.sampleSkewness(), 0);
t.end();
});
t.test('can mix into Array.prototype', function(t) {
ss.mixin(ss);
var even = [2, 4, 6, 8];
t.equal(even.sum(), 20);
t.equal(even.mean(), 5);
t.equal(even.max(), 8);
t.equal(even.min(), 2);
t.equal(even.sampleSkewness(), 0);
t.end();
});
t.test('mixins can take arguments', function(t) {
ss.mixin(ss);
var even = [2, 4, 6, 8];
t.equal(even.quantile(0.2), 2);
t.equal(even.quantile(0.8), 8);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],109:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('mode', function(t) {
t.test('the mode of a single-number array is that one number', function(t) {
t.equal(ss.mode([1]), 1);
t.end();
});
t.test('the mode of a two-number array is that one number', function(t) {
t.equal(ss.mode([1, 1]), 1);
t.end();
});
t.test('other cases', function(t) {
t.equal(ss.mode([1, 1, 2]), 1);
t.equal(ss.mode([1, 1, 2, 3]), 1);
t.equal(ss.mode([1, 1, 2, 3, 3]), 1);
t.equal(ss.mode([1, 1, 2, 3, 3, 3]), 3);
t.equal(ss.mode([1, 1, 2, 2, 2, 2, 3, 3, 3]), 2);
t.equal(ss.mode([1, 2, 3, 4, 5]), 1);
t.equal(ss.mode([1, 2, 3, 4, 5, 5]), 5);
t.equal(ss.mode([1, 1, 1, 2, 2, 3, 3, 4, 4]), 1);
t.end();
});
t.test('the mode of an empty array is null', function(t) {
t.equal(ss.mode([]), null);
t.end();
});
t.test('the mode of a three-number array with two same numbers is the repeated one', function(t) {
t.equal(ss.mode([1, 2, 2]), 2);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],110:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('natural distribution and z-score', function(t) {
t.test('normal table is exposed in the API', function(t) {
t.equal(ss.standardNormalTable.length, 310);
t.equal(ss.standardNormalTable[0], 0.5);
t.end();
});
t.test('P(Z <= 0.4) is 0.6554', function(t) {
// Taken from the examples of use in http://en.wikipedia.org/wiki/Standard_normal_table
t.equal(ss.cumulativeStdNormalProbability(0.4), 0.6554);
t.end();
});
t.test('P(Z <= -1.20) is 0.1151', function(t) {
// Taken from the examples of use in http://en.wikipedia.org/wiki/Standard_normal_table
t.equal(ss.cumulativeStdNormalProbability(-1.20), 0.1151);
t.end();
});
t.test('P(X <= 82) when X ~ N (80, 25) is 0.6554', function(t) {
// Taken from the examples of use in http://en.wikipedia.org/wiki/Standard_normal_table
// A professor's exam scores are approximately distributed normally with mean 80 and standard deviation 5.
// What is the probability that a student scores an 82 or less?
t.equal(ss.cumulativeStdNormalProbability(ss.zScore(82, 80, 5)), 0.6554);
t.end();
});
t.test('P(X >= 90) when X ~ N (80, 25) is 0.0228', function(t) {
// Taken from the examples of use in http://en.wikipedia.org/wiki/Standard_normal_table
// A professor's exam scores are approximately distributed normally with mean 80 and standard deviation 5.
// What is the probability that a student scores a 90 or more?
t.equal(+(1 - ss.cumulativeStdNormalProbability(ss.zScore(90, 80, 5))).toPrecision(5), 0.0228);
t.end();
});
t.test('P(X <= 74) when X ~ N (80, 25) is 0.1151', function(t) {
// Taken from the examples of use in http://en.wikipedia.org/wiki/Standard_normal_table
// A professor's exam scores are approximately distributed normally with mean 80 and standard deviation 5.
// What is the probability that a student scores a 74 or less?
t.equal(ss.cumulativeStdNormalProbability(ss.zScore(74, 80, 5)), 0.1151);
t.end();
});
t.test('P(78 <= X <= 88) when X ~ N (80, 25) is 0.6006', function(t) {
// Taken from the examples of use in http://en.wikipedia.org/wiki/Standard_normal_table
// A professor's exam scores are approximately distributed normally with mean 80 and standard deviation 5.
// What is the probability that a student scores between 78 and 88?
var prob88 = ss.cumulativeStdNormalProbability(ss.zScore(88, 80, 5)),
prob78 = ss.cumulativeStdNormalProbability(ss.zScore(78, 80, 5));
t.equal(+(prob88 - prob78).toPrecision(5), 0.6006);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],111:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var numericSort = require('../src/numeric_sort');
test('numericSort', function(t) {
t.deepEqual(numericSort([1, 2]), [1, 2]);
t.deepEqual(numericSort([2, 1]), [1, 2]);
var input = [2, 1];
var output = [1, 2];
t.deepEqual(numericSort(input), output);
t.deepEqual(input, [2, 1], 'does not mutate input');
t.end();
});
},{"../src/numeric_sort":65,"tape":27}],112:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var PerceptronModel = require('../src/perceptron');
var test = require('tape');
test('perceptron', function(t) {
t.test('initializes to zeros if label is zero', function(t) {
var p = new PerceptronModel();
p.train([1, 2, 3], 0);
t.deepEqual(p.weights, [0, 0, 0]);
t.equal(p.bias, 0);
t.end();
});
t.test('initializes to values if label is one', function(t) {
var p = new PerceptronModel();
p.train([1, 2, 3], 1);
t.deepEqual(p.weights, [1, 2, 3]);
t.equal(p.bias, 1);
t.end();
});
t.test('learns to separate one from two', function(t) {
var p = new PerceptronModel();
for (var i = 0; i < 4; i++) {
p.train([1], 0);
p.train([2], 1);
}
t.equal(p.predict([1]), 0);
t.equal(p.predict([2]), 1);
t.end();
});
t.test('learns a diagonal boundary', function(t) {
var p = new PerceptronModel();
for (var i = 0; i < 5; i++) {
p.train([1, 1], 1);
p.train([0, 1], 0);
p.train([1, 0], 0);
p.train([0, 0], 0);
}
t.equal(p.predict([0, 0]), 0);
t.equal(p.predict([0, 1]), 0);
t.equal(p.predict([1, 0]), 0);
t.equal(p.predict([1, 1]), 1);
t.end();
});
t.end();
});
},{"../src/perceptron":66,"tape":27}],113:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(n) {
return parseFloat(n.toFixed(4));
}
// expected cumulative probabilities taken from Appendix 1, Table I of William W. Hines & Douglas C.
// Montgomery, "Probability and Statistics in Engineering and Management Science", Wiley (1980).
test('poissonDistribution', function(t) {
t.test('can return generate probability and cumulative probability distributions for lambda = 3.0', function(t) {
t.equal('object', typeof ss.poissonDistribution(3.0));
t.equal(rnd(ss.poissonDistribution(3.0)[3]), 0.2240, ss.epsilon);
t.end();
});
t.test('can generate probability and cumulative probability distributions for lambda = 4.0', function(t) {
t.equal('object', typeof ss.poissonDistribution(4.0));
t.equal(rnd(ss.poissonDistribution(4.0)[2]), 0.1465, ss.epsilon);
t.end();
});
t.test('can generate probability and cumulative probability distributions for lambda = 5.5', function(t) {
t.equal('object', typeof ss.poissonDistribution(5.5));
t.equal(rnd(ss.poissonDistribution(5.5)[7]), 0.1234, ss.epsilon);
t.end();
});
t.test('can generate probability and cumulative probability distributions for lambda = 9.5', function(t) {
t.equal('object', typeof ss.poissonDistribution(9.5));
t.equal(rnd(ss.poissonDistribution(9.5)[17]), 0.0088, ss.epsilon);
t.end();
});
t.test('can return null when lambda <= 0', function(t) {
t.equal(null, ss.poissonDistribution(0));
t.equal(null, ss.poissonDistribution(-10));
t.end();
});
t.end();
});
},{"../":1,"tape":27}],114:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('quantile', function(t) {
// Data and results from
// [Wikipedia](http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population)
t.test('can get proper quantiles of an even-length list', function(t) {
var even = [3, 6, 7, 8, 8, 10, 13, 15, 16, 20];
t.equal(ss.quantile(even, 0.25), 7);
t.equal(ss.quantile(even, 0.5), 9);
t.equal(ss.quantile(even, 0.75), 15);
t.end();
});
t.test('can get proper quantiles of an odd-length list', function(t) {
var odd = [3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20];
t.equal(ss.quantile(odd, 0.25), 7);
t.equal(ss.quantile(odd, 0.5), 9);
t.equal(ss.quantile(odd, 0.75), 15);
t.end();
});
t.test('the median quantile is equal to the median', function(t) {
var rand = [1, 4, 5, 8];
t.equal(ss.quantile(rand, 0.5), ss.median(rand));
var rand2 = [10, 50, 2, 4, 4, 5, 8];
t.equal(ss.quantile(rand2, 0.5), ss.median(rand2));
t.end();
});
t.test('a zero-length list produces null', function(t) {
t.equal(ss.quantile([], 0.5), null);
t.end();
});
t.test('test odd-value case', function(t) {
t.equal(ss.quantile([0, 1, 2, 3, 4], 0.2), 1);
t.end();
});
t.test('bad bounds produce null', function(t) {
t.equal(ss.quantile([1, 2, 3], 1.1), null);
t.equal(ss.quantile([1, 2, 3], -0.5), null);
t.end();
});
t.test('max quantile is equal to the max', function(t) {
t.equal(ss.quantile([1, 2, 3], 1), ss.max([1, 2, 3]));
t.end();
});
t.test('min quantile is equal to the min', function(t) {
t.equal(ss.quantile([1, 2, 3], 0), ss.min([1, 2, 3]));
t.end();
});
t.test('if quantile arg is an array, response is an array of quantiles', function(t) {
var odd = [3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20];
t.deepEqual(ss.quantile(odd, [0, 0.25, 0.5, 0.75, 1]), [3, 7, 9, 15, 20]);
t.deepEqual(ss.quantile(odd, [0.75, 0.5]), [15, 9]);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],115:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('quantileSorted', function(t) {
// Data and results from
// [Wikipedia](http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population)
t.test('can get proper quantiles of an even-length list', function(t) {
var even = [3, 6, 7, 8, 8, 10, 13, 15, 16, 20];
t.equal(ss.quantileSorted(even, 0.25), 7);
t.equal(ss.quantileSorted(even, 0.5), 9);
t.equal(ss.quantileSorted(even, 0.75), 15);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],116:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('r-squared', function(t) {
t.test('says that the r squared of a two-point line is perfect', function(t) {
var d = [[0, 0], [1, 1]];
var l = ss.linearRegressionLine(ss.linearRegression(d));
t.equal(ss.rSquared(d, l), 1);
t.end();
});
t.test('says that the r squared of a three-point line is not perfect', function(t) {
var d = [[0, 0], [0.5, 0.2], [1, 1]];
var l = ss.linearRegressionLine(ss.linearRegression(d));
t.notEqual(ss.rSquared(d, l), 1);
t.end();
});
t.test('r-squared of single sample is 1', function(t) {
var d = [[0, 0]];
var l = ss.linearRegressionLine(ss.linearRegression(d));
t.equal(ss.rSquared(d, l), 1);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],117:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('root_mean_square', function(t) {
// From http://en.wikipedia.org/wiki/Root_mean_square
t.test('can get the RMS of two or more numbers', function(t) {
t.equal(ss.rootMeanSquare([1, 1]), 1);
t.equal(rnd(ss.rootMeanSquare([3, 4, 5])), 4.082);
t.equal(rnd(ss.rootMeanSquare([-0.1, 5, -2, 10])), 5.679);
t.end();
});
t.test('returns null for empty lists', function(t) {
t.equal(ss.rootMeanSquare([]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],118:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var Random = require('random-js');
var random = new Random(Random.engines.mt19937().seed(0));
var ss = require('../');
function rng() { return random.real(0, 1); }
test('sample', function(t) {
t.deepEqual(ss.sample([], 0, rng), [], 'edge case - zero array');
t.deepEqual(ss.sample([], 2, rng), [], 'edge case - zero array');
t.deepEqual(ss.sample([1, 2, 3], 0, rng, 0), [], 'edge case - zero array');
t.deepEqual(ss.sample([1, 2, 3], 1, rng), [1], 'edge case - sample of 1');
t.deepEqual(ss.sample([1, 2, 3], 1, rng), [2]);
t.deepEqual(ss.sample([1, 2, 3], 3, rng), [2, 3, 1]);
t.deepEqual(ss.sample([1, 2, 3, 4], 2, rng), [3, 1]);
t.deepEqual(ss.sample([1, 2, 3, 4, 6, 7, 8], 2, rng), [8, 7]);
t.deepEqual(ss.sample(['foo', 'bar'], 1, rng), ['foo'], 'non-number contents');
t.end();
});
},{"../":1,"random-js":26,"tape":27}],119:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('sample correlation', function(t) {
t.test('can get the sample correlation of identical arrays', function(t) {
var data = [1, 2, 3, 4, 5, 6];
t.equal(rnd(ss.sampleCorrelation(data, data)), 1);
t.end();
});
t.test('can get the sample correlation of different arrays', function(t) {
var a = [1, 2, 3, 4, 5, 6];
var b = [2, 2, 3, 4, 5, 60];
t.equal(rnd(ss.sampleCorrelation(a, b)), 0.691);
t.end();
});
t.test('zero-length corner case', function(t) {
t.equal(rnd(ss.sampleCorrelation([], [])), 0);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],120:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('sample covariance', function(t) {
t.test('can get perfect negative covariance', function(t) {
var x = [1, 2, 3, 4, 5, 6];
var y = [6, 5, 4, 3, 2, 1];
t.equal(rnd(ss.sampleCovariance(x, y)), -3.5);
t.end();
});
t.test('covariance of something with itself is its variance', function(t) {
var x = [1, 2, 3, 4, 5, 6];
t.equal(rnd(ss.sampleCovariance(x, x)), 3.5);
t.end();
});
t.test('covariance is zero for something with no correlation', function(t) {
var x = [1, 2, 3, 4, 5, 6];
var y = [1, 1, 2, 2, 1, 1];
t.equal(rnd(ss.sampleCovariance(x, y)), 0);
t.end();
});
t.test('zero-length corner case', function(t) {
t.equal(rnd(ss.sampleCovariance([], [])), 0);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],121:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('sample skewness', function(t) {
t.test('the skewness of an empty sample is null', function(t) {
var data = [];
t.equal(ss.sampleSkewness(data), null);
t.end();
});
t.test('the skewness of an sample with one number is null', function(t) {
var data = [1];
t.equal(ss.sampleSkewness(data), null);
t.end();
});
t.test('the skewness of an sample with two numbers is null', function(t) {
var data = [1, 2];
t.equal(ss.sampleSkewness(data), null);
t.end();
});
t.test('can calculate the skewness of SAS example 1', function(t) {
// Data and answer taken from SKEWNESS function documentation at
// http://support.sas.com/documentation/c../lrdict/64316/HTML/default/viewer.htm#a000245947.htm
var data = [0, 1, 1];
t.equal(+ss.sampleSkewness(data).toPrecision(10), -1.732050808);
t.end();
});
t.test('can calculate the skewness of SAS example 2', function(t) {
// Data and answer taken from SKEWNESS function documentation at
// http://support.sas.com/documentation/c../lrdict/64316/HTML/default/viewer.htm#a000245947.htm
var data = [2, 4, 6, 3, 1];
t.equal(+ss.sampleSkewness(data).toPrecision(10), 0.5901286564);
t.end();
});
t.test('can calculate the skewness of SAS example 3', function(t) {
// Data and answer taken from SKEWNESS function documentation at
// http://support.sas.com/documentation/c../lrdict/64316/HTML/default/viewer.htm#a000245947.htm
var data = [2, 0, 0];
t.equal(+ss.sampleSkewness(data).toPrecision(10), 1.732050808);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],122:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('sampleStandardDeviation', function(t) {
t.test('can get the standard deviation of an example on wikipedia', function(t) {
t.equal(rnd(ss.sampleStandardDeviation([2, 4, 4, 4, 5, 5, 7, 9])), 2.138);
t.end();
});
t.test('zero-length corner case', function(t) {
t.equal(rnd(ss.sampleStandardDeviation([])), 0);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],123:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('sample variance', function(t) {
t.test('can get the sample variance of a six-sided die', function(t) {
t.equal(rnd(ss.sampleVariance([1, 2, 3, 4, 5, 6])), 3.5);
t.end();
});
// confirmed in R
//
// > var(1:10)
// [1] 9.166667
t.test('can get the sample variance of numbers 1-10', function(t) {
t.equal(rnd(ss.sampleVariance([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])), 9.167);
t.end();
});
t.test('the sample variance of two numbers that are the same is 0', function(t) {
t.equal(rnd(ss.sampleVariance([1, 1])), 0);
t.end();
});
t.test('the sample variance of one number is null', function(t) {
t.equal(ss.sampleVariance([1]), null);
t.end();
});
t.test('the sample variance of no numbers is null', function(t) {
t.equal(ss.sampleVariance([]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],124:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var Random = require('random-js');
var random = new Random(Random.engines.mt19937().seed(0));
var ss = require('../');
function rng() { return random.real(0, 1); }
test('shuffle', function(t) {
var input = [1, 2, 3, 4, 5, 6];
t.deepEqual(ss.shuffle([], rng), []);
t.deepEqual(ss.shuffle(input, rng), [1, 5, 3, 2, 4, 6]);
t.deepEqual(input, [1, 2, 3, 4, 5, 6], 'does not change original array');
t.deepEqual(ss.shuffle(input, rng), [5, 4, 1, 3, 6, 2]);
t.deepEqual(input, [1, 2, 3, 4, 5, 6], 'does not change original array');
t.end();
});
test('shuffleInPlace', function(t) {
var input = [1, 2, 3, 4, 5, 6];
t.deepEqual(ss.shuffleInPlace([], rng), []);
t.deepEqual(ss.shuffleInPlace(input, rng), [6, 1, 5, 2, 4, 3]);
t.deepEqual(input, [6, 1, 5, 2, 4, 3], 'changes original array');
t.end();
});
test('shuffleInPlace truly random', function(t) {
var input = [1, 2, 3, 4, 5, 6];
t.deepEqual(ss.shuffleInPlace([]), []);
t.deepEqual(ss.shuffleInPlace(input).sort(), [1, 2, 3, 4, 5, 6]);
t.end();
});
},{"../":1,"random-js":26,"tape":27}],125:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var sortedUniqueCount = require('../src/sorted_unique_count');
test('sortedUniqueCount', function(t) {
t.equal(sortedUniqueCount([]), 0);
t.equal(sortedUniqueCount([1]), 1);
t.equal(sortedUniqueCount([undefined]), 1);
t.equal(sortedUniqueCount([1, 2, 3, 4]), 4);
t.equal(sortedUniqueCount([1, 2, 3, 3, 4]), 4);
t.equal(sortedUniqueCount([1, 2, 3, 3, 4, 4]), 4);
t.equal(sortedUniqueCount([1, 1, 2, 3, 3, 4, 4]), 4);
t.end();
});
},{"../src/sorted_unique_count":81,"tape":27}],126:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('standardDeviation', function(t) {
t.test('can get the standard deviation of an example on wikipedia', function(t) {
t.equal(rnd(ss.standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])), 2);
t.end();
});
// confirmed with numpy
// In [4]: numpy.std([1,2,3])
// Out[4]: 0.81649658092772603
t.test('can get the standard deviation of 1-3', function(t) {
t.equal(rnd(ss.standardDeviation([1, 2, 3])), 0.816);
t.end();
});
t.test('zero-length array corner case', function(t) {
t.equal(rnd(ss.standardDeviation([])), 0);
t.end();
});
// In [6]: numpy.std([0,1,2,3,4,5,6,7,8,9,10])
// Out[6]: 3.1622776601683795
t.test('can get the standard deviation of 1-10', function(t) {
t.equal(rnd(ss.standardDeviation([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])), 3.162);
t.end();
});
t.test('the standard deviation of one number is zero', function(t) {
t.equal(rnd(ss.standardDeviation([1])), 0);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],127:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('standardNormalTable', function(t) {
test('all entries are numeric', function(t) {
for (var i = 0; i < ss.standardNormalTable.length; i++) {
if (typeof ss.standardNormalTable[i] !== 'number' ||
ss.standardNormalTable[i] < 0 ||
ss.standardNormalTable[i] > 1) {
t.fail('standard normal table value invalid');
}
}
t.end();
});
t.end();
});
},{"../":1,"tape":27}],128:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('sum', function(t) {
t.test('can get the sum of two numbers', function(t) {
t.equal(ss.sum([1, 2]), 3);
t.end();
});
t.test('the sum of no numbers is zero', function(t) {
t.equal(ss.sum([]), 0);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],129:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
test('sumNthPowerDeviations', function(t) {
t.equal(
ss.sumNthPowerDeviations([0, 0, 0], 2),
0);
t.equal(
ss.sumNthPowerDeviations([0, 1], 2),
0.5);
t.equal(
ss.sumNthPowerDeviations([0, 1], 3),
0);
t.equal(
ss.sumNthPowerDeviations([0, 1, 2], 2),
2);
t.end();
});
},{"../":1,"tape":27}],130:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape'),
ss = require('../');
test('t test', function(t) {
t.test('can compare a known value to the mean of samples', function(t) {
var res = ss.tTest([1, 2, 3, 4, 5, 6], 3.385);
t.equal(res, 0.1649415480881466);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],131:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape'),
ss = require('../');
test('tTestTwoSample', function(t) {
t.test('can test independency of two samples', function(t) {
var res = ss.tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6], 0);
t.equal(res, -2.1908902300206643);
t.end();
});
t.test('can test independency of two samples (mu == -2)', function(t) {
var res = ss.tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6], -2);
t.equal(res, 0);
t.end();
});
t.test('can test independency of two samples of different lengths', function(t) {
var res = ss.tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6, 1, 2, 0]);
t.equal(res, -0.4165977904505309);
t.end();
});
t.test('has an edge case for one sample being of size zero', function(t) {
t.equal(ss.tTestTwoSample([1, 2, 3, 4], []), null);
t.equal(ss.tTestTwoSample([], [1, 2, 3, 4]), null);
t.equal(ss.tTestTwoSample([], []), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],132:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
function rnd(x) {
return Math.round(x * 1000) / 1000;
}
test('variance', function(t) {
t.test('can get the variance of a six-sided die', function(t) {
t.equal(rnd(ss.variance([1, 2, 3, 4, 5, 6])), 2.917);
t.end();
});
t.test('the variance of one number is zero', function(t) {
t.equal(rnd(ss.variance([1])), 0);
t.end();
});
t.test('the variance of no numbers is null', function(t) {
t.equal(ss.variance([]), null);
t.end();
});
t.end();
});
},{"../":1,"tape":27}],133:[function(require,module,exports){
/* eslint no-shadow: 0 */
'use strict';
var test = require('tape');
var ss = require('../');
// The zScore method is also tested in the normal distribution tests.
test('zScore', function(t) {
t.equal(ss.zScore(78, 80, 5), -0.4);
t.equal(ss.zScore(78, 90, 5), -2.4);
t.equal(ss.zScore(78, 90, 2), -6);
t.end();
});
},{"../":1,"tape":27}]},{},[39]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment