text:
'use strict';

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

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var url = require('url');
var http = require('http');
var https = require('https');
var zlib = require('zlib');
var Stream = require('stream');
var Stream__default = _interopDefault(Stream);
var encoding = require('encoding');

// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
// (MIT licensed)

const BUFFER = Symbol('buffer');
const TYPE = Symbol('type');
const CLOSED = Symbol('closed');

class Blob {
	constructor() {
		Object.defineProperty(this, Symbol.toStringTag, {
			value: 'Blob',
			writable: false,
			enumerable: false,
			configurable: true
		});

		this[CLOSED] = false;
		this[TYPE] = '';

		const blobParts = arguments[0];
		const options = arguments[1];

		const buffers = [];

		if (blobParts) {
			const a = blobParts;
			const length = Number(a.length);
			for (let i = 0; i < length; i++) {
				const element = a[i];
				let buffer;
				if (element instanceof Buffer) {
					buffer = element;
				} else if (ArrayBuffer.isView(element)) {
					buffer = new Buffer(new Uint8Array(element.buffer, element.byteOffset, element.byteLength));
				} else if (element instanceof ArrayBuffer) {
					buffer = new Buffer(new Uint8Array(element));
				} else if (element instanceof Blob) {
					buffer = element[BUFFER];
				} else {
					buffer = new Buffer(typeof element === 'string' ? element : String(element));
				}
				buffers.push(buffer);
			}
		}

		this[BUFFER] = Buffer.concat(buffers);

		let type = options && options.type !== undefined && String(options.type).toLowerCase();
		if (type && !/[^\u0020-\u007E]/.test(type)) {
			this[TYPE] = type;
		}
	}
	get size() {
		return this[CLOSED] ? 0 : this[BUFFER].length;
	}
	get type() {
		return this[TYPE];
	}
	get isClosed() {
		return this[CLOSED];
	}
	slice() {
		const size = this.size;

		const start = arguments[0];
		const end = arguments[1];
		let relativeStart, relativeEnd;
		if (start === undefined) {
			relativeStart = 0;
		} else if (start < 0) {
			relativeStart = Math.max(size + start, 0);
		} else {
			relativeStart = Math.min(start, size);
		}
		if (end === undefined) {
			relativeEnd = size;
		} else if (end < 0) {
			relativeEnd = Math.max(size + end, 0);
		} else {
			relativeEnd = Math.min(end, size);
		}
		const span = Math.max(relativeEnd - relativeStart, 0);

		const buffer = this[BUFFER];
		const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
		const blob = new Blob([], { type: arguments[2] });
		blob[BUFFER] = slicedBuffer;
		blob[CLOSED] = this[CLOSED];
		return blob;
	}
	close() {
		this[CLOSED] = true;
	}
}

Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
	value: 'BlobPrototype',
	writable: false,
	enumerable: false,
	configurable: true
});

/**
 * fetch-error.js
 *
 * FetchError interface for operational errors
 */

/**
 * Create FetchError instance
 *
 * @param   String      message      Error message for human
 * @param   String      type         Error type for machine
 * @param   String      systemError  For Node.js system error
 * @return  FetchError
 */
function FetchError(message, type, systemError) {
  Error.call(this, message);

  this.message = message;
  this.type = type;

  // when err.type is `system`, err.code contains system error code
  if (systemError) {
    this.code = this.errno = systemError.code;
  }

  // hide custom error implementation details from end-users
  Error.captureStackTrace(this, this.constructor);
}

FetchError.prototype = Object.create(Error.prototype);
FetchError.prototype.constructor = FetchError;
FetchError.prototype.name = 'FetchError';

/**
 * body.js
 *
 * Body interface provides common methods for Request and Response
 */

const DISTURBED = Symbol('disturbed');

/**
 * Body class
 *
 * Cannot use ES6 class because Body must be called with .call().
 *
 * @param   Stream  body  Readable stream
 * @param   Object  opts  Response options
 * @return  Void
 */
function Body(body) {
	var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
	    _ref$size = _ref.size;

	let size = _ref$size === undefined ? 0 : _ref$size;
	var _ref$timeout = _ref.timeout;
	let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;

	if (body == null) {
		// body is undefined or null
		body = null;
	} else if (typeof body === 'string') {
		// body is string
	} else if (body instanceof Blob) {
		// body is blob
	} else if (Buffer.isBuffer(body)) {
		// body is buffer
	} else if (body instanceof Stream__default) {
		// body is stream
	} else {
		// none of the above
		// coerce to string
		body = String(body);
	}
	this.body = body;
	this[DISTURBED] = false;
	this.size = size;
	this.timeout = timeout;
}

Body.prototype = {
	get bodyUsed() {
		return this[DISTURBED];
	},

	/**
  * Decode response as ArrayBuffer
  *
  * @return  Promise
  */
	arrayBuffer() {
		return consumeBody.call(this).then(function (buf) {
			return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
		});
	},

	/**
  * Return raw response as Blob
  *
  * @return Promise
  */
	blob() {
		let ct = this.headers && this.headers.get('content-type') || '';
		return consumeBody.call(this).then(function (buf) {
			return Object.assign(
			// Prevent copying
			new Blob([], {
				type: ct.toLowerCase()
			}), {
				[BUFFER]: buf
			});
		});
	},

	/**
  * Decode response as json
  *
  * @return  Promise
  */
	json() {
		return consumeBody.call(this).then(function (buffer) {
			return JSON.parse(buffer.toString());
		});
	},

	/**
  * Decode response as text
  *
  * @return  Promise
  */
	text() {
		return consumeBody.call(this).then(function (buffer) {
			return buffer.toString();
		});
	},

	/**
  * Decode response as buffer (non-spec api)
  *
  * @return  Promise
  */
	buffer() {
		return consumeBody.call(this);
	},

	/**
  * Decode response as text, while automatically detecting the encoding and
  * trying to decode to UTF-8 (non-spec api)
  *
  * @return  Promise
  */
	textConverted() {
		var _this = this;

		return consumeBody.call(this).then(function (buffer) {
			return convertBody(buffer, _this.headers);
		});
	}

};

Body.mixIn = function (proto) {
	for (const name of Object.getOwnPropertyNames(Body.prototype)) {
		// istanbul ignore else: future proof
		if (!(name in proto)) {
			const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
			Object.defineProperty(proto, name, desc);
		}
	}
};

/**
 * Decode buffers into utf-8 string
 *
 * @return  Promise
 */
function consumeBody(body) {
	var _this2 = this;

	if (this[DISTURBED]) {
		return Body.Promise.reject(new Error(`body used already for: ${this.url}`));
	}

	this[DISTURBED] = true;

	// body is null
	if (this.body === null) {
		return Body.Promise.resolve(new Buffer(0));
	}

	// body is string
	if (typeof this.body === 'string') {
		return Body.Promise.resolve(new Buffer(this.body));
	}

	// body is blob
	if (this.body instanceof Blob) {
		return Body.Promise.resolve(this.body[BUFFER]);
	}

	// body is buffer
	if (Buffer.isBuffer(this.body)) {
		return Body.Promise.resolve(this.body);
	}

	// istanbul ignore if: should never happen
	if (!(this.body instanceof Stream__default)) {
		return Body.Promise.resolve(new Buffer(0));
	}

	// body is stream
	// get ready to actually consume the body
	let accum = [];
	let accumBytes = 0;
	let abort = false;

	return new Body.Promise(function (resolve$$1, reject) {
		let resTimeout;

		// allow timeout on slow response body
		if (_this2.timeout) {
			resTimeout = setTimeout(function () {
				abort = true;
				reject(new FetchError(`Response timeout while trying to fetch ${_this2.url} (over ${_this2.timeout}ms)`, 'body-timeout'));
			}, _this2.timeout);
		}

		// handle stream error, such as incorrect content-encoding
		_this2.body.on('error', function (err) {
			reject(new FetchError(`Invalid response body while trying to fetch ${_this2.url}: ${err.message}`, 'system', err));
		});

		_this2.body.on('data', function (chunk) {
			if (abort || chunk === null) {
				return;
			}

			if (_this2.size && accumBytes + chunk.length > _this2.size) {
				abort = true;
				reject(new FetchError(`content size at ${_this2.url} over limit: ${_this2.size}`, 'max-size'));
				return;
			}

			accumBytes += chunk.length;
			accum.push(chunk);
		});

		_this2.body.on('end', function () {
			if (abort) {
				return;
			}

			clearTimeout(resTimeout);
			resolve$$1(Buffer.concat(accum));
		});
	});
}

/**
 * Detect buffer encoding and convert to target encoding
 * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
 *
 * @param   Buffer  buffer    Incoming buffer
 * @param   String  encoding  Target encoding
 * @return  String
 */
function convertBody(buffer, headers) {
	const ct = headers.get('content-type');
	let charset = 'utf-8';
	let res, str;

	// header
	if (ct) {
		res = /charset=([^;]*)/i.exec(ct);
	}

	// no charset in content type, peek at response body for at most 1024 bytes
	str = buffer.slice(0, 1024).toString();

	// html5
	if (!res && str) {
		res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
	}

	// html4
	if (!res && str) {
		res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);

		if (res) {
			res = /charset=(.*)/i.exec(res.pop());
		}
	}

	// xml
	if (!res && str) {
		res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
	}

	// found charset
	if (res) {
		charset = res.pop();

		// prevent decode issues when sites use incorrect encoding
		// ref: https://hsivonen.fi/encoding-menu/
		if (charset === 'gb2312' || charset === 'gbk') {
			charset = 'gb18030';
		}
	}

	// turn raw buffers into a single utf-8 buffer
	return encoding.convert(buffer, 'UTF-8', charset).toString();
}

/**
 * Clone body given Res/Req instance
 *
 * @param   Mixed  instance  Response or Request instance
 * @return  Mixed
 */
function clone(instance) {
	let p1, p2;
	let body = instance.body;

	// don't allow cloning a used body
	if (instance.bodyUsed) {
		throw new Error('cannot clone body after it is used');
	}

	// check that body is a stream and not form-data object
	// note: we can't clone the form-data object without having it as a dependency
	if (body instanceof Stream__default && typeof body.getBoundary !== 'function') {
		// tee instance body
		p1 = new Stream.PassThrough();
		p2 = new Stream.PassThrough();
		body.pipe(p1);
		body.pipe(p2);
		// set instance body to teed body and return the other teed body
		instance.body = p1;
		body = p2;
	}

	return body;
}

/**
 * Performs the operation "extract a `Content-Type` value from |object|" as
 * specified in the specification:
 * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
 *
 * This function assumes that instance.body is present and non-null.
 *
 * @param   Mixed  instance  Response or Request instance
 */
function extractContentType(instance) {
	const body = instance.body;

	// istanbul ignore if: Currently, because of a guard in Request, body
	// can never be null. Included here for completeness.

	if (body === null) {
		// body is null
		return null;
	} else if (typeof body === 'string') {
		// body is string
		return 'text/plain;charset=UTF-8';
	} else if (body instanceof Blob) {
		// body is blob
		return body.type || null;
	} else if (Buffer.isBuffer(body)) {
		// body is buffer
		return null;
	} else if (typeof body.getBoundary === 'function') {
		// detect form data input from form-data module
		return `multipart/form-data;boundary=${body.getBoundary()}`;
	} else {
		// body is stream
		// can't really do much about this
		return null;
	}
}

function getTotalBytes(instance) {
	const body = instance.body;

	// istanbul ignore if: included for completion

	if (body === null) {
		// body is null
		return 0;
	} else if (typeof body === 'string') {
		// body is string
		return Buffer.byteLength(body);
	} else if (body instanceof Blob) {
		// body is blob
		return body.size;
	} else if (Buffer.isBuffer(body)) {
		// body is buffer
		return body.length;
	} else if (body && typeof body.getLengthSync === 'function') {
		// detect form data input from form-data module
		if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
		body.hasKnownLength && body.hasKnownLength()) {
			// 2.x
			return body.getLengthSync();
		}
		return null;
	} else {
		// body is stream
		// can't really do much about this
		return null;
	}
}

function writeToStream(dest, instance) {
	const body = instance.body;

	if (body === null) {
		// body is null
		dest.end();
	} else if (typeof body === 'string') {
		// body is string
		dest.write(body);
		dest.end();
	} else if (body instanceof Blob) {
		// body is blob
		dest.write(body[BUFFER]);
		dest.end();
	} else if (Buffer.isBuffer(body)) {
		// body is buffer
		dest.write(body);
		dest.end();
	} else {
		// body is stream
		body.pipe(dest);
	}
}

// expose Promise
Body.Promise = global.Promise;

/**
 * A set of utilities borrowed from Node.js' _http_common.js
 */

/**
 * Verifies that the given val is a valid HTTP token
 * per the rules defined in RFC 7230
 * See https://tools.ietf.org/html/rfc7230#section-3.2.6
 *
 * Allowed characters in an HTTP token:
 * ^_`a-z  94-122
 * A-Z     65-90
 * -       45
 * 0-9     48-57
 * !       33
 * #$%&'   35-39
 * *+      42-43
 * .       46
 * |       124
 * ~       126
 *
 * This implementation of checkIsHttpToken() loops over the string instead of
 * using a regular expression since the former is up to 180% faster with v8 4.9
 * depending on the string length (the shorter the string, the larger the
 * performance difference)
 *
 * Additionally, checkIsHttpToken() is currently designed to be inlinable by v8,
 * so take care when making changes to the implementation so that the source
 * code size does not exceed v8's default max_inlined_source_size setting.
 **/
/* istanbul ignore next */
function isValidTokenChar(ch) {
  if (ch >= 94 && ch <= 122) return true;
  if (ch >= 65 && ch <= 90) return true;
  if (ch === 45) return true;
  if (ch >= 48 && ch <= 57) return true;
  if (ch === 34 || ch === 40 || ch === 41 || ch === 44) return false;
  if (ch >= 33 && ch <= 46) return true;
  if (ch === 124 || ch === 126) return true;
  return false;
}
/* istanbul ignore next */
function checkIsHttpToken(val) {
  if (typeof val !== 'string' || val.length === 0) return false;
  if (!isValidTokenChar(val.charCodeAt(0))) return false;
  const len = val.length;
  if (len > 1) {
    if (!isValidTokenChar(val.charCodeAt(1))) return false;
    if (len > 2) {
      if (!isValidTokenChar(val.charCodeAt(2))) return false;
      if (len > 3) {
        if (!isValidTokenChar(val.charCodeAt(3))) return false;
        for (var i = 4; i < len; i++) {
          if (!isValidTokenChar(val.charCodeAt(i))) return false;
        }
      }
    }
  }
  return true;
}
/**
 * True if val contains an invalid field-vchar
 *  field-value    = *( field-content / obs-fold )
 *  field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
 *  field-vchar    = VCHAR / obs-text
 *
 * checkInvalidHeaderChar() is currently designed to be inlinable by v8,
 * so take care when making changes to the implementation so that the source
 * code size does not exceed v8's default max_inlined_source_size setting.
 **/
/* istanbul ignore next */
function checkInvalidHeaderChar(val) {
  val += '';
  if (val.length < 1) return false;
  var c = val.charCodeAt(0);
  if (c <= 31 && c !== 9 || c > 255 || c === 127) return true;
  if (val.length < 2) return false;
  c = val.charCodeAt(1);
  if (c <= 31 && c !== 9 || c > 255 || c === 127) return true;
  if (val.length < 3) return false;
  c = val.charCodeAt(2);
  if (c <= 31 && c !== 9 || c > 255 || c === 127) return true;
  for (var i = 3; i < val.length; ++i) {
    c = val.charCodeAt(i);
    if (c <= 31 && c !== 9 || c > 255 || c === 127) return true;
  }
  return false;
}

/**
 * headers.js
 *
 * Headers class offers convenient helpers
 */

function sanitizeName(name) {
	name += '';
	if (!checkIsHttpToken(name)) {
		throw new TypeError(`${name} is not a legal HTTP header name`);
	}
	return name.toLowerCase();
}

function sanitizeValue(value) {
	value += '';
	if (checkInvalidHeaderChar(value)) {
		throw new TypeError(`${value} is not a legal HTTP header value`);
	}
	return value;
}

const MAP = Symbol('map');
class Headers {
	/**
  * Headers class
  *
  * @param   Object  headers  Response headers
  * @return  Void
  */
	constructor() {
		let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;

		this[MAP] = Object.create(null);

		if (init instanceof Headers) {
			const rawHeaders = init.raw();
			const headerNames = Object.keys(rawHeaders);

			for (const headerName of headerNames) {
				for (const value of rawHeaders[headerName]) {
					this.append(headerName, value);
				}
			}

			return;
		}

		// We don't worry about converting prop to ByteString here as append()
		// will handle it.
		if (init == null) {
			// no op
		} else if (typeof init === 'object') {
			const method = init[Symbol.iterator];
			if (method != null) {
				if (typeof method !== 'function') {
					throw new TypeError('Header pairs must be iterable');
				}

				// sequence<sequence<ByteString>>
				// Note: per spec we have to first exhaust the lists then process them
				const pairs = [];
				for (const pair of init) {
					if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
						throw new TypeError('Each header pair must be iterable');
					}
					pairs.push(Array.from(pair));
				}

				for (const pair of pairs) {
					if (pair.length !== 2) {
						throw new TypeError('Each header pair must be a name/value tuple');
					}
					this.append(pair[0], pair[1]);
				}
			} else {
				// record<ByteString, ByteString>
				for (const key of Object.keys(init)) {
					const value = init[key];
					this.append(key, value);
				}
			}
		} else {
			throw new TypeError('Provided initializer must be an object');
		}

		Object.defineProperty(this, Symbol.toStringTag, {
			value: 'Headers',
			writable: false,
			enumerable: false,
			configurable: true
		});
	}

	/**
  * Return first header value given name
  *
  * @param   String  name  Header name
  * @return  Mixed
  */
	get(name) {
		const list = this[MAP][sanitizeName(name)];
		if (!list) {
			return null;
		}

		return list.join(', ');
	}

	/**
  * Iterate over all headers
  *
  * @param   Function  callback  Executed for each item with parameters (value, name, thisArg)
  * @param   Boolean   thisArg   `this` context for callback function
  * @return  Void
  */
	forEach(callback) {
		let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

		let pairs = getHeaderPairs(this);
		let i = 0;
		while (i < pairs.length) {
			var _pairs$i = pairs[i];
			const name = _pairs$i[0],
			      value = _pairs$i[1];

			callback.call(thisArg, value, name, this);
			pairs = getHeaderPairs(this);
			i++;
		}
	}

	/**
  * Overwrite header values given name
  *
  * @param   String  name   Header name
  * @param   String  value  Header value
  * @return  Void
  */
	set(name, value) {
		this[MAP][sanitizeName(name)] = [sanitizeValue(value)];
	}

	/**
  * Append a value onto existing header
  *
  * @param   String  name   Header name
  * @param   String  value  Header value
  * @return  Void
  */
	append(name, value) {
		if (!this.has(name)) {
			this.set(name, value);
			return;
		}

		this[MAP][sanitizeName(name)].push(sanitizeValue(value));
	}

	/**
  * Check for header name existence
  *
  * @param   String   name  Header name
  * @return  Boolean
  */
	has(name) {
		return !!this[MAP][sanitizeName(name)];
	}

	/**
  * Delete all header values given name
  *
  * @param   String  name  Header name
  * @return  Void
  */
	delete(name) {
		delete this[MAP][sanitizeName(name)];
	}

	/**
  * Return raw headers (non-spec api)
  *
  * @return  Object
  */
	raw() {
		return this[MAP];
	}

	/**
  * Get an iterator on keys.
  *
  * @return  Iterator
  */
	keys() {
		return createHeadersIterator(this, 'key');
	}

	/**
  * Get an iterator on values.
  *
  * @return  Iterator
  */
	values() {
		return createHeadersIterator(this, 'value');
	}

	/**
  * Get an iterator on entries.
  *
  * This is the default iterator of the Headers object.
  *
  * @return  Iterator
  */
	[Symbol.iterator]() {
		return createHeadersIterator(this, 'key+value');
	}
}
Headers.prototype.entries = Headers.prototype[Symbol.iterator];

Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
	value: 'HeadersPrototype',
	writable: false,
	enumerable: false,
	configurable: true
});

function getHeaderPairs(headers, kind) {
	const keys = Object.keys(headers[MAP]).sort();
	return keys.map(kind === 'key' ? function (k) {
		return [k];
	} : function (k) {
		return [k, headers.get(k)];
	});
}

const INTERNAL = Symbol('internal');

function createHeadersIterator(target, kind) {
	const iterator = Object.create(HeadersIteratorPrototype);
	iterator[INTERNAL] = {
		target,
		kind,
		index: 0
	};
	return iterator;
}

const HeadersIteratorPrototype = Object.setPrototypeOf({
	next() {
		// istanbul ignore if
		if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
			throw new TypeError('Value of `this` is not a HeadersIterator');
		}

		var _INTERNAL = this[INTERNAL];
		const target = _INTERNAL.target,
		      kind = _INTERNAL.kind,
		      index = _INTERNAL.index;

		const values = getHeaderPairs(target, kind);
		const len = values.length;
		if (index >= len) {
			return {
				value: undefined,
				done: true
			};
		}

		const pair = values[index];
		this[INTERNAL].index = index + 1;

		let result;
		if (kind === 'key') {
			result = pair[0];
		} else if (kind === 'value') {
			result = pair[1];
		} else {
			result = pair;
		}

		return {
			value: result,
			done: false
		};
	}
}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));

Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
	value: 'HeadersIterator',
	writable: false,
	enumerable: false,
	configurable: true
});

/**
 * response.js
 *
 * Response class provides content decoding
 */

/**
 * Response class
 *
 * @param   Stream  body  Readable stream
 * @param   Object  opts  Response options
 * @return  Void
 */
class Response {
	constructor() {
		let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
		let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

		Body.call(this, body, opts);

		this.url = opts.url;
		this.status = opts.status || 200;
		this.statusText = opts.statusText || http.STATUS_CODES[this.status];

		this.headers = new Headers(opts.headers);

		Object.defineProperty(this, Symbol.toStringTag, {
			value: 'Response',
			writable: false,
			enumerable: false,
			configurable: true
		});
	}

	/**
  * Convenience property representing if the request ended normally
  */
	get ok() {
		return this.status >= 200 && this.status < 300;
	}

	/**
  * Clone this response
  *
  * @return  Response
  */
	clone() {

		return new Response(clone(this), {
			url: this.url,
			status: this.status,
			statusText: this.statusText,
			headers: this.headers,
			ok: this.ok
		});
	}
}

Body.mixIn(Response.prototype);

Object.defineProperty(Response.prototype, Symbol.toStringTag, {
	value: 'ResponsePrototype',
	writable: false,
	enumerable: false,
	configurable: true
});

/**
 * request.js
 *
 * Request class contains server only options
 */

const PARSED_URL = Symbol('url');

/**
 * Request class
 *
 * @param   Mixed   input  Url or Request instance
 * @param   Object  init   Custom options
 * @return  Void
 */
class Request {
	constructor(input) {
		let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

		let parsedURL;

		// normalize input
		if (!(input instanceof Request)) {
			if (input && input.href) {
				// in order to support Node.js' Url objects; though WHATWG's URL objects
				// will fall into this branch also (since their `toString()` will return
				// `href` property anyway)
				parsedURL = url.parse(input.href);
			} else {
				// coerce input to a string before attempting to parse
				parsedURL = url.parse(`${input}`);
			}
			input = {};
		} else {
			parsedURL = url.parse(input.url);
		}

		let method = init.method || input.method || 'GET';

		if ((init.body != null || input instanceof Request && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
			throw new TypeError('Request with GET/HEAD method cannot have body');
		}

		let inputBody = init.body != null ? init.body : input instanceof Request && input.body !== null ? clone(input) : null;

		Body.call(this, inputBody, {
			timeout: init.timeout || input.timeout || 0,
			size: init.size || input.size || 0
		});

		// fetch spec options
		this.method = method.toUpperCase();
		this.redirect = init.redirect || input.redirect || 'follow';
		this.headers = new Headers(init.headers || input.headers || {});

		if (init.body != null) {
			const contentType = extractContentType(this);
			if (contentType !== null && !this.headers.has('Content-Type')) {
				this.headers.append('Content-Type', contentType);
			}
		}

		// server only options
		this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
		this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
		this.counter = init.counter || input.counter || 0;
		this.agent = init.agent || input.agent;

		this[PARSED_URL] = parsedURL;
		Object.defineProperty(this, Symbol.toStringTag, {
			value: 'Request',
			writable: false,
			enumerable: false,
			configurable: true
		});
	}

	get url() {
		return url.format(this[PARSED_URL]);
	}

	/**
  * Clone this request
  *
  * @return  Request
  */
	clone() {
		return new Request(this);
	}
}

Body.mixIn(Request.prototype);

Object.defineProperty(Request.prototype, Symbol.toStringTag, {
	value: 'RequestPrototype',
	writable: false,
	enumerable: false,
	configurable: true
});

function getNodeRequestOptions(request) {
	const parsedURL = request[PARSED_URL];
	const headers = new Headers(request.headers);

	// fetch step 3
	if (!headers.has('Accept')) {
		headers.set('Accept', '*/*');
	}

	// Basic fetch
	if (!parsedURL.protocol || !parsedURL.hostname) {
		throw new TypeError('Only absolute URLs are supported');
	}

	if (!/^https?:$/.test(parsedURL.protocol)) {
		throw new TypeError('Only HTTP(S) protocols are supported');
	}

	// HTTP-network-or-cache fetch steps 5-9
	let contentLengthValue = null;
	if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
		contentLengthValue = '0';
	}
	if (request.body != null) {
		const totalBytes = getTotalBytes(request);
		if (typeof totalBytes === 'number') {
			contentLengthValue = String(totalBytes);
		}
	}
	if (contentLengthValue) {
		headers.set('Content-Length', contentLengthValue);
	}

	// HTTP-network-or-cache fetch step 12
	if (!headers.has('User-Agent')) {
		headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
	}

	// HTTP-network-or-cache fetch step 16
	if (request.compress) {
		headers.set('Accept-Encoding', 'gzip,deflate');
	}
	if (!headers.has('Connection') && !request.agent) {
		headers.set('Connection', 'close');
	}

	// HTTP-network fetch step 4
	// chunked encoding is handled by Node.js

	return Object.assign({}, parsedURL, {
		method: request.method,
		headers: headers.raw(),
		agent: request.agent
	});
}

/**
 * index.js
 *
 * a request API compatible with window.fetch
 */

/**
 * Fetch function
 *
 * @param   Mixed    url   Absolute url or Request instance
 * @param   Object   opts  Fetch options
 * @return  Promise
 */
function fetch(url$$1, opts) {

	// allow custom promise
	if (!fetch.Promise) {
		throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
	}

	Body.Promise = fetch.Promise;

	// wrap http.request into fetch
	return new fetch.Promise(function (resolve$$1, reject) {
		// build request object
		const request = new Request(url$$1, opts);
		const options = getNodeRequestOptions(request);

		const send = (options.protocol === 'https:' ? https : http).request;

		// http.request only support string as host header, this hack make custom host header possible
		if (options.headers.host) {
			options.headers.host = options.headers.host[0];
		}

		// send request
		const req = send(options);
		let reqTimeout;

		if (request.timeout) {
			req.once('socket', function (socket) {
				reqTimeout = setTimeout(function () {
					req.abort();
					reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
				}, request.timeout);
			});
		}

		req.on('error', function (err) {
			clearTimeout(reqTimeout);
			reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
		});

		req.on('response', function (res) {
			clearTimeout(reqTimeout);

			// handle redirect
			if (fetch.isRedirect(res.statusCode) && request.redirect !== 'manual') {
				if (request.redirect === 'error') {
					reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
					return;
				}

				if (request.counter >= request.follow) {
					reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
					return;
				}

				if (!res.headers.location) {
					reject(new FetchError(`redirect location header missing at: ${request.url}`, 'invalid-redirect'));
					return;
				}

				// per fetch spec, for POST request with 301/302 response, or any request with 303 response, use GET when following redirect
				if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
					request.method = 'GET';
					request.body = null;
					request.headers.delete('content-length');
				}

				request.counter++;

				resolve$$1(fetch(url.resolve(request.url, res.headers.location), request));
				return;
			}

			// normalize location header for manual redirect mode
			const headers = new Headers();
			for (const name of Object.keys(res.headers)) {
				if (Array.isArray(res.headers[name])) {
					for (const val of res.headers[name]) {
						headers.append(name, val);
					}
				} else {
					headers.append(name, res.headers[name]);
				}
			}
			if (request.redirect === 'manual' && headers.has('location')) {
				headers.set('location', url.resolve(request.url, headers.get('location')));
			}

			// prepare response
			let body = res.pipe(new Stream.PassThrough());
			const response_options = {
				url: request.url,
				status: res.statusCode,
				statusText: res.statusMessage,
				headers: headers,
				size: request.size,
				timeout: request.timeout
			};

			// HTTP-network fetch step 16.1.2
			const codings = headers.get('Content-Encoding');

			// HTTP-network fetch step 16.1.3: handle content codings

			// in following scenarios we ignore compression support
			// 1. compression support is disabled
			// 2. HEAD request
			// 3. no Content-Encoding header
			// 4. no content response (204)
			// 5. content not modified response (304)
			if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
				resolve$$1(new Response(body, response_options));
				return;
			}

			// For Node v6+
			// Be less strict when decoding compressed responses, since sometimes
			// servers send slightly invalid responses that are still accepted
			// by common browsers.
			// Always using Z_SYNC_FLUSH is what cURL does.
			const zlibOptions = {
				flush: zlib.Z_SYNC_FLUSH,
				finishFlush: zlib.Z_SYNC_FLUSH
			};

			// for gzip
			if (codings == 'gzip' || codings == 'x-gzip') {
				body = body.pipe(zlib.createGunzip(zlibOptions));
				resolve$$1(new Response(body, response_options));
				return;
			}

			// for deflate
			if (codings == 'deflate' || codings == 'x-deflate') {
				// handle the infamous raw deflate response from old servers
				// a hack for old IIS and Apache servers
				const raw = res.pipe(new Stream.PassThrough());
				raw.once('data', function (chunk) {
					// see http://stackoverflow.com/questions/37519828
					if ((chunk[0] & 0x0F) === 0x08) {
						body = body.pipe(zlib.createInflate());
					} else {
						body = body.pipe(zlib.createInflateRaw());
					}
					resolve$$1(new Response(body, response_options));
				});
				return;
			}

			// otherwise, use response as-is
			resolve$$1(new Response(body, response_options));
		});

		writeToStream(req, request);
	});
}

/**
 * Redirect code matching
 *
 * @param   Number   code  Status code
 * @return  Boolean
 */
fetch.isRedirect = function (code) {
	return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
};

// expose Promise
fetch.Promise = global.Promise;

module.exports = exports = fetch;
exports.Headers = Headers;
exports.Request = Request;
exports.Response = Response;
exports.FetchError = FetchError;


text:
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
 *
 *   Copyright (C) 2004 University of Chicago.
 *   See COPYRIGHT notice in top-level directory.
 */

#include "adio.h"

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

void ADIOI_GEN_Resize(ADIO_File fd, ADIO_Offset size, int *error_code)
{
    int err, rank;
    static char myname[] = "ADIOI_GEN_RESIZE";

    MPI_Comm_rank(fd->comm, &rank);

    /* first aggregator performs ftruncate() */
    if (rank == fd->hints->ranklist[0]) {
    ADIOI_Assert(size == (off_t) size);
	err = ftruncate(fd->fd_sys, (off_t)size);
    }

    /* bcast return value */
    MPI_Bcast(&err, 1, MPI_INT, fd->hints->ranklist[0], fd->comm);

    /* --BEGIN ERROR HANDLING-- */
    if (err == -1) {
	*error_code = ADIOI_Err_create_code(myname, fd->filename, errno);
	return;
    }
    /* --END ERROR HANDLING-- */

    *error_code = MPI_SUCCESS;
}

redpajama_set_name: RedPajamaGithub


text:
This is the Ruby adapter for the Raygun error reporter, https://raygun.com.

## Installation

Add this line to your application's Gemfile:

    gem 'raygun4ruby'

And then execute:

    $ bundle install

Or install it yourself as:

    $ gem install raygun4ruby

## Usage

### Rails 3/4/5

Run:

    rails g raygun:install YOUR_API_KEY_HERE

You can find your API key in the [Raygun app](https://app.raygun.com/)

You can then test your Raygun integration by running:

    rake raygun:test

You should see an "ItWorksException" appear in your Raygun dashboard. You're ready to zap those errors!

NB: Raygun4Ruby currently requires Ruby >= 2.0

Note that the generator will create a file in `config/initializers` called "raygun.rb". If you need to do any further configuration or customization of Raygun, that's the place to do it!

By default the Rails integration is set to only report Exceptions in Production. To change this behaviour, set `config.enable_reporting` to something else in `config/initializers/raygun.rb`.

### Rails 2

Raygun4Ruby doesn't currently support Rails 2. If you'd like Rails 2 support, [drop us a line](https://raygun.com/forums).

### Sinatra

To enable exception tracking in Sinatra, just add configure Raygun and use the Rack middleware in your app:

```ruby
require 'raygun4ruby'
Raygun.setup do |config|
  config.api_key = "YOUR_API_KEY_HERE"
end
use Raygun::Middleware::RackExceptionInterceptor
```

### Standalone / Manual Exception Tracking

```ruby

require 'rubygems'
require 'raygun4ruby'

Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.filter_parameters = [ :password, :card_number, :cvv ] # don't forget to filter out sensitive parameters
  config.enable_reporting = Rails.env.production? # true to send errors, false to not log
end

begin
  # your lovely code here
rescue => e
  Raygun.track_exception(e)
end

# You may also pass a user object as the third argument to allow affected customers, like so
begin
  # your lovely code here
rescue => e
  # The second argument is the request environment variables
  Raygun.track_exception(e, {}, user)
end
```

You can also pass a Hash as the second parameter to `track_exception`. It should look like a [Rack Env Hash](https://github.com/rack/rack/blob/master/SPEC.rdoc#label-The+Environment)

### Customizing The Parameter Filtering

If you'd like to customize how parameters are filtered, you can pass a `Proc` to `filter_parameters`. Raygun4Ruby will yield the params hash to the block, and the return value will be sent along with your error.

```ruby
Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.filter_parameters do |params|
    params.slice("only", "a", "few", "keys") # note that Hash#slice is in ActiveSupport
  end
end
```

### Recording Breadcrumbs

Breadcrumbs let you provide logging points in your code that will be collected and sent along with any exception sent to Raygun. This lets you have a better understanding of the events that happened in the system that lead up to the exception.

1. Include it as a module in your class
```ruby
class SomeClass
  include Raygun::Breadcrumbs

  def some_method
    record_breadcrumb(
      message: "<log message goes here>",
      category: "some category to group them by, maybe authentication or external-apis for example",
      level: :info, # or debug or warning etc, you can configure what level will get sent
      metadata: {custom_data: 'can go here'},
    )
  end
end
```
This has the added benefit of recording the class the breadcrumb was recorded from automatically

2. Call the `record_breadcrumb` method manually
```ruby
def some_method
  Raygun.record_breadcrumb(
    message: "<log message goes here>",
    category: "some category to group them by, maybe authentication or external-apis for example",
    level: :info, # or debug or warning etc, you can configure what level will get sent
    metadata: {custom_data: 'can go here'},

    # You can also set the class the breadcrumb was logged from
    # It will only be set automatically using the included module approach
    # Method and line number will get added automatically
    class_name: self.class.name
  )
end
```

If you are using Sinatra or another rack framework you will need to include the Breadcrumbs middleware, this is used for storing the breadcrumbs during a request
`use Raygun::Middleware::BreadcrumbsStoreInitializer`
(this must be before you `use` the `Raygun::Middleware::RackExceptionInterceptor`)

If you are using a non web based Ruby application you will have to call `Raygun::Breadcrumbs::Store.initialize` during your applications boot process. The store is per thread, but I have not tested it in a multi threaded application.

### Filtering the payload by whitelist

As an alternative to the above, you can also opt-in to the keys/values to be sent to Raygun by providing a specific whitelist of the keys you want to transmit.

This disables the blacklist filtering above (`filter_parameters`), and is applied to the entire payload (error, request, environment and custom data included), not just the request parameters.

In order to opt-in to this feature, set `filter_payload_with_whitelist` to `true`, and specify a shape of what keys you want (the default is below which is to allow everything through, this also means that the query parameters filtered out by default like password, creditcard etc will not be unless changed):

```ruby
Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.filter_payload_with_whitelist = true

  config.whitelist_payload_shape = {
      machineName: true,
      version: true,
      error: true,
      userCustomData: true,
      tags: true,
      request: {
        hostName: true,
        url: true,
        httpMethod: true,
        iPAddress: true,
        queryString: true,
        headers: true,
        form: {}, # Set to empty hash so that it doesn't just filter out the whole thing, but instead filters out each individual param
        rawData: true
      }
    }
end
```

Alternatively, provide a Proc to filter the payload using your own logic:

```ruby
Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.filter_payload_with_whitelist = true

  config.whitelist_payload_shape do |payload|
    # Return the payload mutated into your desired form
    payload
  end
end
```

### Custom User Data
Custom data can be added to `track_exception` by passing a custom_data key in the second parameter hash.

```ruby
begin
  # more lovely code
rescue Exception => e
  Raygun.track_exception(e, custom_data: {my: 'custom data', goes: 'here'})
end
```

Custom data can also be specified globally either by setting `config.custom_data` to a hash

```ruby
Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.custom_data = {custom_data: 'goes here'}
end
```

or to a proc, which gets passed the exception and environment hash

```ruby
Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.custom_data do |e, env|
    {message: e.message, server: env["SERVER_NAME"]}
  end
end
```

### Ignoring Some Errors

You can ignore certain types of Exception using the `ignore` option in the setup block, like so:

```ruby
Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.ignore  << ['MyApp::AnExceptionIDontCareAbout']
end
```

The following exceptions are ignored by default:

```
ActiveRecord::RecordNotFound
ActionController::RoutingError
ActionController::InvalidAuthenticityToken
ActionDispatch::ParamsParser::ParseError
CGI::Session::CookieStore::TamperedWithCookie
ActionController::UnknownAction
AbstractController::ActionNotFound
Mongoid::Errors::DocumentNotFound
```

 [You can see this here](https://github.com/MindscapeHQ/raygun4ruby/blob/master/lib/raygun/configuration.rb#L90) and unignore them if needed by doing the following:

```ruby
Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.ignore.delete('ActionController::InvalidAuthenticityToken')
end
```

### Using a Proxy

You can pass proxy settings using the `proxy_settings` config option.

```ruby
Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.proxy_settings = { host: "localhost", port: 8888 }
end
```

### Affected Customers

Raygun can now track how many customers have been affected by an error.

By default, Raygun looks for a method called `current_user` on your controller, and it will populate the customer's information based on a default method name mapping.

(e.g Raygun will call `email` to populate the customer's email, and `first_name` for the customer's first name)

You can inspect and customize this mapping using `config.affected_user_mapping`, like so:

```ruby
Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.affected_user_method = :my_current_user # `current_user` by default
  # To augment the defaults with your unique methods you can do the following
  config.affected_user_mapping = Raygun::AffectedUser::DEFAULT_MAPPING.merge({
    identifier: :some_custom_unique_identifier,
    # If you set the key to a proc it will be passed the user object and you can construct the value your self
    full_name: ->(user) { "#{user.first_name} #{user.last_name}" }
  })
end
```

To see the defaults check out [affected_user.rb](https://github.com/MindscapeHQ/raygun4ruby/tree/master/lib/raygun/affected_user.rb)

If you're using Rails, most authentication systems will have this method set and you should be good to go.

The count of unique affected customers will appear on the error group in the Raygun dashboard. If your customer has an `Email` attribute, and that email has a Gravatar associated with that address, you will also see your customer's avatar.

If you wish to keep it anonymous, you could set this identifier to something like `SecureRandom.uuid` and store that in a cookie, like so:

```ruby
class ApplicationController < ActionController::Base

  def raygun_user
    cookies.permanent[:raygun_user_identifier] ||= SecureRandom.uuid
  end

end
```

(Remember to set `affected_user_method` to `:raygun_user` in your config block...)

### Version tracking

Raygun can attach the version of your application to its error reports. In your Raygun.setup block, set `version` to the current version of your app.

```ruby
Raygun.setup do |config|
  config.version = "1.0.0.4" # you could also pull this from ENV or however you want to set it.
end
```

### Tags

Tags can be added to `track_exception` by passing a tags key in the second parameter hash.

```ruby
begin
  # more lovely code
rescue Exception => e
  Raygun.track_exception(e, tags: ['my', 'tags', 'go here'])
end
```

Tags can also be specified globally either by setting `config.custom_data` to an array

```ruby
Raygun.setup do |config|
  config.tags = ['heroku']
end
```

or to a proc, which gets passed the exception and environment hash. This proc _must_ return an array of strings

```ruby
Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.tags do |e, env|
    [env["SERVER_NAME"]]
  end
end
```

### Resque Error Tracking

Raygun4Ruby also includes a Resque failure backend. You should include it inside your Resque initializer (usually something like `config/initializers/load_resque.rb`)

```ruby
require 'resque/failure/multiple'
require 'resque/failure/raygun'
require 'resque/failure/redis'

Resque::Failure::Multiple.classes = [Resque::Failure::Redis, Resque::Failure::Raygun]
Resque::Failure.backend = Resque::Failure::Multiple
```

### Sidekiq Error Tracking

Raygun4Ruby can track errors from Sidekiq (2.x or 3+). All you need to do is add the line:

```ruby
  require 'raygun/sidekiq'
```

Either in your Raygun initializer or wherever else takes your fancy :)

#### Affected Customers in Sidekiq

To track affected customers, define a class method on your worker class that returns a user object.
Make sure the name of this method is the same as whatever you have defined as the `affected_user_method` in your Raygun configuration and that it returns an object that fits the mappings defined in `affected_user_mapping`
If you have not changed these, refer to [Affected customers](#affected-customers) for the defaults

```ruby
class FailingWorker
  include Sidekiq::Worker

  def perform(arg1, arg2)
  end

  # Your method must accept an array of arguments
  # These will be the same as those passed to `perform`
  def self.current_user(args)
    arg1 = args[0]
    arg2 = args[1]

    user = User.find_by(name: arg1)

    # Your method must return a user object
    user
  end
```

### Other Configuration options

For a complete list of configuration options see the [configuration.rb](https://github.com/MindscapeHQ/raygun4ruby/blob/master/lib/raygun/configuration.rb) file

## Found a bug?

Oops! Just let us know by opening an Issue on Github.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Building

1. Build the gem (`gem build raygun4ruby.gemspec`) - don't bother trying to build it on Windows,
the resulting Gem won't work.
2. Install the gem (`gem install raygun4ruby-VERSION.gem`)


text:
import { ListItem, ListSelector, ListSelectorConfig } from './components/listselector';
import { UIInstanceManager } from './uimanager';
import { AudioTrackEvent, PlayerAPI, AudioTrack } from 'bitmovin-player';
import { i18n } from './localization/i18n';

/**
 * Helper class to handle all audio tracks related events
 *
 * This class listens to player events as well as the `ListSelector` event if selection changed
 */
export class AudioTrackSwitchHandler {

  private player: PlayerAPI;
  private listElement: ListSelector<ListSelectorConfig>;
  private uimanager: UIInstanceManager;

  constructor(player: PlayerAPI, element: ListSelector<ListSelectorConfig>, uimanager: UIInstanceManager) {
    this.player = player;
    this.listElement = element;
    this.uimanager = uimanager;

    this.bindSelectionEvent();
    this.bindPlayerEvents();
    this.refreshAudioTracks();
  }

  private bindSelectionEvent(): void {
    this.listElement.onItemSelected.subscribe((_, value: string) => {
      this.player.setAudio(value);
    });
  }

  private bindPlayerEvents(): void {
    // Update selection when selected track has changed
    this.player.on(this.player.exports.PlayerEvent.AudioChanged, this.selectCurrentAudioTrack);
    // Update tracks when source goes away
    this.player.on(this.player.exports.PlayerEvent.SourceUnloaded, this.refreshAudioTracks);
    // Update tracks when the period within a source changes
    this.player.on(this.player.exports.PlayerEvent.PeriodSwitched, this.refreshAudioTracks);
    // Update tracks when a track is added or removed
    this.player.on(this.player.exports.PlayerEvent.AudioAdded, this.addAudioTrack);
    this.player.on(this.player.exports.PlayerEvent.AudioRemoved, this.removeAudioTrack);
    this.uimanager.getConfig().events.onUpdated.subscribe(this.refreshAudioTracks);
  }

  private addAudioTrack = (event: AudioTrackEvent) => {
    const audioTrack = event.track;
    if (!this.listElement.hasItem(audioTrack.id)) {
      this.listElement.addItem(audioTrack.id, i18n.getLocalizer(audioTrack.label), true);
    }
  };

  private removeAudioTrack = (event: AudioTrackEvent) => {
    const audioTrack = event.track;
    if (this.listElement.hasItem(audioTrack.id)) {
      this.listElement.removeItem(audioTrack.id);
    }
  };

  private selectCurrentAudioTrack = () => {
    let currentAudioTrack = this.player.getAudio();

    // HLS streams don't always provide this, so we have to check
    if (currentAudioTrack) {
      this.listElement.selectItem(currentAudioTrack.id);
    }
  };

  private refreshAudioTracks = () => {
    const audioTracks = this.player.getAvailableAudio();
    const audioTrackToListItem = (audioTrack: AudioTrack): ListItem => {
      return { key: audioTrack.id, label: audioTrack.label };
    };

    this.listElement.synchronizeItems(audioTracks.map(audioTrackToListItem));
    this.selectCurrentAudioTrack();
  };
}


text:
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<title>Other Toolkits</title>
<link rel="stylesheet" type="text/css" href="../style.css">

Comparing CD with Other Graphics Libraries

There are other graphics libraries, with some portability among operational
  systems, available on the Internet. Among them we can highlight:

GKS - Very complete 2D and 3D graphics library, but
    with limited image resources. It is an ISO standard, and it implementations
    are usually commercial. Tecgraf has an implementation of GKS which is no
    longer used, being replaced by CD.
    http://www.bsi.org.uk/sc24/.

    --------------------

Mesa - 3D graphics library with support to the OpenGL
    standard. Implemented in C. Aimed only at display, with attribute functions
    for illumination and shading features.
    http://www.mesa3d.org/.

OpenGL - 3D graphics library with some 2D support.
    Aimed only at display. A window CD canvas can coexist with an OpenGL canvas
    at the same time. Note: When Double Buffer is used, do not forget to swap
    buffer before redrawing with the CD library.
    http://www.opengl.org.

    --------------------

GGI - 2D graphics library aimed only at display.
    http://www.ggi-project.org/.

GD - Library only for drawing on images, saves PNG
    files. Implemented in C.
    http://www.boutell.com/gd/.

GDK - Used by the GTK user interface toolkit.
    Implemented in C. Aimed only at display, and contains several functions for
    managing windows, keyboard and mouse.
    http://www.gtk.org/.

CAIRO - A vector graphics library designed to provide
    high-quality display and print output. Very interesting, lots of functions,
    usually render in bitmaps on native systems. Display hardware acceleration is used
    almost only to display the bitmaps. Although it can reach high quality
    rendering.
    http://cairographics.org/.

AGG - The AGG Project (Anti-Grain Geometry). High
    Fidelity 2D Graphics A High Quality Rendering Engine for C++. Renders to a
    bitmap then transfer it to the native system, just like Cairo. GNU GPL
    license.  http://www.antigrain.com/

Most of them are aimed only at one type of driver, usually display or
  images, and sometimes user interface routines were also included. Others add
  3D drawing routines, as well as scene illumination routines. All this
  unnecessarily increases their complexity and does not make them more complete
  as 2D graphic libraries.

There are also several Graphics User Interface libraries that contain
  drawing functions, like Qt and wxWidgets.

As to performance, CD is as good as any other, in some cases having a
  better performance. Thus, the CD library offers unique features and quality as
  a portable 2D graphic library.


text:
package deliverycube.common.atg.componentresolver.jndi;

import javax.naming.Context;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

import atg.core.util.StringUtils;
import deliverycube.common.atg.componentresolver.ComponentResolver;
import deliverycube.common.atg.componentresolver.UnknownComponentException;

/**
 * Implementation of the {@link ComponentResolver} interface that uses the JNDI to resolve components.
 *
 * This is a stateful object - the componentName property must be set.
 *
 * @author Vihung Marathe
 *
 */
public class JndiComponentResolver implements ComponentResolver {
    private static final Logger log = Logger.getLogger(JndiComponentResolver.class);

    /**
     *
     */
    public JndiComponentResolver() {
        super();
    }

    /**
     * Uses JNDI to resolve components in any scope at invocation time
     *
     * @throws IllegalArgumentException
     *             if no componentName has been set
     * @throws UnknownComponentException
     *             if the component cannot be resolved
     * @see deliverycube.deliverycube.common.atg.componentresolver.ComponentResolver#resolveComponent()
     */
    @Override
    public Object resolveComponent() throws UnknownComponentException {
        if (log.isDebugEnabled()) log.debug("Invoked. componentName=" + mComponentName);
        if (StringUtils.isEmpty(mComponentName)) throw new IllegalArgumentException("No componentName set");

        final String jndiName = "dynamo:" + mComponentName;
        if (log.isTraceEnabled()) log.trace("jndiName=" + jndiName);

        try {
            final Context ctx = new javax.naming.InitialContext();

            final Object component = ctx.lookup(jndiName);
            if (log.isTraceEnabled()) log.trace("resolveComponent(): component=" + component);
            if (log.isTraceEnabled()) log.trace("resolveComponent(): component.class=" + component.getClass().getName());

            if (component == null) {
                throw new UnknownComponentException("Component: " + jndiName + " could not be resolved");
            }

            return component;
        } catch (final NamingException e) {
            throw new UnknownComponentException("Component: " + jndiName + " could not be resolved", e);
        }
    }

    /** Handle to the Component Name */
    private String mComponentName;

    /**
     * Accessor for the componentName property
     *
     * @return the componentName
     */
    public String getComponentName() {
        return mComponentName;
    }

    /**
     * Modifier for the componentName property
     *
     * @param pComponentName
     *            the componentName to set
     */
    public void setComponentName(final String pComponentName) {
        mComponentName = pComponentName;
    }

}


text:
<?php

namespace PHPExiftool\Driver\Tag\XMPMP1;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class PipelineVersion extends AbstractTag
{

    protected $Id = 'PipelineVersion';

    protected $Name = 'PipelineVersion';

    protected $FullName = 'Microsoft::MP1';

    protected $GroupName = 'XMP-MP1';

    protected $g0 = 'XMP';

    protected $g1 = 'XMP-MP1';

    protected $g2 = 'Image';

    protected $Type = 'string';

    protected $Writable = true;

    protected $Description = 'Pipeline Version';

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>GenericGF</title>
<meta name="date" content="2012-10-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.zxing.common.reedsolomon

Class GenericGF

java.lang.Object

com.google.zxing.common.reedsolomon.GenericGF

public final class GenericGF
extends java.lang.Object

This class contains utility methods for performing mathematical operations over
 the Galois Fields. Operations use a given primitive polynomial in calculations.

Throughout this package, elements of the GF are represented as an int
 for convenience and speed (but at the cost of memory).

Author:

Sean Owen, David Olivier

Field Summary

Fields

Modifier and Type
Field and Description

static GenericGF
AZTEC_DATA_10

static GenericGF
AZTEC_DATA_12

static GenericGF
AZTEC_DATA_6

static GenericGF
AZTEC_DATA_8

static GenericGF
AZTEC_PARAM

static GenericGF
DATA_MATRIX_FIELD_256

static GenericGF
MAXICODE_FIELD_64

static GenericGF
QR_CODE_FIELD_256

Constructor Summary

Constructors

Constructor and Description

GenericGF(int primitive,
         int size)

Create a representation of GF(size) using the given primitive polynomial.

Method Summary

Methods

Modifier and Type
Method and Description

int
getSize()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

AZTEC_DATA_12

public static final GenericGF AZTEC_DATA_12

AZTEC_DATA_10

public static final GenericGF AZTEC_DATA_10

AZTEC_DATA_6

public static final GenericGF AZTEC_DATA_6

AZTEC_PARAM

public static final GenericGF AZTEC_PARAM

QR_CODE_FIELD_256

public static final GenericGF QR_CODE_FIELD_256

DATA_MATRIX_FIELD_256

public static final GenericGF DATA_MATRIX_FIELD_256

AZTEC_DATA_8

public static final GenericGF AZTEC_DATA_8

MAXICODE_FIELD_64

public static final GenericGF MAXICODE_FIELD_64

Constructor Detail

GenericGF

public GenericGF(int primitive,
         int size)

Create a representation of GF(size) using the given primitive polynomial.

Parameters:

primitive - irreducible polynomial whose coefficients are represented by
  the bits of an int, where the least-significant bit represents the constant
  coefficient

Method Detail

getSize

public int getSize()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""Input function to observation sequence model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.compat.v1 as tf
from tensorflow.compat.v1 import estimator as tf_estimator
from tensorflow.contrib import data as contrib_data

CONTEXT_KEY_PREFIX = 'c-'
SEQUENCE_KEY_PREFIX = 's-'

def _example_index_to_sparse_index(example_indices, batch_size):
  """Creates a 2D sparse index tensor from a list of 1D example indices.

  For example, this would do the transformation:
  [0, 0, 0, 1, 3, 3] -> [[0,0], [0,1], [0,2], [1,0], [3,0], [3,1]]

  The second column of the output tensor is the running count of the occurrences
  of that example index.

  Args:
    example_indices: A sorted 1D Tensor with example indices.
    batch_size: The batch_size. Could be larger than max(example_indices) if the
      last examples of the batch do not have the feature present.

  Returns:
    The sparse index tensor.
    The maxmium length of a row in this tensor.
  """
  binned_counts = tf.bincount(example_indices, minlength=batch_size)
  max_len = tf.to_int64(tf.reduce_max(binned_counts))
  return tf.where(tf.sequence_mask(binned_counts)), max_len

def _remove_empty_timesteps(sp_tensor):
  """Creates a 3D SparseTensor skipping empty time steps.

  Args:
    sp_tensor: A SparseTensor with at least 2 dimensions (subsequent ones will
      be ignored and simply flattened into the 2nd dimension).

  Returns:
    A 3D SparseTensor with index 0 for dimension 3 and a series from [0,..k]
    for dimension 1 for each batch entry.
  """

  batch_size = tf.to_int32(sp_tensor.dense_shape[0])
  indices, max_len = _example_index_to_sparse_index(
      tf.to_int32(sp_tensor.indices[:, 0]), batch_size)
  indices = tf.concat([indices, tf.zeros_like(indices[:, 0:1])], axis=1)
  return tf.SparseTensor(
      indices=indices,
      values=sp_tensor.values,
      dense_shape=[batch_size, max_len, 1])

def _extend_with_dummy(extend_with, to_extend, dummy_value='n/a'):
  """Extends one SparseTensor with dummy_values at positions of other."""
  dense_shape = tf.to_int64(
      tf.concat([[tf.shape(extend_with)[0]],
                 [tf.maximum(tf.shape(extend_with)[1],
                             tf.shape(to_extend)[1])],
                 [tf.maximum(tf.shape(extend_with)[2],
                             tf.shape(to_extend)[2])]],
                axis=0))
  additional_indices = tf.sets.set_difference(
      tf.SparseTensor(
          indices=extend_with.indices,
          values=tf.zeros_like(extend_with.values, dtype=tf.int32),
          dense_shape=dense_shape),
      tf.SparseTensor(
          indices=to_extend.indices,
          values=tf.zeros([tf.shape(to_extend.indices)[0]], dtype=tf.int32),
          dense_shape=dense_shape)).indices
  # Supply defaults for all other indices.
  default = tf.tile(
      tf.constant([dummy_value]), multiples=[tf.shape(additional_indices)[0]])

  string_value = (
      tf.as_string(to_extend.values)
      if to_extend.values.dtype != tf.string else to_extend.values)
  return tf.sparse_reorder(
      tf.SparseTensor(
          indices=tf.concat([to_extend.indices, additional_indices], axis=0),
          values=tf.concat([string_value, default], axis=0),
          dense_shape=dense_shape))

def _sparse_intersect_indices(sp_tensor, required_sp_tensor):
  """Filters timestamps in sp_tensor to those present in required_sp_tensor."""
  # We extend both sp_tensor and required_sp_tensor with each others indices
  # so that they have the same indices.
  # E.g. their dense representation of one batch entry could be:
  # [dummy, dummy, 1 ]
  dummy_value = 'n/a'
  dummy_required_sp_tensor = _extend_with_dummy(
      sp_tensor, required_sp_tensor, dummy_value)
  dummy_sp_tensor = _extend_with_dummy(required_sp_tensor, sp_tensor,
                                       dummy_value)
  # We get rid to dummy values both for indices in the required_sp_tensor and
  # the sp_tensor.
  # First get rid of indices with dummy values in dummy_required_sp_tensor.
  in_required = tf.sparse_retain(
      dummy_sp_tensor,
      tf.logical_not(tf.equal(dummy_required_sp_tensor.values, dummy_value)))
  # Remove empty timesteps so that the timesteps align with the original
  # required_sp_tensor.
  # Then remove the indices with dummy values.
  in_required = tf.sparse_retain(
      _remove_empty_timesteps(in_required),
      tf.logical_not(tf.equal(in_required.values, dummy_value)))
  if sp_tensor.values.dtype != tf.string:
    in_required = tf.SparseTensor(
        indices=in_required.indices, dense_shape=in_required.dense_shape,
        values=tf.strings.to_number(
            in_required.values, out_type=sp_tensor.values.dtype))
  return in_required

def _dense_intersect_indices(tensor, required_sp_tensor):
  required_2d_indices = required_sp_tensor.indices[:, 0:2]
  values = tf.gather_nd(tensor, required_2d_indices)
  indices, max_len = _example_index_to_sparse_index(
      tf.to_int32(required_sp_tensor.indices[:, 0]),
      tf.to_int32(required_sp_tensor.dense_shape[0]))
  return tf.expand_dims(
      tf.sparse_to_dense(
          indices, tf.stack([required_sp_tensor.dense_shape[0], max_len]),
          values),
      axis=2)

def _intersect_indices(sequence_feature, required_sp_tensor):
  if isinstance(sequence_feature, tf.SparseTensor):
    return _sparse_intersect_indices(sequence_feature, required_sp_tensor)
  else:
    return _dense_intersect_indices(sequence_feature, required_sp_tensor)

def _make_parsing_fn(mode, label_name, sequence_features,
                     dense_sequence_feature):
  """Creates an input function to an estimator.

  Args:
    mode: The execution mode, as defined in tf.estimator.ModeKeys.
    label_name: Name of the label present as context feature in the
      SequenceExamples.
    sequence_features: List of sequence features (strings) that are valid keys
      in the tf.SequenceExample.
    dense_sequence_feature: Name of the float sequence feature.

  Returns:
    Two dictionaries with the parsing config for the context features and
    sequence features.
  """
  sequence_features_config = dict()
  for feature in sequence_features:
    dtype = tf.string
    if feature == dense_sequence_feature:
      dtype = tf.float32
    sequence_features_config[feature] = tf.io.VarLenFeature(dtype)

  sequence_features_config['eventId'] = tf.io.FixedLenSequenceFeature(
      [], tf.int64, allow_missing=False)

  context_features_config = dict()
  context_features_config['timestamp'] = tf.io.FixedLenFeature(
      [], tf.int64, default_value=-1)
  context_features_config['sequenceLength'] = tf.io.FixedLenFeature(
      [], tf.int64, default_value=-1)

  if mode != tf_estimator.ModeKeys.PREDICT:
    context_features_config[label_name] = tf.io.VarLenFeature(tf.string)

  def _parse_fn(serialized_examples):
    """Parses tf.(Sparse)Tensors from the serialized tf.SequenceExamples.

    Requires TF versions >= 1.12 but is faster than _parse_fn_old.
    Args:
      serialized_examples: A batch of serialized tf.SequenceExamples.

    Returns:
      A dictionary from name to (Sparse)Tensors of the context and sequence
      features.
    """
    context, sequence, _ = tf.io.parse_sequence_example(
        serialized_examples,
        context_features=context_features_config,
        sequence_features=sequence_features_config,
        name='parse_sequence_example')
    feature_map = dict()
    for k, v in context.items():
      feature_map[CONTEXT_KEY_PREFIX + k] = v
    for k, v in sequence.items():
      feature_map[SEQUENCE_KEY_PREFIX + k] = v
    return feature_map

  return _parse_fn

def _make_feature_engineering_fn(required_sp_tensor_name, label_name):
  """Creates an input function to an estimator.

  Args:
    required_sp_tensor_name: Name of the SparseTensor that is required. Other
      sequence features will be reduced to times at which this SparseTensor is
      also present.
    label_name: Name of label.

  Returns:
    Two dictionaries with the parsing config for the context features and
    sequence features.
  """

  def _process(examples):
    """Supplies input to our model.

    This function supplies input to our model after parsing.
    Args:
      examples: The dictionary from key to (Sparse)Tensors with context and
        sequence features.

    Returns:
      A tuple consisting of 1) a dictionary of tensors whose keys are
      the feature names, and 2) a tensor of target labels if the mode
      is not INFER (and None, otherwise).
    """
    # Combine into a single dictionary.
    feature_map = {}
    # Flatten sparse tensor to compute event age. This dense tensor also
    # contains padded values. These will not be used when gathering elements
    # from the dense tensor since each sparse feature won't have a value
    # defined for the padding.
    padded_event_age = (
        # Broadcast current time along sequence dimension.
        tf.expand_dims(examples.pop(CONTEXT_KEY_PREFIX + 'timestamp'), 1)
        # Subtract time of events.
        - examples.pop(SEQUENCE_KEY_PREFIX + 'eventId'))
    examples[SEQUENCE_KEY_PREFIX + 'deltaTime'] = padded_event_age

    if CONTEXT_KEY_PREFIX + label_name in examples:
      label = examples.pop(CONTEXT_KEY_PREFIX + label_name)
      label = tf.sparse.to_dense(tf.SparseTensor(
          indices=label.indices, dense_shape=[label.dense_shape[0], 1],
          values=tf.ones_like(label.values, dtype=tf.float32)))
      feature_map[CONTEXT_KEY_PREFIX + label_name] = label

    for k, v in examples.items():
      if k.startswith(CONTEXT_KEY_PREFIX):
        feature_map[k] = v
      else:
        feature_map[k] = _intersect_indices(
            v, examples[SEQUENCE_KEY_PREFIX + required_sp_tensor_name])
    sequence_length = tf.reduce_sum(
        _intersect_indices(
            tf.ones_like(examples[SEQUENCE_KEY_PREFIX + 'deltaTime']),
            examples[SEQUENCE_KEY_PREFIX + required_sp_tensor_name]),
        axis=1)
    feature_map[CONTEXT_KEY_PREFIX + 'sequenceLength'] = sequence_length
    return feature_map

  return _process

def get_input_fn(mode,
                 input_files,
                 label_name,
                 sequence_features,
                 dense_sequence_feature,
                 required_sequence_feature,
                 batch_size,
                 shuffle=True):
  """Creates an input function to an estimator.

  Args:
    mode: The execution mode, as defined in tf.estimator.ModeKeys.
    input_files: List of input files in TFRecord format containing
      tf.SequenceExamples.
    label_name: Name of the label present as context feature in the
      SequenceExamples.
    sequence_features: List of sequence features (strings) that are valid keys
      in the tf.SequenceExample.
    dense_sequence_feature: Name of float sequence feature.
    required_sequence_feature: Name of SparseTensor sequence feature that
      determines which events will be kept.
    batch_size: The size of the batch when reading in data.
    shuffle: Whether to shuffle the examples.

  Returns:
    A function that returns a dictionary of features and the target labels.
  """

  def input_fn():
    """Supplies input to our model.

    This function supplies input to our model, where this input is a
    function of the mode. For example, we supply different data if
    we're performing training versus evaluation.
    Returns:
      A tuple consisting of 1) a dictionary of tensors whose keys are
      the feature names, and 2) a tensor of target labels if the mode
      is not INFER (and None, otherwise).
    """
    is_training = mode == tf_estimator.ModeKeys.TRAIN
    num_epochs = None if is_training else 1

    with tf.name_scope('read_batch'):
      file_names = input_files
      files = tf.data.Dataset.list_files(file_names)
      if shuffle:
        files = files.shuffle(buffer_size=len(file_names))
      dataset = (
          files.apply(
              contrib_data.parallel_interleave(
                  tf.data.TFRecordDataset, cycle_length=10)).repeat(num_epochs))
      if shuffle:
        dataset = dataset.shuffle(buffer_size=100)
      parse_fn = _make_parsing_fn(mode, label_name, sequence_features,
                                  dense_sequence_feature)
      feature_engineering_fn = _make_feature_engineering_fn(
          required_sequence_feature, label_name)
      feature_map = (
          dataset.batch(batch_size)
          # Parallelize the input processing and put it behind a
          # queue to increase performance by removing it from the
          # critical path of per-step-computation.
          .map(parse_fn, num_parallel_calls=8)
          .map(feature_engineering_fn, num_parallel_calls=8)
          .prefetch(buffer_size=1).make_one_shot_iterator().get_next())
      label = None
      if mode != tf_estimator.ModeKeys.PREDICT:
        label = feature_map.pop(CONTEXT_KEY_PREFIX + label_name)
      return feature_map, {label_name: label}

  return input_fn


text:
<?php

namespace ZfcRbac\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcRbac\Service\AuthorizationService;

/**
 * Factory to create the authorization service
 *
 * @author  Michaël Gallego <mic.gallego@gmail.com>
 * @license MIT
 */
class AuthorizationServiceFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     * @return AuthorizationService
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var \Rbac\Rbac $rbac */
        $rbac = $serviceLocator->get('Rbac\Rbac');

        /* @var \ZfcRbac\Service\RoleService $roleService */
        $roleService = $serviceLocator->get('ZfcRbac\Service\RoleService');

        /* @var \ZfcRbac\Assertion\AssertionPluginManager $assertionPluginManager */
        $assertionPluginManager = $serviceLocator->get('ZfcRbac\Assertion\AssertionPluginManager');

        /* @var \ZfcRbac\Options\ModuleOptions $moduleOptions */
        $moduleOptions = $serviceLocator->get('ZfcRbac\Options\ModuleOptions');

        $authorizationService = new AuthorizationService($rbac, $roleService, $assertionPluginManager);
        $authorizationService->setAssertions($moduleOptions->getAssertionMap());

        return $authorizationService;
    }
}


text:
- *`Added`* Add a new feature, localization
- *`Added`* Add a translation file for Japanese
- *`Changed`* Change a page header from transactions history to charges history
- *`Removed`* Remove a link, view detail, from each row of transactions and transfers history table
- *`Removed`* Remove sub-tabs, charges and transfers
- *`Removed`* Remove an unused setting, description

## [1.2.2] 2016-08-26
- *`Improved`* Specify the display size of card brand image and allow customer to define their own style
- *`Removed`* Remove an unused unit test of the library, omise-php

## [1.2.1] 2016-08-05
- *`Added`* Configuration for card brand logo display
- *`Added`* List of transfers
- *`Fixed`* Changing page by specify the page number which is not functional

## [1.2.0] 2016-06-01
- *`Added`* manual capture feature
- *`Added`* supported JPY currency
- *`Added`* shortcut menu to Omise's setting page
- *`Added`* Included Omise-PHP 2.4.1 library to the project.
- *`Improved`* Redesigned Omise Dashboard
- *`Improved`* Re-ordered fields in Omise Setting page.
- *`Improved`* Better handle error cases (error messages)
- *`Improved`* Better handle WC order note to trace Omise's actions back.
- *`Improved`* Revised PHP code to following the WordPress Coding Standards.
- *`Improved`* Fixed/Improved various things.

## [1.1.1] 2015-11-16
- *`Added`* Added Omise-Version into the cURL request header.

## [1.1.0] 2015-09-24
- *`Added`* Adds support for 3-D Secure.

## [1.0.2] 2015-03-23
- *`Fixed`* Fix create token issue.

## [1.0.1] 2015-03-10
- *`Added`* Support fund transfers.

## [1.0.0] 2015-01-20
- *`Added`* First version supports.
  - Charge a card
  - Save a card
  - Delete a card


text:
var hexToRgb = require('./index');
var test = require('tape');

test('converts', function (t) {

  t.deepEqual(hexToRgb('000000'), [0,0,0], 'black converted');
  t.deepEqual(hexToRgb('000'), [0,0,0], 'black shorthand converted');
  t.deepEqual(hexToRgb('#ffffff'), [255,255,255], 'white converted with hash');
  t.deepEqual(hexToRgb('#fff'), [255,255,255], 'white shorthand converted with hash');
  t.end();
});


text:
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^register/$', views.register, name='register'),
    url(r'^login/$', views.user_login, name='login'),
    url(r'^logout/$', views.user_logout, name='logout'),
    url(r'^profile/(?P<sh_user_id>[0-9]+)/$', views.profile, name='profile'),
    url(r'^leagues/$', views.leagues, name='leagues'),
    url(r'^leagues/create/$', views.create_league, name='create_league'),
    url(r'^league/(?P<league_id>[0-9]+)/$', views.league_detail, name='league_detail'),
    url(r'^league/(?P<league_id>[0-9]+)/create_suggestion/$', views.create_suggestion, name='create_suggestion'),
    url(r'^league/(?P<league_id>[0-9]+)/manage_league_membership/$', views.manage_league_membership, name='manage_league_membership'),
    url(r'^league/(?P<league_id>[0-9]+)/manage_league_suggestions/$', views.manage_league_suggestions, name='manage_league_suggestions'),
    url(r'^suggestion/(?P<suggestion_id>[0-9]+)/$', views.suggestion_detail, name='suggestion_detail'),
    url(r'^suggestion/(?P<suggestion_id>[0-9]+)/create_huddle/$', views.create_huddle, name='create_huddle'),
    url(r'^huddle/(?P<huddle_id>[0-9]+)/$', views.huddle_detail, name='huddle_detail'),
]


text:
<?php

include_once 'phing/types/AbstractFileSet.php';

/**
 * Subclass as hint for supporting tasks that the included directories
 * instead of files should be used.
 *
 * @package phing.types
 */
class DirSet extends AbstractFileSet
{

    /**
     * @param null $dirset
     */
    public function __construct($dirset = null)
    {
        parent::__construct($dirset);
    }

    /**
     * Return a DirSet that has the same basedir and same patternsets
     * as this one.
     */
    public function __clone()
    {
        if ($this->isReference()) {
            return new DirSet($this->getRef($this->getProject()));
        } else {
            return new DirSet($this);
        }
    }

}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Accessibility</title>
  <link rel="stylesheet" href="accessibility.css">

Accessibility

Global accessibility mode:


text:
package com.hp.autonomy.frontend.testing.matchers;

import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.mockito.ArgumentMatcher;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.hamcrest.core.AllOf.allOf;

/**
 * Mockito matcher that matches a given item if it is a set containing the given items.
 * <p/>
 * This differs from {@link org.hamcrest.core.IsCollectionContaining} in that it explicitly returns a {@link Set}, which
 * cam help with compilation errors.
 * @param <T> The parameterized type of the set
 */
public class SetContainingItems<T> extends ArgumentMatcher<Set<? super T>> {

    private final Set<? super T> set = new HashSet<>();
    private Matcher<? super T> matcher;

    /**
     * Constructs a new SetContainingItems that matches a set containing the given items
     * @param items The items the set must contain
     */
    @SafeVarargs
    public SetContainingItems(final T... items) {
        set.addAll(Arrays.asList(items));
    }

    /**
     * Constructs a new SetContainingItems that matches a set where all the items match a given matcher
     * @param matcher The matcher that must match all items in the set
     */
    public SetContainingItems(final Matcher<? super T> matcher) {
        this.matcher = matcher;
    }

    /**
     * Convenience method for constructing a SetContainingItems
     * @param items The items the set must contain
     * @param <T> The type of the items
     * @return A SetContainingItems that matches a set containing the items
     */
    @SafeVarargs
    @Factory
    public static <T> SetContainingItems<T> isSetWithItems(final T... items) {
        return new SetContainingItems<>(items);
    }

    /**
     * Convenience method for constructing a SetContainingItems where the items in the set must match the given matchers
     * @param matchers The matchers the items in the set must match
     * @param <T> The type of the items in the set
     * @return A SetContainingItems which will match a set where all the items must match all the given matchers
     */
    @SafeVarargs
    @Factory
    public static <T> Matcher<Set<T>> isSetWithItems(final Matcher<? super T>... matchers) {
        final List<Matcher<? super Set<T>>> all = new ArrayList<>(matchers.length);

        for (final Matcher<? super T> elementMatcher : matchers) {
            // Doesn't forward to hasItem() method so compiler can sort out generics.
            all.add(new SetContainingItems<>(elementMatcher));
        }

        return allOf(all);
    }

    @Override
    public boolean matches(final Object item) {
        if (!(item instanceof Set)) {
            return false;
        }

        final Set<?> itemAsSet = (Set<?>) item;

        if (matcher == null) {
            return set.containsAll(itemAsSet);
        } else {
            for (final Object setItem : itemAsSet) {
                if (matcher.matches(setItem)) {
                    return true;
                }
            }

            return false;
        }
    }
}


text:
__all__ = ['SortedDict']

from itertools import imap as _imap

class SortedDict(dict):
    def __init__(self, value=None, kvio=False):
        """
        SortedDict will implement Key Insertion Order (KIO: updates of values
        do not affect the position of the key), Key Value Insertion Order (KVIO,
        an existing key's position is removed and put at the back)
        """
        self._kvio = kvio
        self._fields = []
        self.update(value or {})

    def __setitem__(self, key, value, append=False, dict_setitem=dict.__setitem__):
        if not key in self:
            self._fields.append(key)
        elif self._kvio or append:
            self._fields.remove(key)
            self._fields.append(key)
        return dict_setitem(self, key, value)

    def __delitem__(self, key, dict_delitem=dict.__delitem__):
        if key.startswith('_'):
            del self.__dict__[key]
        else:
            dict_delitem(self, key)
            self._fields.remove(key)

    def __iter__(self):
        'od.__iter__() <==> iter(od)'
        for k in self._fields:
            yield k

    def __reversed__(self):
        'od.__reversed__() <==> reversed(od)'
        for k in reversed(self._fields):
            yield k

    def __getattr__(self, key):
        try:
            return self.__getitem__(key)
        except KeyError as k:
            return None

    def __setattr__(self, key, value):
        if key.startswith('_'):
            self.__dict__[key] = value
        else:
            self.__setitem__(key, value)

    def __delattr__(self, key):
        try:
            self.__delitem__(key)
        except KeyError as k:
            raise AttributeError(k)

    def keys(self):
        return self._fields

    def values(self):
        return [self[k] for k in self._fields]

    def iterkeys(self):
        return iter(self)

    def itervalues(self):
        for k in self:
            yield self[k]

    def update(self, value):
        for k, v in value.items():
            self.__setitem__(k, v)

    def items(self):
        return [(k, self[k]) for k in self._fields]

    def iteritems(self):
        for k in self:
            yield (k, self[k])

    def pop(self, key, default=None):
        v = dict.pop(self, key, default)
        if key in self._fields:
            self._fields.remove(key)
        return v

    def __repr__(self):
        return '<%s {%s}>' % (self.__class__.__name__, ', '.join(['%r:%r' % (k, v) for k, v in sorted(self.items())]))

    def dict(self):
        return self

    def copy(self):
        return self.__class__(self)

    # def sort(self, cmp=None, key=None, reverse=False):
    #     self._fields = [x for x, y in sorted(self.items(), cmp, key, reverse)]
    #
    def setdefault(self, key, value=None):
        if key in self:
            return self[key]
        else:
            self[key] = value
            return value

    def clear(self):
        dict.clear(self)
        self._fields = []

    def __eq__(self, other):
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
        while comparison to a regular mapping is order-insensitive.

        '''
        if isinstance(other, SortedDict):
            return dict.__eq__(self, other) and all(_imap(_eq, self, other))
        return dict.__eq__(self, other)

    def __ne__(self, other):
        'od.__ne__(y) <==> od!=y'
        return not self == other


text:
namespace Gu.State
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Reflection;

    internal sealed class ChangeTrackerNode : IDisposable, IInitialize<ChangeTrackerNode>, ITrackerNode<ChangeTrackerNode>
    {
        private readonly IRefCounted<RootChanges> refcountedRootChanges;
        private readonly IBorrowed<ChildNodes<ChangeTrackerNode>> children;

        private ChangeTrackerNode(object source, PropertiesSettings settings, bool isRoot)
        {
            this.refcountedRootChanges = RootChanges.GetOrCreate(source, settings, isRoot);
            var sourceChanges = this.refcountedRootChanges.Value;
            this.children = ChildNodes<ChangeTrackerNode>.Borrow();
            sourceChanges.PropertyChange += this.OnSourcePropertyChange;
            if (Is.NotifyingCollection(source))
            {
                this.ItemType = this.SourceList.GetType()
                                    .GetItemType();
                sourceChanges.Add += this.OnSourceAdd;
                sourceChanges.Remove += this.OnSourceRemove;
                sourceChanges.Replace += this.OnSourceReplace;
                sourceChanges.Move += this.OnSourceMove;
                sourceChanges.Reset += this.OnSourceReset;
            }
        }

        public event EventHandler<TrackerChangedEventArgs<ChangeTrackerNode>> Changed;

        internal object Source => this.refcountedRootChanges.Value.Source;

        internal PropertiesSettings Settings => this.refcountedRootChanges.Value.Settings;

        internal IList SourceList => (IList)this.Source;

        private IReadOnlyCollection<PropertyInfo> TrackProperties => this.refcountedRootChanges.Value.TrackProperties;

        private Type ItemType { get; }

        private ChildNodes<ChangeTrackerNode> Children => this.children.Value;

        public void Dispose()
        {
            var rootChanges = this.refcountedRootChanges.Value;
            rootChanges.PropertyChange -= this.OnSourcePropertyChange;
            rootChanges.Add -= this.OnSourceAdd;
            rootChanges.Remove -= this.OnSourceRemove;
            rootChanges.Replace -= this.OnSourceReplace;
            rootChanges.Move -= this.OnSourceMove;
            rootChanges.Reset -= this.OnSourceReset;
            this.refcountedRootChanges.Dispose();
            this.children.Dispose();
        }

        public ChangeTrackerNode Initialize()
        {
            var settings = this.Settings;
            switch (settings.ReferenceHandling)
            {
                case ReferenceHandling.Throw:
                    break;
                case ReferenceHandling.References:
                    break;
                case ReferenceHandling.Structural:
                    foreach (var property in this.TrackProperties)
                    {
                        this.UpdatePropertyNode(property);
                    }

                    if (this.Source is IList list)
                    {
                        var itemType = list.GetType().GetItemType();
                        if (!settings.IsImmutable(itemType) && !settings.IsIgnoringDeclaringType(itemType))
                        {
                            for (var i = 0; i < list.Count; i++)
                            {
                                this.UpdateIndexNode(i);
                            }
                        }
                    }

                    break;
                default:
                    throw Throw.ShouldNeverGetHereException($"Unknown ReferenceHandling: {settings.ReferenceHandling}");
            }

            return this;
        }

        internal static bool TryGetOrCreate(object source, PropertiesSettings settings, bool isRoot, out IRefCounted<ChangeTrackerNode> result)
        {
            if (source is INotifyPropertyChanged inpc)
            {
                result = GetOrCreate(inpc, settings, isRoot);
                return true;
            }

            if (source is INotifyCollectionChanged incc)
            {
                result = GetOrCreate(incc, settings, isRoot);
                return true;
            }

            result = null;
            return false;
        }

        internal static IRefCounted<ChangeTrackerNode> GetOrCreate(INotifyPropertyChanged source, PropertiesSettings settings, bool isRoot)
        {
            Debug.Assert(source != null, "Cannot track null");
            return TrackerCache.GetOrAdd((object)source, settings, s => new ChangeTrackerNode(s, settings, isRoot));
        }

        internal static IRefCounted<ChangeTrackerNode> GetOrCreate(INotifyCollectionChanged source, PropertiesSettings settings, bool isRoot)
        {
            Debug.Assert(source != null, "Cannot track null");
            return TrackerCache.GetOrAdd((object)source, settings, s => new ChangeTrackerNode(s, settings, isRoot));
        }

        private void OnChildNodeChanged(object sender, TrackerChangedEventArgs<ChangeTrackerNode> e)
        {
            if (e.Previous?.Contains(this) == true)
            {
                return;
            }

            this.Changed?.Invoke(this, e);
        }

        private void OnSourcePropertyChange(object sender, PropertyChangeEventArgs e)
        {
            this.UpdatePropertyNode(e.PropertyInfo);
            this.Changed?.Invoke(this, RootChangeEventArgs.Create(this, e));
        }

        private void OnSourceAdd(object sender, AddEventArgs e)
        {
            if (this.TryCreateChildNode(e.Index, out var childNode))
            {
                this.Children.Insert(e.Index, childNode);
            }

            this.Changed?.Invoke(this, RootChangeEventArgs.Create(this, e));
        }

        private void OnSourceRemove(object sender, RemoveEventArgs e)
        {
            this.Children.Remove(e.Index);
            this.Changed?.Invoke(this, RootChangeEventArgs.Create(this, e));
        }

        private void OnSourceReplace(object sender, ReplaceEventArgs e)
        {
            this.UpdateIndexNode(e.Index);
            this.Changed?.Invoke(this, RootChangeEventArgs.Create(this, e));
        }

        private void OnSourceMove(object sender, MoveEventArgs e)
        {
            this.Children.Move(e.FromIndex, e.ToIndex);
            this.Changed?.Invoke(this, RootChangeEventArgs.Create(this, e));
        }

        private void OnSourceReset(object sender, ResetEventArgs e)
        {
            if (!Is.Trackable(this.ItemType))
            {
                this.Changed?.Invoke(this, RootChangeEventArgs.Create(this, e));
                return;
            }

            using var borrow = ListPool<IUnsubscriber<IChildNode<ChangeTrackerNode>>>.Borrow();
            for (var i = 0; i < this.SourceList.Count; i++)
            {
                if (this.TryCreateChildNode(i, out var childNode))
                {
                    borrow.Value.Add(childNode);
                }
            }

            this.Children.Reset(borrow.Value);
            this.Changed?.Invoke(this, RootChangeEventArgs.Create(this, e));
        }

        private void UpdatePropertyNode(PropertyInfo property)
        {
            if (this.Settings.IsIgnoringProperty(property) ||
                !Is.Trackable(property.PropertyType))
            {
                return;
            }

            var getter = GetterAndSetter.GetOrCreate(property);
            var value = getter.GetValue(this.Source);
            if (TryGetOrCreate(value, this.Settings, isRoot: false, result: out var node))
            {
                using (node)
                {
                    var propertyNode = ChildNodes<ChangeTrackerNode>.CreateChildNode(this, node.Value, property);
                    propertyNode.Changed += this.OnChildNodeChanged;
                    var childNode = propertyNode.UnsubscribeAndDispose(n => n.Changed -= this.OnChildNodeChanged);
                    this.Children.SetValue(property, childNode);
                }
            }
            else
            {
                this.Children.Remove(property);
            }
        }

        private void UpdateIndexNode(int index)
        {
            if (this.TryCreateChildNode(index, out var childNode))
            {
                this.Children.Replace(index, childNode);
            }
            else
            {
                this.Children.Remove(index);
            }
        }

        private bool TryCreateChildNode(int index, out IUnsubscriber<IChildNode<ChangeTrackerNode>> result)
        {
            var value = this.SourceList.ElementAtOrMissing(index);
            if (value == PaddedPairs.MissingItem)
            {
                result = null;
                return false;
            }

            if (TryGetOrCreate(value, this.Settings, isRoot: false, result: out var node))
            {
                using (node)
                {
                    var indexNode = ChildNodes<ChangeTrackerNode>.CreateChildNode(this, node.Value, index);
                    indexNode.Changed += this.OnChildNodeChanged;
                    result = indexNode.UnsubscribeAndDispose(n => n.Changed -= this.OnChildNodeChanged);
                    return true;
                }
            }

            result = null;
            return false;
        }
    }
}


text:
#if !defined( _OLEBIND_H_ )
#define _OLEBIND_H_

#if !defined( INITGUID )
#include <olectl.h>
#endif

DEFINE_GUID(IID_IBoundObject,
	0x9BFBBC00,0xEFF1,0x101A,0x84,0xED,0x00,0xAA,0x00,0x34,0x1D,0x07);
DEFINE_GUID(IID_IBoundObjectSite,
	0x9BFBBC01,0xEFF1,0x101A,0x84,0xED,0x00,0xAA,0x00,0x34,0x1D,0x07);

typedef interface IBoundObject FAR* LPBOUNDOBJECT;
typedef interface IBoundObjectSite FAR* LPBOUNDOBJECTSITE;

typedef interface ICursor FAR* LPCURSOR;
typedef interface ICursor FAR* FAR* LPLPCURSOR;
typedef interface ICursorMove FAR* LPCURSORMOVE;
typedef interface ICursorScroll FAR* LPCURSORSCROLL;
typedef interface ICursorFind FAR* LPCURSORFIND;
typedef interface ICursorUpdateARow FAR* LPCURSORUPDATEAROW;

//////////////////////////////////////////////////////////////////////////////
//
//  IBoundObject interface
//
//////////////////////////////////////////////////////////////////////////////

#undef  INTERFACE
#define INTERFACE IBoundObject

DECLARE_INTERFACE_(IBoundObject, IUnknown)
{
	//
	//  IUnknown methods
	//
	STDMETHOD(QueryInterface)(THIS_ REFIID riid, LPVOID FAR* ppvObj) PURE;
	STDMETHOD_(ULONG,AddRef)(THIS) PURE;
	STDMETHOD_(ULONG,Release)(THIS) PURE;

	//
	//  IBoundObject methods
	//
	STDMETHOD(OnSourceChanged)(THIS_ DISPID dispid, BOOL fBound, BOOL FAR* lpfOwnXferOut) PURE;
	STDMETHOD(IsDirty)(THIS_ DISPID dispid) PURE;
};
//////////////////////////////////////////////////////////////////////////////
//
//  IBoundObjectSite interface
//
//////////////////////////////////////////////////////////////////////////////

#undef  INTERFACE
#define INTERFACE IBoundObjectSite

DECLARE_INTERFACE_(IBoundObjectSite, IUnknown)
{
	//
	//  IUnknown methods
	//
	STDMETHOD(QueryInterface)(THIS_ REFIID riid, LPVOID FAR* ppvObj) PURE;
	STDMETHOD_(ULONG,AddRef)(THIS) PURE;
	STDMETHOD_(ULONG,Release)(THIS) PURE;

	//
	//  IBoundObjectSite methods
	//
	STDMETHOD(GetCursor)(THIS_ DISPID dispid, LPLPCURSOR ppCursor, LPVOID FAR* ppcidOut) PURE;
};

#endif // !defined( _OLEBIND_H_ )


text:
package ui

import (
	"strings"

	"github.com/dustin/go-humanize"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"go.chromium.org/luci/common/clock"
	"go.chromium.org/luci/common/sync/parallel"
	"go.chromium.org/luci/server/router"
	"go.chromium.org/luci/server/templates"

	api "go.chromium.org/luci/cipd/api/cipd/v1"
	"go.chromium.org/luci/cipd/common"
)

func packagePage(c *router.Context, pkg string) error {
	// Validate the package name and grab a parent prefix to list siblings.
	pkg = strings.Trim(pkg, "/")
	if err := common.ValidatePackageName(pkg); err != nil {
		return status.Errorf(codes.InvalidArgument, "bad package name: %s", err)
	}
	pfx := ""
	if i := strings.LastIndex(pkg, "/"); i != -1 {
		pfx = pkg[:i]
	}

	svc := state(c.Context).services

	// Cursor used for paginating instance listing.
	cursor := c.Request.URL.Query().Get("c")
	prevPageURL := ""
	nextPageURL := ""

	var instances *api.ListInstancesResponse
	var siblings *api.ListPrefixResponse
	var refs *api.ListRefsResponse
	var meta *prefixMetadataBlock

	err := parallel.FanOutIn(func(tasks chan<- func() error) {
		tasks <- func() error {
			var err error
			instances, err = svc.PublicRepo.ListInstances(c.Context, &api.ListInstancesRequest{
				Package:   pkg,
				PageSize:  12,
				PageToken: cursor,
			})
			if err != nil {
				return err
			}
			if instances.NextPageToken != "" {
				instancesListing.storePrevCursor(c.Context, pkg, instances.NextPageToken, cursor)
				nextPageURL = packagePageURL(pkg, instances.NextPageToken)
			}
			if cursor != "" {
				prevPageURL = packagePageURL(pkg, instancesListing.fetchPrevCursor(c.Context, pkg, cursor))
			}
			return nil
		}
		tasks <- func() error {
			var err error
			siblings, err = svc.PublicRepo.ListPrefix(c.Context, &api.ListPrefixRequest{
				Prefix: pfx,
			})
			return err
		}
		tasks <- func() error {
			var err error
			meta, err = fetchPrefixMetadata(c.Context, pkg)
			return err
		}
		tasks <- func() error {
			var err error
			refs, err = svc.PublicRepo.ListRefs(c.Context, &api.ListRefsRequest{
				Package: pkg,
			})
			return err
		}
	})
	if err != nil {
		return err
	}

	// Mapping "instance ID" => list of refs pointing to it.
	refMap := make(map[string][]*api.Ref, len(refs.Refs))
	for _, ref := range refs.Refs {
		iid := common.ObjectRefToInstanceID(ref.Instance)
		refMap[iid] = append(refMap[iid], ref)
	}

	// Build instance listing, annotating instances with refs that point to them.
	type instanceItem struct {
		ID          string
		TruncatedID string
		Href        string
		Refs        []refItem
		Age         string
	}

	now := clock.Now(c.Context).UTC()
	instListing := make([]instanceItem, len(instances.Instances))
	for i, inst := range instances.Instances {
		iid := common.ObjectRefToInstanceID(inst.Instance)
		instListing[i] = instanceItem{
			ID:          iid,
			TruncatedID: iid[:30],
			Href:        instancePageURL(pkg, iid),
			Age:         humanize.RelTime(inst.RegisteredTs.AsTime(), now, "", ""),
			Refs:        refsListing(refMap[iid], pkg, now),
		}
	}

	templates.MustRender(c.Context, c.Writer, "pages/index.html", map[string]interface{}{
		"Package":     pkg,
		"Breadcrumbs": breadcrumbs(pfx, ""),
		"Prefixes":    prefixesListing(pfx, siblings.Prefixes),
		"Packages":    packagesListing(pfx, siblings.Packages, pkg),
		"Metadata":    meta,
		"Instances":   instListing,
		"Refs":        refsListing(refs.Refs, pkg, now),
		"NextPageURL": nextPageURL,
		"PrevPageURL": prevPageURL,
	})
	return nil
}