<commit_before>import streamiterator from "./streamiterator"
import { PassThrough, Readable } from "stream"

test("for await loop | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	stream.write(1)
	stream.write(new Promise(resolve => setTimeout(() => resolve(2), 50)))
	stream.write(3)
	setTimeout(() => {
		stream.write(4)
		stream.write(5)
		stream.write(6)
		stream.end()
	}, 100)
	let count = 0
	for await (const data of streamiterator(stream)) {
		++count
		expect(data).toBe(count)
		expect(data).toBeLessThan(7)
	}
	expect(count).toBe(6)
})

test("for await loop | stream.push", async () => {
	const stream = new Readable({
		objectMode: true,
		read() {
			this._count |= 0
			this.push(++this._count)
			const data = ++this._count
			this.push(new Promise(resolve => setTimeout(() => resolve(data), 50)))
			this.push(++this._count)
			if (this._count > 5) {
				this.push(null)
			}
		},
	})
	let count = 0
	for await (const data of streamiterator(stream)) {
		++count
		expect(data).toBe(count)
		expect(data).toBeLessThan(7)
	}
	expect(count).toBe(6)
})

test("throwing in a loop emitted errors | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	stream.write(1)
	stream.write(new Promise(resolve => setTimeout(() => resolve(2), 50)))
	stream.write(3)
	setTimeout(() => {
		stream.write(4)
		stream.write(5)
		stream.write(6)
		stream.emit("error", 13)
		stream.write(7)
	}, 100)
	let error
	let count = 0
	try {
		for await (const data of streamiterator(stream)) {
			++count
			expect(data).toBe(count)
			expect(data).toBeLessThan(7)
		}
	} catch (e) {
		error = e
	}
	expect(error).toBe(13)
	expect(count).toBe(6)
})

test("throwing in a loop emitted errors | stream.push", async () => {
	const stream = new Readable({
		objectMode: true,
		read() {
			this._count |= 0
			this.push(++this._count)
			const data = ++this._count
			this.push(new Promise(resolve => setTimeout(() => resolve(data), 50)))
			this.push(++this._count)
			if (this._count > 5) {
				stream.emit("error", 13)
			}
		},
	})
	let error
	let count = 0
	try {
		for await (const data of streamiterator(stream)) {
			++count
			expect(data).toBe(count)
			expect(data).toBeLessThan(7)
		}
	} catch (e) {
		error = e
	}
	expect(error).toBe(13)
	expect(count).toBe(6)
})

test("reading ahead | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		stream.end()
	}, 100)
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.next()
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 3, done: false })
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("reading ahead | stream.push", async () => {
	const stream = new Readable({
		objectMode: true,
		highWaterMark: 1,
		read() {
			this._count |= 0
			this.push(++this._count)
			if (this._count >= 3) {
				this.push(null)
			}
		},
	})
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.next()
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 3, done: false })
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("returning ahead | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		stream.write(4)
		// unfinished stream
	}, 100)
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.return(42)
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 42, done: true })
	expect(closed).toBe(true)
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("returning ahead | stream.push", async () => {
	let closed = false
	const stream = new Readable({
		objectMode: true,
		highWaterMark: 1,
		read() {
			this._count |= 0
			this.push(++this._count)
		},
		destroy(error, callback) {
			closed = true
			callback()
		},
	})
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.return(42)
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 42, done: true })
	expect(closed).toBe(true)
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("throwing ahead | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		stream.write(4)
		// unfinished stream
	}, 100)
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	const onerror = new Promise(resolve => stream.on("error", resolve))
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.throw(13)
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3.then(result => ({ result }), error => error)).toBe(13)
	expect(closed).toBe(true)
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
	expect(await onerror).toBe(13)
})

test("closing stream on loop break | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		// unfinished stream
	}, 100)
	let count = 0
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	for await (const data of streamiterator(stream)) {
		++count
		expect(data).toBe(1)
		break
	}
	expect(count).toBe(1)
	expect(closed).toBe(true)
})

test("closing stream on throwing in a loop | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		// unfinished stream
	}, 100)
	let count = 0
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	let error
	try {
		for await (const data of streamiterator(stream)) {
			++count
			expect(data).toBe(1)
			throw 13
		}
	} catch (e) {
		error = e
	}
	expect(count).toBe(1)
	expect(error).toBe(13)
	expect(closed).toBe(true)
})

test("reading buffered data after emitting error | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	process.nextTick(async () => {
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.write(1)
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.write(2)
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.write(3)
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.emit("error", 13)
	})
	let count = 0
	let error
	try {
		for await (const data of streamiterator(stream)) {
			if (count === 0) {
				await new Promise(resolve => setTimeout(resolve, 100))
			}
			++count
			expect(data).toBe(count)
			expect(data).toBeLessThan(4)
		}
	} catch (e) {
		error = e
	}
	expect(count).toBe(3)
	expect(error).toBe(13)
})
<commit_msg>do not emit errors on stream from iterator.throw<commit_after>import streamiterator from "./streamiterator"
import { PassThrough, Readable } from "stream"

test("for await loop | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	stream.write(1)
	stream.write(new Promise(resolve => setTimeout(() => resolve(2), 50)))
	stream.write(3)
	setTimeout(() => {
		stream.write(4)
		stream.write(5)
		stream.write(6)
		stream.end()
	}, 100)
	let count = 0
	for await (const data of streamiterator(stream)) {
		++count
		expect(data).toBe(count)
		expect(data).toBeLessThan(7)
	}
	expect(count).toBe(6)
})

test("for await loop | stream.push", async () => {
	const stream = new Readable({
		objectMode: true,
		read() {
			this._count |= 0
			this.push(++this._count)
			const data = ++this._count
			this.push(new Promise(resolve => setTimeout(() => resolve(data), 50)))
			this.push(++this._count)
			if (this._count > 5) {
				this.push(null)
			}
		},
	})
	let count = 0
	for await (const data of streamiterator(stream)) {
		++count
		expect(data).toBe(count)
		expect(data).toBeLessThan(7)
	}
	expect(count).toBe(6)
})

test("throwing in a loop emitted errors | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	stream.write(1)
	stream.write(new Promise(resolve => setTimeout(() => resolve(2), 50)))
	stream.write(3)
	setTimeout(() => {
		stream.write(4)
		stream.write(5)
		stream.write(6)
		stream.emit("error", 13)
		stream.write(7)
	}, 100)
	let error
	let count = 0
	try {
		for await (const data of streamiterator(stream)) {
			++count
			expect(data).toBe(count)
			expect(data).toBeLessThan(7)
		}
	} catch (e) {
		error = e
	}
	expect(error).toBe(13)
	expect(count).toBe(6)
})

test("throwing in a loop emitted errors | stream.push", async () => {
	const stream = new Readable({
		objectMode: true,
		read() {
			this._count |= 0
			this.push(++this._count)
			const data = ++this._count
			this.push(new Promise(resolve => setTimeout(() => resolve(data), 50)))
			this.push(++this._count)
			if (this._count > 5) {
				stream.emit("error", 13)
			}
		},
	})
	let error
	let count = 0
	try {
		for await (const data of streamiterator(stream)) {
			++count
			expect(data).toBe(count)
			expect(data).toBeLessThan(7)
		}
	} catch (e) {
		error = e
	}
	expect(error).toBe(13)
	expect(count).toBe(6)
})

test("reading ahead | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		stream.end()
	}, 100)
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.next()
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 3, done: false })
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("reading ahead | stream.push", async () => {
	const stream = new Readable({
		objectMode: true,
		highWaterMark: 1,
		read() {
			this._count |= 0
			this.push(++this._count)
			if (this._count >= 3) {
				this.push(null)
			}
		},
	})
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.next()
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 3, done: false })
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("returning ahead | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		stream.write(4)
		// unfinished stream
	}, 100)
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.return(42)
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 42, done: true })
	expect(closed).toBe(true)
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("returning ahead | stream.push", async () => {
	let closed = false
	const stream = new Readable({
		objectMode: true,
		highWaterMark: 1,
		read() {
			this._count |= 0
			this.push(++this._count)
		},
		destroy(error, callback) {
			closed = true
			callback()
		},
	})
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.return(42)
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3).toEqual({ value: 42, done: true })
	expect(closed).toBe(true)
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("throwing ahead | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		stream.write(4)
		// unfinished stream
	}, 100)
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	const iterator = streamiterator(stream)
	const i1 = iterator.next()
	const i2 = iterator.next()
	const i3 = iterator.throw(13)
	const i4 = iterator.next()
	const i5 = iterator.next()
	expect(await i1).toEqual({ value: 1, done: false })
	expect(await i2).toEqual({ value: 2, done: false })
	expect(await i3.then(result => ({ result }), error => error)).toBe(13)
	expect(closed).toBe(true)
	expect(await i4).toEqual({ value: undefined, done: true })
	expect(await i5).toEqual({ value: undefined, done: true })
})

test("closing stream on loop break | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		// unfinished stream
	}, 100)
	let count = 0
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	for await (const data of streamiterator(stream)) {
		++count
		expect(data).toBe(1)
		break
	}
	expect(count).toBe(1)
	expect(closed).toBe(true)
})

test("closing stream on throwing in a loop | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	setTimeout(() => {
		stream.write(1)
		stream.write(2)
		stream.write(3)
		// unfinished stream
	}, 100)
	let count = 0
	let closed = false
	stream.on("close", () => {
		closed = true
	})
	let error
	try {
		for await (const data of streamiterator(stream)) {
			++count
			expect(data).toBe(1)
			throw 13
		}
	} catch (e) {
		error = e
	}
	expect(count).toBe(1)
	expect(error).toBe(13)
	expect(closed).toBe(true)
})

test("reading buffered data after emitting error | stream.write", async () => {
	const stream = new PassThrough({ objectMode: true })
	process.nextTick(async () => {
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.write(1)
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.write(2)
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.write(3)
		await new Promise(resolve => setTimeout(resolve, 20))
		stream.emit("error", 13)
	})
	let count = 0
	let error
	try {
		for await (const data of streamiterator(stream)) {
			if (count === 0) {
				await new Promise(resolve => setTimeout(resolve, 100))
			}
			++count
			expect(data).toBe(count)
			expect(data).toBeLessThan(4)
		}
	} catch (e) {
		error = e
	}
	expect(count).toBe(3)
	expect(error).toBe(13)
})
<|endoftext|>


<commit_before><commit_msg>Delete lm2.js<commit_after><|endoftext|>


<commit_before>import is_nil from 'lodash.isnil';
import is_number from 'lodash.isnumber';
import is_string from 'lodash.isstring';

import {completeAssign} from 'common/utils';
import {SceneController} from 'graphics/scene';
import Rect from 'maths/rect';

export default function Screen(canvas_context) {
	const state = {
		backgroundColor: 'rgba(0, 0, 0, 0)',
		children: [],
		absoluteScale: {x: 1, y: 1},
		scale: {x: 1, y: 1},
		scale_stack: []
	};

	return completeAssign(SceneController(state), {
		///////////////////////////////////////////////////////////////////////
		/// Screen metrics
		get width() {
			return canvas_context.canvas.width*state.scale.x;
		},
		set width(w) {
			canvas_context.canvas.width = w/state.scale.x;
		},
		get height() {
			return canvas_context.canvas.height*state.scale.y;
		},
		set height(h) {
			canvas_context.canvas.height = h/state.scale.y;
		},
		size() {
			return {
				width: this.width,
				height: this.height
			};
		},
		setSize({width, height}) {
			this.width = width;
			this.height = height;
			return this;
		},
		localRect() {
			return Rect({x: 0, y: 0}, this.size());
		},
		rect() {
			return this.localRect();
		},
		///////////////////////////////////////////////////////////////////////
		/// Pen
		get pen() {
			return {
				lineWidth: canvas_context.lineWidth,
				strokeStyle: canvas_context.strokeStyle
			};
		},
		set pen(pen) {
			if (is_number(pen)) {
				canvas_context.lineWidth = pen;
			} else if (is_string(pen)) {
				canvas_context.strokeStyle = pen;
			} else {
				canvas_context.lineWidth = pen.lineWidth;
				canvas_context.strokeStyle = pen.strokeStyle;
			}
		},
		///////////////////////////////////////////////////////////////////////
		/// Brush
		get brush() {
			return {
				fillStyle: canvas_context.fillStyle,
				get isGradient() {
					return false;
				},
				get isSolid() {
					return false;
				}
			};
		},
		set brush(brush) {
			if (is_string(brush)) {
				canvas_context.fillStyle = brush;
			} else {
				canvas_context.fillStyle = brush.fillStyle;
			}
		},
		///////////////////////////////////////////////////////////////////////
		/// Basics drawing routines
		clear() {
			canvas_context.fillRect(0, 0, this.width, this.height);
			return this;
		},
		drawLine({x: x1, y: y1}, {x: x2, y: y2}) {
			this.beginPath();
			this.moveTo({x: x1, y: y1});
			this.lineTo({x: x2, y: y2});
			this.drawPath();
			return this;
		},
		drawRect({topLeft, topRight, bottomLeft, bottomRight}) {
			this.beginPath();
			this.moveTo(topLeft);
			this.lineTo(topRight);
			this.lineTo(bottomRight);
			this.lineTo(bottomLeft);
			this.closePath();
			this.drawPath();
			return this;
		},
		fillRect({topLeft, topRight, bottomLeft, bottomRight}) {
			this.beginPath();
			this.moveTo(topLeft);
			this.lineTo(topRight);
			this.lineTo(bottomRight);
			this.lineTo(bottomLeft);
			this.closePath();
			this.fillPath();
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Path
		beginPath() {
			canvas_context.beginPath();
			return this;
		},
		closePath() {
			canvas_context.closePath();
			return this;
		},
		moveTo({x, y}) {
			canvas_context.moveTo(x, y);
			return this;
		},
		lineTo({x, y}) {
			canvas_context.lineTo(x, y);
			return this;
		},
		arc({x, y}, radius, start_angle, end_angle, anticlockwise) {
			canvas_context.arc(x, y, radius, start_angle, end_angle, anticlockwise);
			return this;
		},
		drawPath(path) {
			if (is_nil(path)) {
				canvas_context.stroke();
			} else {
				canvas_context.stroke(path);
			}
			return this;
		},
		fillPath(path) {
			if (is_nil(path)) {
				canvas_context.fill();
			} else {
				canvas_context.fill(path);
			}
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Clip
		clipRect({topLeft, topRight, bottomLeft, bottomRight}) {
			this.beginPath();
			this.moveTo(topLeft);
			this.lineTo(topRight);
			this.lineTo(bottomRight);
			this.lineTo(bottomLeft);
			this.closePath();
			canvas_context.clip();
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Context save/restore
		save() {
			const {scale, absoluteScale} = state;
			state.scale_stack.push({scale, absoluteScale});
			canvas_context.save();
			return this;
		},
		restore() {
			const {scale, absoluteScale} = state.scale_stack.pop();
			state.scale = scale;
			state.absoluteScale = absoluteScale;
			canvas_context.restore();
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Transformations
		absoluteScale() {
			return state.absoluteScale;
		},
		scale() {
			return state.scale;
		},
		setScale(f) {
			const scale = is_number(f) ? {x: f, y: f} : f;
			state.absoluteScale = {
				x: state.absoluteScale.x*scale.x,
				y: state.absoluteScale.x*scale.y
			};
			state.scale = scale;
			canvas_context.scale(state.scale.x, state.scale.y);
			return this;
		},
		translate({x, y}) {
			canvas_context.translate(x, y);
			return this;
		},
		rotate(angle) {
			canvas_context.rotate(angle);
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Gradient
		createLinearGradient({x: x1, y: y1}, {x: x2, y: y2}, colorStops) {
			const grd = canvas_context.createLinearGradient(x1, y1, x2, y2);
			for (let stop of colorStops) {
				grd.addColorStop(stop.pos, stop.color);
			}
			return grd;
		},
		///////////////////////////////////////////////////////////////////////
		/// Scene
		render() {
			this.brush = state.backgroundColor;
			this.clear();
			for (let child of state.children) {
				child.render(this);
			}
			return this;
		},
		setBackgroundColor(color) {
			state.backgroundColor = color;
			return this;
		},
		scene() {
			return null;
		}
	});
}
<commit_msg>Change default background color value<commit_after>import is_nil from 'lodash.isnil';
import is_number from 'lodash.isnumber';
import is_string from 'lodash.isstring';

import {completeAssign} from 'common/utils';
import {SceneController} from 'graphics/scene';
import Rect from 'maths/rect';

export default function Screen(canvas_context) {
	const state = {
		backgroundColor: 'rgba(0, 0, 0, 1)',
		children: [],
		absoluteScale: {x: 1, y: 1},
		scale: {x: 1, y: 1},
		scale_stack: []
	};

	return completeAssign(SceneController(state), {
		///////////////////////////////////////////////////////////////////////
		/// Screen metrics
		get width() {
			return canvas_context.canvas.width*state.scale.x;
		},
		set width(w) {
			canvas_context.canvas.width = w/state.scale.x;
		},
		get height() {
			return canvas_context.canvas.height*state.scale.y;
		},
		set height(h) {
			canvas_context.canvas.height = h/state.scale.y;
		},
		size() {
			return {
				width: this.width,
				height: this.height
			};
		},
		setSize({width, height}) {
			this.width = width;
			this.height = height;
			return this;
		},
		localRect() {
			return Rect({x: 0, y: 0}, this.size());
		},
		rect() {
			return this.localRect();
		},
		///////////////////////////////////////////////////////////////////////
		/// Pen
		get pen() {
			return {
				lineWidth: canvas_context.lineWidth,
				strokeStyle: canvas_context.strokeStyle
			};
		},
		set pen(pen) {
			if (is_number(pen)) {
				canvas_context.lineWidth = pen;
			} else if (is_string(pen)) {
				canvas_context.strokeStyle = pen;
			} else {
				canvas_context.lineWidth = pen.lineWidth;
				canvas_context.strokeStyle = pen.strokeStyle;
			}
		},
		///////////////////////////////////////////////////////////////////////
		/// Brush
		get brush() {
			return {
				fillStyle: canvas_context.fillStyle,
				get isGradient() {
					return false;
				},
				get isSolid() {
					return false;
				}
			};
		},
		set brush(brush) {
			if (is_string(brush)) {
				canvas_context.fillStyle = brush;
			} else {
				canvas_context.fillStyle = brush.fillStyle;
			}
		},
		///////////////////////////////////////////////////////////////////////
		/// Basics drawing routines
		clear() {
			canvas_context.fillRect(0, 0, this.width, this.height);
			return this;
		},
		drawLine({x: x1, y: y1}, {x: x2, y: y2}) {
			this.beginPath();
			this.moveTo({x: x1, y: y1});
			this.lineTo({x: x2, y: y2});
			this.drawPath();
			return this;
		},
		drawRect({topLeft, topRight, bottomLeft, bottomRight}) {
			this.beginPath();
			this.moveTo(topLeft);
			this.lineTo(topRight);
			this.lineTo(bottomRight);
			this.lineTo(bottomLeft);
			this.closePath();
			this.drawPath();
			return this;
		},
		fillRect({topLeft, topRight, bottomLeft, bottomRight}) {
			this.beginPath();
			this.moveTo(topLeft);
			this.lineTo(topRight);
			this.lineTo(bottomRight);
			this.lineTo(bottomLeft);
			this.closePath();
			this.fillPath();
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Path
		beginPath() {
			canvas_context.beginPath();
			return this;
		},
		closePath() {
			canvas_context.closePath();
			return this;
		},
		moveTo({x, y}) {
			canvas_context.moveTo(x, y);
			return this;
		},
		lineTo({x, y}) {
			canvas_context.lineTo(x, y);
			return this;
		},
		arc({x, y}, radius, start_angle, end_angle, anticlockwise) {
			canvas_context.arc(x, y, radius, start_angle, end_angle, anticlockwise);
			return this;
		},
		drawPath(path) {
			if (is_nil(path)) {
				canvas_context.stroke();
			} else {
				canvas_context.stroke(path);
			}
			return this;
		},
		fillPath(path) {
			if (is_nil(path)) {
				canvas_context.fill();
			} else {
				canvas_context.fill(path);
			}
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Clip
		clipRect({topLeft, topRight, bottomLeft, bottomRight}) {
			this.beginPath();
			this.moveTo(topLeft);
			this.lineTo(topRight);
			this.lineTo(bottomRight);
			this.lineTo(bottomLeft);
			this.closePath();
			canvas_context.clip();
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Context save/restore
		save() {
			const {scale, absoluteScale} = state;
			state.scale_stack.push({scale, absoluteScale});
			canvas_context.save();
			return this;
		},
		restore() {
			const {scale, absoluteScale} = state.scale_stack.pop();
			state.scale = scale;
			state.absoluteScale = absoluteScale;
			canvas_context.restore();
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Transformations
		absoluteScale() {
			return state.absoluteScale;
		},
		scale() {
			return state.scale;
		},
		setScale(f) {
			const scale = is_number(f) ? {x: f, y: f} : f;
			state.absoluteScale = {
				x: state.absoluteScale.x*scale.x,
				y: state.absoluteScale.x*scale.y
			};
			state.scale = scale;
			canvas_context.scale(state.scale.x, state.scale.y);
			return this;
		},
		translate({x, y}) {
			canvas_context.translate(x, y);
			return this;
		},
		rotate(angle) {
			canvas_context.rotate(angle);
			return this;
		},
		///////////////////////////////////////////////////////////////////////
		/// Gradient
		createLinearGradient({x: x1, y: y1}, {x: x2, y: y2}, colorStops) {
			const grd = canvas_context.createLinearGradient(x1, y1, x2, y2);
			for (let stop of colorStops) {
				grd.addColorStop(stop.pos, stop.color);
			}
			return grd;
		},
		///////////////////////////////////////////////////////////////////////
		/// Scene
		render() {
			this.brush = state.backgroundColor;
			this.clear();
			for (let child of state.children) {
				child.render(this);
			}
			return this;
		},
		setBackgroundColor(color) {
			state.backgroundColor = color;
			return this;
		},
		scene() {
			return null;
		}
	});
}
<|endoftext|>


<commit_before>var assert = require('assert')
var crypto = require('crypto')

var bitcoinjs = require('bitcoinjs-lib')
var bip32utils = require('bip32-utils')
var bufferutils = bitcoinjs.bufferutils
var networks = bitcoinjs.networks

var Address = bitcoinjs.Address
var HDNode = bitcoinjs.HDNode
var TransactionBuilder = bitcoinjs.TransactionBuilder
var Script = bitcoinjs.Script

function Wallet(seed, network) {
  seed = seed || crypto.randomBytes(32)
  network = network || networks.bitcoin

  // Stored in a closure to make accidental serialization less likely
  var masterKey = HDNode.fromSeedBuffer(seed, network)

  // HD first-level child derivation method should be hardened
  // See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254
  var accountZero = masterKey.deriveHardened(0)
  var external = accountZero.derive(0)
  var internal = accountZero.derive(1)

  this.account = new bip32utils.Account(external.neutered(), internal.neutered())
  this.network = network
  this.unspents = []

  this.getMasterKey = function() { return masterKey }
  this.getAccountZero = function() { return accountZero }
  this.getExternalAccount = function() { return external }
  this.getInternalAccount = function() { return internal }
}

function estimatePaddedFee(tx, network) {
  var tmpTx = tx.clone()
  tmpTx.addOutput(Script.EMPTY, network.dustSoftThreshold || 0)

  return network.estimateFee(tmpTx)
}

Wallet.prototype.createTransaction = function(outputs, options) {
  options = options || {}

  var changeAddress = options.changeAddress
  var fixedFee = options.fixedFee
  var minConf = options.minConf === undefined ? 1 : options.minConf

  // filter by minConf and sort by descending value
  var unspents = this.unspents.filter(function(unspent) {
    return unspent.confirmations >= minConf
  }).sort(function(o1, o2) {
    return o2.value - o1.value
  })

  var txb = new TransactionBuilder()
  var targetValue = 0

  outputs.forEach(function(output) {
    if (output.value <= this.network.dustThreshold) {
      throw new Error(output.value + ' must be above dust threshold (' + this.network.dustThreshold + ' Satoshis)')
    }

    targetValue += output.value
    txb.addOutput(output.address, output.value)
  }, this)

  var accum = 0
  var addresses = []
  var subTotal = targetValue

  for (var i = 0; i < unspents.length; ++i) {
    var unspent = unspents[i]
    addresses.push(unspent.address)

    txb.addInput(unspent.txId, unspent.index)

    var fee
    if (fixedFee === undefined) {
      fee = estimatePaddedFee(txb.buildIncomplete(), this.network)

    } else {
      fee = fixedFee
    }

    accum += unspent.value
    subTotal = targetValue + fee

    if (accum >= subTotal) {
      var change = accum - subTotal

      if (change > this.network.dustThreshold) {
        txb.addOutput(changeAddress || this.getChangeAddress(), change)
      }

      break
    }
  }

  if (accum < subTotal) {
    throw new Error('Not enough funds (incl. fee): ' + accum + ' < ' + subTotal)
  }

  return this.signWith(txb, addresses).build()
}

Wallet.prototype.generateAddress = function() {
  this.account.nextAddress()

  return this.getAddress()
}

Wallet.prototype.getAddress = function() {
  return this.account.getAddress()
}

Wallet.prototype.getBalance = function(minConf) {
  minConf = minConf || 0

  return this.unspents.filter(function(unspent) {
    return unspent.confirmations >= minConf

  }).reduce(function(accum, unspent) {
    return accum + unspent.value
  }, 0)
}

Wallet.prototype.getChangeAddress = function() {
  return this.account.getChangeAddress()
}

Wallet.prototype.getUnspentOutputs = function(minConf) {
  minConf = minConf || 0

  return this.unspents.filter(function(unspent) {
    return unspent.confirmations >= minConf

  }).map(function(unspent) {
    return {
      address: unspent.address,
      confirmations: unspent.confirmations,
      index: unspent.index,
      txId: unspent.txId,
      value: unspent.value
    }
  })
}

Wallet.prototype.setUnspentOutputs = function(unspents) {
  this.unspents = unspents.map(function(unspent) {
    var txId = unspent.txId
    var index = unspent.index

    assert.equal(typeof txId, 'string', 'Expected txId, got ' + txId)
    assert.equal(txId.length, 64, 'Expected valid txId, got ' + txId)
    assert.doesNotThrow(function() { Address.fromBase58Check(unspent.address) }, 'Expected Base58 Address, got ' + unspent.address)
    assert(isFinite(index), 'Expected number index, got ' + index)
    assert.equal(typeof unspent.value, 'number', 'Expected number value, got ' + unspent.value)
    assert.equal(typeof unspent.confirmations, 'number', 'Expected number confirmations, got ' + unspent.confirmations)

    var txHash = bufferutils.reverse(new Buffer(txId, 'hex'))

    unspent = {
      address: unspent.address,
      confirmations: unspent.confirmations || 0,
      index: index,
      txHash: txHash,
      txId: txId,
      value: unspent.value
    }

    return unspent
  }, this)
}

Wallet.prototype.signWith = function(tx, addresses) {
  var external = this.getExternalAccount()
  var internal = this.getInternalAccount()
  var nodes = this.account.getNodes(addresses, external, internal)
  var keys = nodes.map(function(node) { return node.privKey })

  keys.forEach(function(key, i) {
    tx.sign(i, key)
  })

  return tx
}

module.exports = Wallet
<commit_msg>Wallet: dont expose m/i at all<commit_after>var assert = require('assert')
var crypto = require('crypto')

var bitcoinjs = require('bitcoinjs-lib')
var bip32utils = require('bip32-utils')
var bufferutils = bitcoinjs.bufferutils
var networks = bitcoinjs.networks

var Address = bitcoinjs.Address
var HDNode = bitcoinjs.HDNode
var TransactionBuilder = bitcoinjs.TransactionBuilder
var Script = bitcoinjs.Script

function Wallet(seed, network) {
  seed = seed || crypto.randomBytes(32)
  network = network || networks.bitcoin

  // HD first-level child derivation method should be hardened
  // See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254
  var m = HDNode.fromSeedBuffer(seed, network)
  var i = m.deriveHardened(0)
  var external = i.derive(0)
  var internal = i.derive(1)

  this.account = new bip32utils.Account(external.neutered(), internal.neutered())
  this.network = network
  this.unspents = []

  // Getters in a closure to avoid accidental serialization
  this.getExternalAccount = function() { return external }
  this.getInternalAccount = function() { return internal }
}

function estimatePaddedFee(tx, network) {
  var tmpTx = tx.clone()
  tmpTx.addOutput(Script.EMPTY, network.dustSoftThreshold || 0)

  return network.estimateFee(tmpTx)
}

Wallet.prototype.createTransaction = function(outputs, options) {
  options = options || {}

  var changeAddress = options.changeAddress
  var fixedFee = options.fixedFee
  var minConf = options.minConf === undefined ? 1 : options.minConf

  // filter by minConf and sort by descending value
  var unspents = this.unspents.filter(function(unspent) {
    return unspent.confirmations >= minConf
  }).sort(function(o1, o2) {
    return o2.value - o1.value
  })

  var txb = new TransactionBuilder()
  var targetValue = 0

  outputs.forEach(function(output) {
    if (output.value <= this.network.dustThreshold) {
      throw new Error(output.value + ' must be above dust threshold (' + this.network.dustThreshold + ' Satoshis)')
    }

    targetValue += output.value
    txb.addOutput(output.address, output.value)
  }, this)

  var accum = 0
  var addresses = []
  var subTotal = targetValue

  for (var i = 0; i < unspents.length; ++i) {
    var unspent = unspents[i]
    addresses.push(unspent.address)

    txb.addInput(unspent.txId, unspent.index)

    var fee
    if (fixedFee === undefined) {
      fee = estimatePaddedFee(txb.buildIncomplete(), this.network)

    } else {
      fee = fixedFee
    }

    accum += unspent.value
    subTotal = targetValue + fee

    if (accum >= subTotal) {
      var change = accum - subTotal

      if (change > this.network.dustThreshold) {
        txb.addOutput(changeAddress || this.getChangeAddress(), change)
      }

      break
    }
  }

  if (accum < subTotal) {
    throw new Error('Not enough funds (incl. fee): ' + accum + ' < ' + subTotal)
  }

  return this.signWith(txb, addresses).build()
}

Wallet.prototype.generateAddress = function() {
  this.account.nextAddress()

  return this.getAddress()
}

Wallet.prototype.getAddress = function() {
  return this.account.getAddress()
}

Wallet.prototype.getBalance = function(minConf) {
  minConf = minConf || 0

  return this.unspents.filter(function(unspent) {
    return unspent.confirmations >= minConf

  }).reduce(function(accum, unspent) {
    return accum + unspent.value
  }, 0)
}

Wallet.prototype.getChangeAddress = function() {
  return this.account.getChangeAddress()
}

Wallet.prototype.getUnspentOutputs = function(minConf) {
  minConf = minConf || 0

  return this.unspents.filter(function(unspent) {
    return unspent.confirmations >= minConf

  }).map(function(unspent) {
    return {
      address: unspent.address,
      confirmations: unspent.confirmations,
      index: unspent.index,
      txId: unspent.txId,
      value: unspent.value
    }
  })
}

Wallet.prototype.setUnspentOutputs = function(unspents) {
  this.unspents = unspents.map(function(unspent) {
    var txId = unspent.txId
    var index = unspent.index

    assert.equal(typeof txId, 'string', 'Expected txId, got ' + txId)
    assert.equal(txId.length, 64, 'Expected valid txId, got ' + txId)
    assert.doesNotThrow(function() { Address.fromBase58Check(unspent.address) }, 'Expected Base58 Address, got ' + unspent.address)
    assert(isFinite(index), 'Expected number index, got ' + index)
    assert.equal(typeof unspent.value, 'number', 'Expected number value, got ' + unspent.value)
    assert.equal(typeof unspent.confirmations, 'number', 'Expected number confirmations, got ' + unspent.confirmations)

    var txHash = bufferutils.reverse(new Buffer(txId, 'hex'))

    unspent = {
      address: unspent.address,
      confirmations: unspent.confirmations || 0,
      index: index,
      txHash: txHash,
      txId: txId,
      value: unspent.value
    }

    return unspent
  }, this)
}

Wallet.prototype.signWith = function(tx, addresses) {
  var external = this.getExternalAccount()
  var internal = this.getInternalAccount()
  var nodes = this.account.getNodes(addresses, external, internal)
  var keys = nodes.map(function(node) { return node.privKey })

  keys.forEach(function(key, i) {
    tx.sign(i, key)
  })

  return tx
}

module.exports = Wallet
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */

let General = {
  title: 'General',
  description: (

      Configure your container service here or install from Universe.

  ),
  type: 'object',
  properties: {
    id: {
      title: 'ID',
      description: 'The ID for the service',
      type: 'string',
      getter: function (service) {
        return service.getId();
      }
    },
    resources: {
      type: 'group',
      properties: {
        cpus: {
          title: 'CPUs',
          description: 'The amount of CPUs used for the service',
          type: 'number',
          default: 1,
          getter: function (service) {
            return `${service.getCpus() || this.default}`;
          }
        },
        mem: {
          title: 'Mem (MiB)',
          type: 'number',
          default: 128,
          getter: function (service) {
            return `${service.getMem() || this.default}`;
          }
        },
        disk: {
          title: 'Disk (MiB)',
          type: 'number',
          default: 0,
          getter: function (service) {
            return `${service.getDisk() || this.default}`;
          }
        },
        instances: {
          title: 'Instances',
          type: 'number',
          default: 1,
          getter: function (service) {
            return `${service.getInstancesCount() || this.default}`;
          }
        }
      }
    },
    cmd: {
      title: 'Command',
      description: 'The command executed by the service',
      type: 'string',
      multiLine: true,
      getter: function (service) {
        return service.getCommand();
      }
    }
  },
  required: [
    'id'
  ]
};

module.exports = General;
<commit_msg>Update General.js<commit_after>/* eslint-disable no-unused-vars */
import React from 'react';
import {Link} from 'react-router';
/* eslint-enable no-unused-vars */

let General = {
  title: 'General',
  description: (

      Configure your container service here or <Link to"universe">install from Universe</Link>.

  ),
  type: 'object',
  properties: {
    id: {
      title: 'ID',
      description: 'The ID for the service',
      type: 'string',
      getter: function (service) {
        return service.getId();
      }
    },
    resources: {
      type: 'group',
      properties: {
        cpus: {
          title: 'CPUs',
          description: 'The amount of CPUs used for the service',
          type: 'number',
          default: 1,
          getter: function (service) {
            return `${service.getCpus() || this.default}`;
          }
        },
        mem: {
          title: 'Mem (MiB)',
          type: 'number',
          default: 128,
          getter: function (service) {
            return `${service.getMem() || this.default}`;
          }
        },
        disk: {
          title: 'Disk (MiB)',
          type: 'number',
          default: 0,
          getter: function (service) {
            return `${service.getDisk() || this.default}`;
          }
        },
        instances: {
          title: 'Instances',
          type: 'number',
          default: 1,
          getter: function (service) {
            return `${service.getInstancesCount() || this.default}`;
          }
        }
      }
    },
    cmd: {
      title: 'Command',
      description: 'The command executed by the service',
      type: 'string',
      multiLine: true,
      getter: function (service) {
        return service.getCommand();
      }
    }
  },
  required: [
    'id'
  ]
};

module.exports = General;
<|endoftext|>


<commit_before>/** @babel */

import helpers from '../spec-helpers'
import path from 'path'
import LatexmkBuilder from '../../lib/builders/latexmk'
import _ from 'lodash'
import fs from 'fs-plus'

describe('LatexmkBuilder', () => {
  let builder, fixturesPath, filePath

  beforeEach(() => {
    waitsForPromise(() => {
      return helpers.activatePackages()
    })
    builder = new LatexmkBuilder()
    fixturesPath = helpers.cloneFixtures()
    filePath = path.join(fixturesPath, 'file.tex')
  })

  describe('constructArgs', () => {
    it('produces default arguments when package has default config values', () => {
      const expectedArgs = [
        '-interaction=nonstopmode',
        '-f',
        '-cd',
        '-file-line-error',
        '-synctex=1',
        '-pdflatex="pdflatex"',
        '-pdf',
        `"${filePath}"`
      ]
      const args = builder.constructArgs(filePath)

      expect(args).toEqual(expectedArgs)
    })

    it('adds -g flag when rebuild is passed', () => {
      expect(builder.constructArgs(filePath, null, true)).toContain('-g')
    })

    it('adds -shell-escape flag when package config value is set', () => {
      atom.config.set('latex.enableShellEscape', true)
      expect(builder.constructArgs(filePath)).toContain('-shell-escape')
    })

    it('disables synctex according to package config', () => {
      atom.config.set('latex.enableSynctex', false)
      expect(builder.constructArgs(filePath)).not.toContain('-synctex=1')
    })

    it('adds -outdir=<path> argument according to package config', () => {
      const outdir = 'bar'
      const expectedArg = `-outdir="${outdir}"`
      atom.config.set('latex.outputDirectory', outdir)

      expect(builder.constructArgs(filePath)).toContain(expectedArg)
    })

    it('adds pdflatex arguments according to package config', () => {
      atom.config.set('latex.engine', 'lualatex')
      expect(builder.constructArgs(filePath)).toContain('-pdflatex="lualatex"')
    })

    it('adds a custom engine string according to package config', () => {
      atom.config.set('latex.customEngine', 'pdflatex %O %S')
      expect(builder.constructArgs(filePath)).toContain('-pdflatex="pdflatex %O %S"')
    })

    it('adds -ps and removes -pdf arguments according to package config', () => {
      atom.config.set('latex.outputFormat', 'ps')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-ps')
      expect(args).not.toContain('-pdf')
    })

    it('adds -dvi and removes -pdf arguments according to package config', () => {
      atom.config.set('latex.outputFormat', 'dvi')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-dvi')
      expect(args).not.toContain('-pdf')
    })

    it('adds latex dvipdfmx arguments according to package config', () => {
      atom.config.set('latex.engine', 'uplatex')
      atom.config.set('latex.producer', 'dvipdfmx')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-latex="uplatex"')
      expect(args).toContain('-pdfdvi -e "$dvipdf = \'dvipdfmx %O -o %D %S\';"')
      expect(args).not.toContain('-pdf')
    })

    it('adds latex dvipdf arguments according to package config', () => {
      atom.config.set('latex.engine', 'uplatex')
      atom.config.set('latex.producer', 'dvipdf')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-latex="uplatex"')
      expect(args).toContain('-pdfdvi -e "$dvipdf = \'dvipdf %O %S %D\';"')
      expect(args).not.toContain('-pdf')
    })

    it('adds latex ps arguments according to package config', () => {
      atom.config.set('latex.engine', 'uplatex')
      atom.config.set('latex.producer', 'ps2pdf')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-latex="uplatex"')
      expect(args).toContain('-pdfps')
      expect(args).not.toContain('-pdf')
    })

    it('adds a jobname argument when passed a non-null jobname', () => {
      expect(builder.constructArgs(filePath, 'foo')).toContain('-jobname=foo')
    })
  })

  describe('run', () => {
    let exitCode, parsedLog

    it('successfully executes latexmk when given a valid TeX file', () => {
      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(0)
      })
    })

    it('successfully executes latexmk when given a file path containing spaces', () => {
      filePath = path.join(fixturesPath, 'filename with spaces.tex')

      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(0)
      })
    })

    it('fails with code 12 and various errors, warnings and info messages are produced in log file', () => {
      filePath = path.join(fixturesPath, 'error-warning.tex')
      const subFilePath = path.join(fixturesPath, 'sub', 'wibble.tex')

      waitsForPromise(() => {
        return builder.run(filePath).then(code => {
          exitCode = code
          parsedLog = builder.parseLogFile(filePath)
        })
      })

      runs(() => {
        const messages = [
          { type: 'Error', text: 'There\'s no line here to end' },
          { type: 'Error', text: 'Argument of \\@sect has an extra }' },
          { type: 'Error', text: 'Paragraph ended before \\@sect was complete' },
          { type: 'Error', text: 'Extra alignment tab has been changed to \\cr' },
          { type: 'Warning', text: 'Reference `tab:snafu\' on page 1 undefined' },
          { type: 'Error', text: 'Class foo: Significant class issue' },
          { type: 'Warning', text: 'Class foo: Class issue' },
          { type: 'Warning', text: 'Class foo: Nebulous class issue' },
          { type: 'Info', text: 'Class foo: Insignificant class issue' },
          { type: 'Error', text: 'Package bar: Significant package issue' },
          { type: 'Warning', text: 'Package bar: Package issue' },
          { type: 'Warning', text: 'Package bar: Nebulous package issue' },
          { type: 'Info', text: 'Package bar: Insignificant package issue' },
          { type: 'Warning', text: 'There were undefined references' }
        ]

        // Loop through the required messages and make sure that each one appears
        // in the parsed log output. We do not do a direct one-to-one comparison
        // since there will likely be font messages which may be dependent on
        // which TeX distribution is being used or which fonts are currently
        // installed.
        for (const message of messages) {
          expect(_.some(parsedLog.messages,
            logMessage => message.type === logMessage.type && message.text === logMessage.text)).toBe(true, `Message = ${message.text}`)
        }

        expect(_.every(parsedLog.messages,
          logMessage => !logMessage.filePath || logMessage.filePath === filePath || logMessage.filePath === subFilePath))
          .toBe(true, 'Incorrect file path resolution in log.')

        expect(exitCode).toBe(12)
      })
    })

    it('fails to execute latexmk when given invalid arguments', () => {
      spyOn(builder, 'constructArgs').andReturn(['-invalid-argument'])

      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(10)
      })
    })

    it('fails to execute latexmk when given invalid file path', () => {
      filePath = path.join(fixturesPath, 'foo.tex')
      const args = builder.constructArgs(filePath)

      // Need to remove the 'force' flag to trigger the desired failure.
      const removed = args.splice(1, 1)
      expect(removed).toEqual(['-f'])

      spyOn(builder, 'constructArgs').andReturn(args)

      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(11)
      })
    })

    function checkCustomRules (name, extensions) {
      const dir = path.join(fixturesPath, 'latexmk')
      filePath = path.format({ dir, name, ext: '.tex' })
      atom.config.set('latex.enableLatexmkrc', true)

      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(0)
        for (const ext of extensions) {
          const output = path.format({ dir, name, ext })
          expect(fs.existsSync(output)).toBe(true, `Check the existance of ${ext} file.`)
        }
      })
    }

    it('successfully creates glossary files when using the glossaries package', () => {
      checkCustomRules('glossaries-test', ['.acn', '.acr', '.glo', '.gls', '.pdf'])
    })

    it('successfully creates nomenclature files when using the nomencl package', () => {
      checkCustomRules('nomencl-test', ['.nlo', '.nls', '.pdf'])
    })
  })
})
<commit_msg>Add index package tests<commit_after>/** @babel */

import helpers from '../spec-helpers'
import path from 'path'
import LatexmkBuilder from '../../lib/builders/latexmk'
import _ from 'lodash'
import fs from 'fs-plus'

describe('LatexmkBuilder', () => {
  let builder, fixturesPath, filePath

  beforeEach(() => {
    waitsForPromise(() => {
      return helpers.activatePackages()
    })
    builder = new LatexmkBuilder()
    fixturesPath = helpers.cloneFixtures()
    filePath = path.join(fixturesPath, 'file.tex')
  })

  describe('constructArgs', () => {
    it('produces default arguments when package has default config values', () => {
      const expectedArgs = [
        '-interaction=nonstopmode',
        '-f',
        '-cd',
        '-file-line-error',
        '-synctex=1',
        '-pdflatex="pdflatex"',
        '-pdf',
        `"${filePath}"`
      ]
      const args = builder.constructArgs(filePath)

      expect(args).toEqual(expectedArgs)
    })

    it('adds -g flag when rebuild is passed', () => {
      expect(builder.constructArgs(filePath, null, true)).toContain('-g')
    })

    it('adds -shell-escape flag when package config value is set', () => {
      atom.config.set('latex.enableShellEscape', true)
      expect(builder.constructArgs(filePath)).toContain('-shell-escape')
    })

    it('disables synctex according to package config', () => {
      atom.config.set('latex.enableSynctex', false)
      expect(builder.constructArgs(filePath)).not.toContain('-synctex=1')
    })

    it('adds -outdir=<path> argument according to package config', () => {
      const outdir = 'bar'
      const expectedArg = `-outdir="${outdir}"`
      atom.config.set('latex.outputDirectory', outdir)

      expect(builder.constructArgs(filePath)).toContain(expectedArg)
    })

    it('adds pdflatex arguments according to package config', () => {
      atom.config.set('latex.engine', 'lualatex')
      expect(builder.constructArgs(filePath)).toContain('-pdflatex="lualatex"')
    })

    it('adds a custom engine string according to package config', () => {
      atom.config.set('latex.customEngine', 'pdflatex %O %S')
      expect(builder.constructArgs(filePath)).toContain('-pdflatex="pdflatex %O %S"')
    })

    it('adds -ps and removes -pdf arguments according to package config', () => {
      atom.config.set('latex.outputFormat', 'ps')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-ps')
      expect(args).not.toContain('-pdf')
    })

    it('adds -dvi and removes -pdf arguments according to package config', () => {
      atom.config.set('latex.outputFormat', 'dvi')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-dvi')
      expect(args).not.toContain('-pdf')
    })

    it('adds latex dvipdfmx arguments according to package config', () => {
      atom.config.set('latex.engine', 'uplatex')
      atom.config.set('latex.producer', 'dvipdfmx')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-latex="uplatex"')
      expect(args).toContain('-pdfdvi -e "$dvipdf = \'dvipdfmx %O -o %D %S\';"')
      expect(args).not.toContain('-pdf')
    })

    it('adds latex dvipdf arguments according to package config', () => {
      atom.config.set('latex.engine', 'uplatex')
      atom.config.set('latex.producer', 'dvipdf')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-latex="uplatex"')
      expect(args).toContain('-pdfdvi -e "$dvipdf = \'dvipdf %O %S %D\';"')
      expect(args).not.toContain('-pdf')
    })

    it('adds latex ps arguments according to package config', () => {
      atom.config.set('latex.engine', 'uplatex')
      atom.config.set('latex.producer', 'ps2pdf')
      const args = builder.constructArgs(filePath)
      expect(args).toContain('-latex="uplatex"')
      expect(args).toContain('-pdfps')
      expect(args).not.toContain('-pdf')
    })

    it('adds a jobname argument when passed a non-null jobname', () => {
      expect(builder.constructArgs(filePath, 'foo')).toContain('-jobname=foo')
    })
  })

  describe('run', () => {
    let exitCode, parsedLog

    it('successfully executes latexmk when given a valid TeX file', () => {
      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(0)
      })
    })

    it('successfully executes latexmk when given a file path containing spaces', () => {
      filePath = path.join(fixturesPath, 'filename with spaces.tex')

      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(0)
      })
    })

    it('fails with code 12 and various errors, warnings and info messages are produced in log file', () => {
      filePath = path.join(fixturesPath, 'error-warning.tex')
      const subFilePath = path.join(fixturesPath, 'sub', 'wibble.tex')

      waitsForPromise(() => {
        return builder.run(filePath).then(code => {
          exitCode = code
          parsedLog = builder.parseLogFile(filePath)
        })
      })

      runs(() => {
        const messages = [
          { type: 'Error', text: 'There\'s no line here to end' },
          { type: 'Error', text: 'Argument of \\@sect has an extra }' },
          { type: 'Error', text: 'Paragraph ended before \\@sect was complete' },
          { type: 'Error', text: 'Extra alignment tab has been changed to \\cr' },
          { type: 'Warning', text: 'Reference `tab:snafu\' on page 1 undefined' },
          { type: 'Error', text: 'Class foo: Significant class issue' },
          { type: 'Warning', text: 'Class foo: Class issue' },
          { type: 'Warning', text: 'Class foo: Nebulous class issue' },
          { type: 'Info', text: 'Class foo: Insignificant class issue' },
          { type: 'Error', text: 'Package bar: Significant package issue' },
          { type: 'Warning', text: 'Package bar: Package issue' },
          { type: 'Warning', text: 'Package bar: Nebulous package issue' },
          { type: 'Info', text: 'Package bar: Insignificant package issue' },
          { type: 'Warning', text: 'There were undefined references' }
        ]

        // Loop through the required messages and make sure that each one appears
        // in the parsed log output. We do not do a direct one-to-one comparison
        // since there will likely be font messages which may be dependent on
        // which TeX distribution is being used or which fonts are currently
        // installed.
        for (const message of messages) {
          expect(_.some(parsedLog.messages,
            logMessage => message.type === logMessage.type && message.text === logMessage.text)).toBe(true, `Message = ${message.text}`)
        }

        expect(_.every(parsedLog.messages,
          logMessage => !logMessage.filePath || logMessage.filePath === filePath || logMessage.filePath === subFilePath))
          .toBe(true, 'Incorrect file path resolution in log.')

        expect(exitCode).toBe(12)
      })
    })

    it('fails to execute latexmk when given invalid arguments', () => {
      spyOn(builder, 'constructArgs').andReturn(['-invalid-argument'])

      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(10)
      })
    })

    it('fails to execute latexmk when given invalid file path', () => {
      filePath = path.join(fixturesPath, 'foo.tex')
      const args = builder.constructArgs(filePath)

      // Need to remove the 'force' flag to trigger the desired failure.
      const removed = args.splice(1, 1)
      expect(removed).toEqual(['-f'])

      spyOn(builder, 'constructArgs').andReturn(args)

      waitsForPromise(() => {
        return builder.run(filePath).then(code => { exitCode = code })
      })

      runs(() => {
        expect(exitCode).toBe(11)
      })
    })

    function doCustomRuleCheck (label, name, extensions, outputDirectory) {
      it(label, () => {
        let dir = path.join(fixturesPath, 'latexmk')
        filePath = path.format({ dir, name, ext: '.tex' })
        dir = path.join(dir, outputDirectory)
        atom.config.set('latex.enableLatexmkrc', true)
        atom.config.set('latex.outputDirectory', outputDirectory)

        waitsForPromise(() => {
          return builder.run(filePath).then(code => { exitCode = code })
        })

        runs(() => {
          expect(exitCode).toBe(0)
          for (const ext of extensions) {
            const output = path.format({ dir, name, ext })
            expect(fs.existsSync(output)).toBe(true, `Check the existance of ${ext} file.`)
          }
        })
      })
    }

    function checkCustomRules (label, name, extensions) {
      doCustomRuleCheck(label, name, extensions, '')
      doCustomRuleCheck(`${label} with an output directory`, name, extensions, 'build')
    }

    checkCustomRules('successfully creates glossary files when using the glossaries package',
      'glossaries-test',
      ['.acn', '.acr', '.glo', '.gls', '.pdf']
    )

    checkCustomRules('successfully creates nomenclature files when using the nomencl package',
      'nomencl-test',
      ['.nlo', '.nls', '.pdf']
    )

    checkCustomRules('successfully creates index files when using the index package',
      'index-test',
      ['.idx', '.ind', '.pdf']
    )
  })
})
<|endoftext|>


<commit_before>'use strict';

const util = require('util');

const Promise = require('bluebird');
const ObjectId = require('mongodb').ObjectId;

// const logger = require('lib/modules/logger');
// const QueryResult = require('../queryResult');

const EXTRACT_QUERY_REGEX_PATTERN = '^(?:db).*.(?:%s)\\(([^]+)\\)'; //https://regex101.com/r/nM7fJ5/3
const EXTRACT_OPTIONS_REGEX = /({[^]+})(?:[\s\n\r])*,(?:[\s\n\r])*({[^]+})/;

class BaseQuery {
  constructor() {
    this.rawQuery = null; //the full raw query ex. 'db.users.find({ .... })'
  }

  parse(rawQuery, options) {
    let _this = this;
    options = options || {};

    _this.rawQuery = rawQuery;

    return new Promise((resolve, reject) => {
      if (!rawQuery) return reject(new Error('baseQuery - parse() : rawQuery is required'));

      let query = _parseRawQuery(rawQuery, {
        methodName: _this.mongoMethod,
        extractOptions: _this.extractOptions,
        evalContext: options.context || {}
      });

      if (!query || !query.query) return reject(new Error('error parsing query'));

      _this.query = query.query;
      _this.queryOptions = query.queryOptions;

      return resolve(_this);
    });
  }
}

function _parseValueFromRawQuery(rawQuery, methodName) {
  let regex = _getRegExpForMethodName(methodName);

  let matches = regex.exec(rawQuery);

  return matches && matches.length > 1 ? matches[1] : null;
}

/**
 * @method _parseRawQuery - parses a raw query, ex. 'db.users.find({...})'
 * @param {String} rawQuery
 * @param {Object} options
 * @param {String} options.methodName  - name of them mongo method that is trying to be executed
 * @param {Bool} options.extractOptions - whether or not we should parse a 2nd options objects (update, updateMany)
 * @param {Object} options.evalContext - context to evalulate the js expression in
 * @returns
 */
function _parseRawQuery(rawQuery, options) {
  options = options || {};

  let rawQueryValue = _parseValueFromRawQuery(rawQuery, options.methodName);

  if (!rawQueryValue) return null;

  if (!options.extractOptions) {
    let query = _evalQueryValue(rawQueryValue, options.evalContext);

    if (_.isError(query)) return new Error('error parsing query');

    return {
      query: query
    };
  } else {
    let matches = rawQuery.match(EXTRACT_OPTIONS_REGEX);

    if (!matches || !matches.length || matches.length <= 2) return new Error('error parsing query');

    let query = _evalQueryValue(matches[1], options.evalContext);
    let queryOptions = _evalQueryValue(matches[2], options.evalContext);

    if (_.isError(query)) return new Error('error parsing query');
    if (_.isError(queryOptions)) return new Error('error parsing query options');

    return {
      query: query,
      queryOptions: queryOptions
    };
  }
}

function _getRegExpForMethodName(methodName) {
  var regexPattern = util.format(EXTRACT_QUERY_REGEX_PATTERN, methodName);
  return new RegExp(regexPattern);
}

/**
 * @method evalQueryValue - evaluates a JS expression from the Mongotron code editor
 * @private
 *
 * @param {String} raw value from editor
 */
function _evalQueryValue(rawValue, evalContext) {
  evalContext = evalContext || {};
  evalContext.ObjectId = ObjectId;

  var queryValue;

  try {
    queryValue = eval.call(evalContext, '(' + rawValue + ')'); // jshint ignore:line
  } catch (err) {
    queryValue = err;
  }

  return queryValue;
}

module.exports = BaseQuery;
<commit_msg>delegate to parser<commit_after>'use strict';

const Promise = require('bluebird');
const ObjectId = require('mongodb').ObjectId;

const parser = require('../parser');

class BaseQuery {
  constructor() {
    this.rawQuery = null; //the full raw query ex. 'db.users.find({ .... })'
  }

  parse(rawQuery, options) {
    let _this = this;
    options = options || {};

    _this.rawQuery = rawQuery;

    return new Promise((resolve, reject) => {
      if (!rawQuery) return reject(new Error('baseQuery - parse() : rawQuery is required'));

      if (!parser.isValidQuery(rawQuery)) return reject(new Error('Invalid query'));

      var functionName = parser.parseFunction(rawQuery);

      if (!functionName) return reject(new Error('Invalid mongo function'));

      let query = _parseRawQuery(rawQuery, {
        methodName: _this.mongoMethod,
        extractOptions: _this.extractOptions,
        evalContext: options.evalContext || {}
      });

      if (!query || !query.query) return reject(new Error('error parsing query'));
      if (_.isError(query)) return reject(query);

      _this.query = query.query;
      _this.queryOptions = query.queryOptions;

      return resolve(_this);
    });
  }
}

/**
 * @method _parseRawQuery - parses a raw query, ex. 'db.users.find({...})'
 * @param {String} rawQuery
 * @param {Object} options
 * @param {String} options.methodName  - name of them mongo method that is trying to be executed
 * @param {Bool} options.extractOptions - whether or not we should parse a 2nd options objects (update, updateMany)
 * @param {Object} options.evalContext - context to evalulate the js expression in
 * @returns
 */
function _parseRawQuery(rawQuery, options) {
  options = options || {};

  var query = null;
  var queryOptions = null;

  if (!options.extractOptions) {
    let rawQueryValue = parser.parseQuery(rawQuery);

    if (!rawQueryValue) return new Error('error parsing query');

    query = _evalQueryValue(rawQueryValue, options.evalContext);

    if (_.isError(query)) return new Error('error evaluating query');
  } else {
    let rawQueryValue = parser.parseQuery(rawQuery);
    let rawOptionsValue = parser.parseOptions(rawQuery);

    if (!rawQueryValue) return new Error('error parsing query');
    if (!rawOptionsValue) return new Error('error parsing query options');

    query = _evalQueryValue(rawQueryValue, options.evalContext);
    queryOptions = _evalQueryValue(rawOptionsValue, options.evalContext);

    if (_.isError(query)) return new Error('error evaluating query');
    if (_.isError(queryOptions)) return new Error('error evaluating query');
  }

  return {
    query: query,
    queryOptions: queryOptions
  };
}

/**
 * @method evalQueryValue - evaluates a JS expression from the Mongotron code editor
 * @private
 *
 * @param {String} raw value from editor
 */
function _evalQueryValue(rawValue, evalContext) {
  evalContext = evalContext || {};
  evalContext.ObjectId = ObjectId;

  var queryValue;

  try {
    queryValue = eval.call(evalContext, '(' + rawValue + ')'); // jshint ignore:line
  } catch (err) {
    queryValue = err;
  }

  return queryValue;
}

module.exports = BaseQuery;
<|endoftext|>


<commit_before>
import { Loader } from './loader'

const system = () => {
  if (!self.System) {
    let scope = new URL(self.registration.scope)
    let base = scope

    if (KERNEL_CONFIG.WORKER_BASE) {
      base = new URL(KERNEL_CONFIG.WORKER_BASE, base)
    }

    self.System = new Loader({
      base: base
    })

    console.warn('[SW] Kick-off from ' + base.toString())

    if (KERNEL_CONFIG.WORKER_EMBED) {
      System.set(KERNEL_CONFIG.WORKER_INIT, require(KERNEL_CONFIG.WORKER_INIT))
    }
  }

  return System
}

const init = async () => {
  return system().import(KERNEL_CONFIG.WORKER_INIT)
}

export default function() {
  this.addEventListener('install', (event) => {
    event.waitUntil(
      init()
        .then(worker => worker.install(event))
        .catch(error => { console.error(error); throw error })
    )
  })

  this.addEventListener('activate', (event) => {
    event.waitUntil(
      init()
        .then(worker => worker.activate(event))
        .catch(error => { console.error(error); throw error })
    )
  })

  this.addEventListener('fetch', (event) => {
    event.waitUntil(
      init()
        .then(worker => worker.fetch(event))
        .catch(error => { console.error(error); throw error })
    )
  })

  this.addEventListener('message', (event) => {
    if(event.data === 'kernel:sw-force-reload') {
      loader = undefined
    }

    event.waitUntil(
      init()
        .then(worker => worker.message(event))
        .catch(error => { console.error(error); throw error })
    )
  })
}
<commit_msg>Remove useless async<commit_after>
import { Loader } from './loader'

const system = () => {
  if (!self.System) {
    let scope = new URL(self.registration.scope)
    let base = scope

    if (KERNEL_CONFIG.WORKER_BASE) {
      base = new URL(KERNEL_CONFIG.WORKER_BASE, base)
    }

    self.System = new Loader({
      base: base
    })

    console.warn('[SW] Kick-off from ' + base.toString())

    if (KERNEL_CONFIG.WORKER_EMBED) {
      System.set(KERNEL_CONFIG.WORKER_INIT, require(KERNEL_CONFIG.WORKER_INIT))
    }
  }

  return System
}

const init = () => {
  return system().import(KERNEL_CONFIG.WORKER_INIT)
}

export default function() {
  this.addEventListener('install', (event) => {
    event.waitUntil(
      init()
        .then(worker => worker.install(event))
        .catch(error => { console.error(error); throw error })
    )
  })

  this.addEventListener('activate', (event) => {
    event.waitUntil(
      init()
        .then(worker => worker.activate(event))
        .catch(error => { console.error(error); throw error })
    )
  })

  this.addEventListener('fetch', (event) => {
    event.waitUntil(
      init()
        .then(worker => worker.fetch(event))
        .catch(error => { console.error(error); throw error })
    )
  })

  this.addEventListener('message', (event) => {
    if(event.data === 'kernel:sw-force-reload') {
      loader = undefined
    }

    event.waitUntil(
      init()
        .then(worker => worker.message(event))
        .catch(error => { console.error(error); throw error })
    )
  })
}
<|endoftext|>


<commit_before>/*
 * seqJS
 * https://github.com/haydnKing/seqJS
 *
 * Copyright (c) 2014 Haydn King
 * Licensed under the MIT license.
 */

var seqJS = seqJS || {};

(function(){

    var pad_l = function(str, val){
        if(str.length > val){
            return str.substring(0,val);
        }
        return spaces(val - str.length) + str;
    };
    var spaces = function(val){
        var r = '';
        for(var i = 0; i < val; i++){
            r += ' ';
        }
        return r;
    };

    var writers = {};

    var gb_write = function(record){
        var get_date = function(){
            var d = new Date();
            return d.getDate().toString() + '-' + [
                'JAN',
                'FEB',
                'MAR',
                'APR',
                'MAY',
                'JUN',
                'JUL',
                'AUG',
                'SEP',
                'OCT',
                'NOV',
                'DEC'][d.getMonth()] + '-' + d.getFullYear().toString();
        };

        var get_locus = function(record){
            var ra = record.annotations,
                name = record.name,
                len = record.length().toString();
            if((name.length + len.length) >= 28){
                name = name.substr(0, 27 - len.length);
            }
            return "LOCUS       " +
              name + ' ' +
              pad_l(len, 27 - name.length) +
              ' ' + record.seq.unit() + ' ' +
              pad_l(ra.residue_type || '', 6) +
              pad_l( (ra.topology === 'circular') ? 'circular' : '', 13) +
              ' ' + (ra.data_division || 'SYN') +
              ' ' + (ra.date || get_date());
        };

        return get_locus(record);
    };

    writers['gb'] = gb_write;
    writers['genbank'] = gb_write;

    /*
     * seqJS.write(record, type) - write the record to a string and return the
     *  string
     *      type: 'gb' or 'fasta'
     */
    seqJS.write = function(record, type){
        if(Object.keys(writers).indexOf(type) > -1){
            return writers[type](record);
        }
        else {
            throw "Unknown format \'"+type+"\'. Known formats are " +
                Object.keys(writers).join(', ') + '.';
        }
    };

}());

<commit_msg>Write defninition line<commit_after>/*
 * seqJS
 * https://github.com/haydnKing/seqJS
 *
 * Copyright (c) 2014 Haydn King
 * Licensed under the MIT license.
 */

var seqJS = seqJS || {};

(function(){

    var pad_l = function(str, val){
        if(str.length > val){
            return str.substring(0,val);
        }
        return spaces(val - str.length) + str;
    };
    var pad_r = function(str, val){
        if(str.length > val){
            return str.substring(0,val);
        }
        return str + spaces(val - str.length);
    };
    var spaces = function(val){
        var r = '';
        for(var i = 0; i < val; i++){
            r += ' ';
        }
        return r;
    };

    var writers = {};

    var gb_write = function(record){
        var get_date = function(){
            var d = new Date();
            return d.getDate().toString() + '-' + [
                'JAN',
                'FEB',
                'MAR',
                'APR',
                'MAY',
                'JUN',
                'JUL',
                'AUG',
                'SEP',
                'OCT',
                'NOV',
                'DEC'][d.getMonth()] + '-' + d.getFullYear().toString();
        };

        var line_wrap = function(line, max_len, wrap){
            wrap = wrap || '\n';
            var lines = [],
                l = '',
                s = line.split(' '),
                w;
            for(var i in s){
                w = s[i];
                if((l.length+w.length) >= max_len){
                    lines.push(l);
                    l = w;
                }
                else{
                    l += ' ' + w;
                }
            }
            lines.push(l);
            return lines.join(wrap);
        };

        var write_locus = function(record){
            var ra = record.annotations,
                name = record.name,
                len = record.length().toString();
            if((name.length + len.length) >= 28){
                name = name.substr(0, 27 - len.length);
            }
            return "LOCUS       " +
              name + ' ' +
              pad_l(len, 27 - name.length) +
              ' ' + record.seq.unit() + ' ' +
              pad_l(ra.residue_type || '', 6) +
              pad_l( (ra.topology === 'circular') ? 'circular' : '', 13) +
              ' ' + (ra.data_division || 'SYN') +
              ' ' + (ra.date || get_date()) + '\n';
        };

        var write_annotation = function(key, value, indent){
            indent = indent || false;

            return pad_r( (indent ? '  ' : '') + key.toUpperCase(), 10) +
                ' ' + line_wrap(value,69,'\n            ');
        };

        return write_locus(record) + write_annotation('definition', record.desc);
    };

    writers['gb'] = gb_write;
    writers['genbank'] = gb_write;

    /*
     * seqJS.write(record, type) - write the record to a string and return the
     *  string
     *      type: 'gb' or 'fasta'
     */
    seqJS.write = function(record, type){
        if(Object.keys(writers).indexOf(type) > -1){
            return writers[type](record);
        }
        else {
            throw "Unknown format \'"+type+"\'. Known formats are " +
                Object.keys(writers).join(', ') + '.';
        }
    };

}());

<|endoftext|>


<commit_before>$(document).ready(function() {
  var player = $("video.html5-main-video")[0];

  // Nothing to do if the youtube player does not exist
  if (!player) {
    return;
  }

  var context = new AudioContext();
  var source = context.createMediaElementSource(player);
  source.connect(context.destination);

  // Set up the different audio nodes we will use for the app
  var analyser = context.createAnalyser();
  var distortion = context.createWaveShaper();
  var gainNode = context.createGain();
  var biquadFilter = context.createBiquadFilter();
  var convolver = context.createConvolver();
  var oscillator = context.createOscillator();
  var compressor = context.createDynamicsCompressor();

  $.get(chrome.extension.getURL("src/youmix.html"), function(data) {
    $('#watch-header').after(data);

    // Add the range slider
    $('input[type="range"]').rangeslider({
      polyfill: false,
      rangeClass: 'rangeslider',
      fillClass: 'rangeslider__fill',
      handleClass: 'rangeslider__handle'
    });
  });

  // Listen for changes to the presets
  $('body').on('change', "#ym-presets", function() {
    var preset = $(this).val();

    // Hide all the options
    $('.ym-node-group').hide();

    // Show the set of options matching the preset selected
    if (preset !== 'normal') {
      $("div[data-node-group='" + preset +"']").show();
    }

    // Load the filter
    presets(preset);
  });

  // Listen for changes to the options
  $('body').on('change', ".ym-node-group input[type='range'], .ym-node-group select", function() {
    var value = $(this).val();
    var node = $(this).data('node');
    var property = $(this).data('node-property');

    switch (node) {
      case 'biquadfilter':
        if (property === 'type') {
          biquadFilter.type = $(this).val()
        } else {
          biquadFilter[property].value = value;
        }

        break;

      case 'compressor':
        compressor[property].value = value;
        break;

      case 'oscillator':
        oscillator[property].value = value;
        break;

      case 'distortion':
        if (property === 'amount') {
          value = parseInt(value, 10);
          distortion.curve = makeDistortionCurve(value);
        } else if (property === 'oversample') {
          distortion.oversample = value;
        }
        break;
    }
  });

  function presets(preset) {
    source.disconnect();

    switch (preset) {
      case 'normal':
        source.connect(context.destination);
        break;

      /*
        The BiquadFilterNode interface represents a simple low-order filter.
      */
      case 'biquadfilter':
        source.connect(biquadFilter);
        biquadFilter.type = "lowpass";
        biquadFilter.frequency.value = 50;
        biquadFilter.detune.value = 100;
        biquadFilter.Q.value = 10;

        // Connect to output
        biquadFilter.connect(context.destination);
        break;

      /*
        The DynamicsCompressorNode interface provides a compression effect,
        which lowers the volume of the loudest parts of the signal in order to
        help prevent clipping and distortion that can occur when multiple sounds
        are played and multiplexed together at once.
      */
      case 'compressor':
        // Connect the source node to the destination
        source.connect(compressor);

        // These are the default values
        compressor.threshold.value = -50;
        compressor.knee.value = 40;
        compressor.ratio.value = 12;
        compressor.reduction.value = -20;
        compressor.attack.value = 0;
        compressor.release.value = 0.25;

        // Connect to output
        compressor.connect(context.destination);
        break;

      case 'oscillator':

        source.connect(oscillator);
        oscillator.type = 'sine';

        // Value in hertz
        oscillator.frequency.value = 2;
        //oscillator.start();

        // Connect to output
        oscillator.connect(context.destination);

        oscillator.start();

        break;

      /*
        The WaveShaperNode interface represents a non-linear distorter.
      */
      case 'distortion':
        // Connect the source node to the destination
        source.connect(distortion);

        // These are the default values
        distortion.oversample = 'none';
        distortion.curve = makeDistortionCurve(50);

        // Connect to output
        distortion.connect(context.destination);
        break;
    }
  }

  /*
    Distortion curves are not the easiest thing to work out, and you will
    probably need to look around to find such algorithms. We found the below
    distortion curve code on Stack Overflow.
  */
  function makeDistortionCurve(amount) {
    var k = typeof amount === 'number' ? amount : 50;
    var samples = 44100;
    var curve = new Float32Array(samples);
    var deg = Math.PI / 180;
    var x;

    for (var i = 0; i < samples; i+=1) {
      x = i * 2 / samples - 1;
      curve[i] = k * x * 60 * deg / (Math.PI + k * Math.abs(x));
    }

    return curve;
  }
});<commit_msg>Cleanup<commit_after>$(document).ready(function() {
  // Only works if the video player has the needed HTML5 class
  var player = $("video.html5-main-video")[0];

  // Nothing to do if the youtube player does not exist
  if (!player) {
    return;
  }

  var context = new AudioContext();
  var source = context.createMediaElementSource(player);
  source.connect(context.destination);

  // Set up the different audio nodes we will use for the app
  var analyser = context.createAnalyser();
  var distortion = context.createWaveShaper();
  var gainNode = context.createGain();
  var biquadFilter = context.createBiquadFilter();
  var convolver = context.createConvolver();
  var oscillator = context.createOscillator();
  var compressor = context.createDynamicsCompressor();

  $.get(chrome.extension.getURL("src/youmix.html"), function(data) {
    $('#watch-header').after(data);

    // Add the range slider
    $('input[type="range"]').rangeslider({
      polyfill: false,
      rangeClass: 'rangeslider',
      fillClass: 'rangeslider__fill',
      handleClass: 'rangeslider__handle'
    });
  });

  // Listen for changes to the presets
  $('body').on('change', "#ym-presets", function() {
    var preset = $(this).val();

    // Hide all the options
    $('.ym-node-group').hide();

    // Show the set of options matching the preset selected
    if (preset !== 'normal') {
      $("div[data-node-group='" + preset +"']").show();
    }

    // Load the filter
    presets(preset);
  });

  // Listen for changes to the options
  $('body').on('change', ".ym-node-group input[type='range'], .ym-node-group select", function() {
    var value = $(this).val();
    var node = $(this).data('node');
    var property = $(this).data('node-property');

    switch (node) {
      case 'biquadfilter':
        if (property === 'type') {
          biquadFilter.type = $(this).val()
        } else {
          biquadFilter[property].value = value;
        }

        break;

      case 'compressor':
        compressor[property].value = value;
        break;

      case 'oscillator':
        oscillator[property].value = value;
        break;

      case 'distortion':
        if (property === 'amount') {
          value = parseInt(value, 10);
          distortion.curve = makeDistortionCurve(value);
        } else if (property === 'oversample') {
          distortion.oversample = value;
        }
        break;
    }
  });

  function presets(preset) {
    source.disconnect();

    switch (preset) {
      case 'normal':
        source.connect(context.destination);
        break;

      /*
        The BiquadFilterNode interface represents a simple low-order filter.
      */
      case 'biquadfilter':
        source.connect(biquadFilter);
        biquadFilter.type = "lowpass";
        biquadFilter.frequency.value = 50;
        biquadFilter.detune.value = 100;
        biquadFilter.Q.value = 10;

        // Connect to output
        biquadFilter.connect(context.destination);
        break;

      /*
        The DynamicsCompressorNode interface provides a compression effect,
        which lowers the volume of the loudest parts of the signal in order to
        help prevent clipping and distortion that can occur when multiple sounds
        are played and multiplexed together at once.
      */
      case 'compressor':
        // Connect the source node to the destination
        source.connect(compressor);

        // These are the default values
        compressor.threshold.value = -50;
        compressor.knee.value = 40;
        compressor.ratio.value = 12;
        compressor.reduction.value = -20;
        compressor.attack.value = 0;
        compressor.release.value = 0.25;

        // Connect to output
        compressor.connect(context.destination);
        break;

      case 'oscillator':
        source.connect(oscillator);
        oscillator.type = 'sine';

        // Value in hertz
        oscillator.frequency.value = 2;
        //oscillator.start();

        // Connect to output
        oscillator.connect(context.destination);

        oscillator.start();

        break;

      /*
        The WaveShaperNode interface represents a non-linear distorter.
      */
      case 'distortion':
        // Connect the source node to the destination
        source.connect(distortion);

        // These are the default values
        distortion.oversample = 'none';
        distortion.curve = makeDistortionCurve(50);

        // Connect to output
        distortion.connect(context.destination);
        break;
    }
  }

  /*
    Distortion curves are not the easiest thing to work out, and you will
    probably need to look around to find such algorithms. We found the below
    distortion curve code on Stack Overflow.
  */
  function makeDistortionCurve(amount) {
    var k = typeof amount === 'number' ? amount : 50;
    var samples = 44100;
    var curve = new Float32Array(samples);
    var deg = Math.PI / 180;
    var x;

    for (var i = 0; i < samples; i+=1) {
      x = i * 2 / samples - 1;
      curve[i] = k * x * 60 * deg / (Math.PI + k * Math.abs(x));
    }

    return curve;
  }
});<|endoftext|>


<commit_before>import { defineMigration } from '/server/imports/utils/defineMigration';
import { dbViolationCaseActionLogs } from '/db/dbViolationCaseActionLogs';

defineMigration({
  version: 45,
  name: 'comment violation case',
  up() {
    dbViolationCaseActionLogs.rawCollection().update(
      { action: 'comment' },
      { $set: { action: 'fscComment' } },
      { multi: true }
    );
  }
});
<commit_msg>修正 Migration 沒有等待 update 完成的錯誤<commit_after>import { defineMigration } from '/server/imports/utils/defineMigration';
import { dbViolationCaseActionLogs } from '/db/dbViolationCaseActionLogs';

defineMigration({
  version: 45,
  name: 'comment violation case',
  async up() {
    await dbViolationCaseActionLogs.rawCollection().update(
      { action: 'comment' },
      { $set: { action: 'fscComment' } },
      { multi: true }
    );
  }
});
<|endoftext|>


<commit_before>(function (root, factory) {
    'use strict';
    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.

    /* istanbul ignore next */
    if (typeof define === 'function' && define.amd) {
        define('stackframe', [], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.StackFrame = factory();
    }
}(this, function () {
    'use strict';
    function _isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    function _capitalize(str) {
        return str[0].toUpperCase() + str.substring(1);
    }

    function _getter(p) {
        return function () {
            return this[p];
        };
    }

    var booleanProps = ['isConstructor', 'isEval', 'isNative', 'isToplevel'];
    var numericProps = ['columnNumber', 'lineNumber'];
    var stringProps = ['fileName', 'functionName', 'source'];
    var arrayProps = ['args'];

    var props = booleanProps.concat(numericProps.concat(stringProps.concat(arrayProps)));

    function StackFrame(obj) {
        if (obj instanceof Object) {
            for (var i = 0; i < props.length; i++) {
                if (obj.hasOwnProperty(props[i]) && obj[props[i]] !== undefined) {
                    this['set' + _capitalize(props[i])](obj[props[i]]);
                }
            }
        }
    }

    StackFrame.prototype = {
        getArgs: function () {
            return this.args;
        },
        setArgs: function (v) {
            if (Object.prototype.toString.call(v) !== '[object Array]') {
                throw new TypeError('Args must be an Array');
            }
            this.args = v;
        },

        getEvalOrigin: function () {
            return this.evalOrigin;
        },
        setEvalOrigin: function (v) {
            if (v instanceof StackFrame) {
                this.evalOrigin = v;
            } else if (v instanceof Object) {
                this.evalOrigin = new StackFrame(v);
            } else {
                throw new TypeError('Eval Origin must be an Object or StackFrame');
            }
        },

        toString: function () {
            var functionName = this.getFunctionName() || '{anonymous}';
            var args = '(' + (this.getArgs() || []).join(',') + ')';
            var fileName = this.getFileName() ? ('@' + this.getFileName()) : '';
            var lineNumber = _isNumber(this.getLineNumber()) ? (':' + this.getLineNumber()) : '';
            var columnNumber = _isNumber(this.getColumnNumber()) ? (':' + this.getColumnNumber()) : '';
            return functionName + args + fileName + lineNumber + columnNumber;
        }
    };

    for (var i = 0; i < booleanProps.length; i++) {
        StackFrame.prototype['get' + _capitalize(booleanProps[i])] = _getter(booleanProps[i]);
        StackFrame.prototype['set' + _capitalize(booleanProps[i])] = (function (p) {
            return function (v) {
                this[p] = Boolean(v);
            };
        })(booleanProps[i]);
    }

    for (var j = 0; j < numericProps.length; j++) {
        StackFrame.prototype['get' + _capitalize(numericProps[j])] = _getter(numericProps[j]);
        StackFrame.prototype['set' + _capitalize(numericProps[j])] = (function (p) {
            return function (v) {
                if (!_isNumber(v)) {
                    throw new TypeError(p + ' must be a Number');
                }
                this[p] = Number(v);
            };
        })(numericProps[j]);
    }

    for (var k = 0; k < stringProps.length; k++) {
        StackFrame.prototype['get' + _capitalize(stringProps[k])] = _getter(stringProps[k]);
        StackFrame.prototype['set' + _capitalize(stringProps[k])] = (function (p) {
            return function (v) {
                this[p] = String(v);
            };
        })(stringProps[k]);
    }

    return StackFrame;
}));
<commit_msg>Array#concat takes multiple arguments.<commit_after>(function (root, factory) {
    'use strict';
    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.

    /* istanbul ignore next */
    if (typeof define === 'function' && define.amd) {
        define('stackframe', [], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.StackFrame = factory();
    }
}(this, function () {
    'use strict';
    function _isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    function _capitalize(str) {
        return str[0].toUpperCase() + str.substring(1);
    }

    function _getter(p) {
        return function () {
            return this[p];
        };
    }

    var booleanProps = ['isConstructor', 'isEval', 'isNative', 'isToplevel'];
    var numericProps = ['columnNumber', 'lineNumber'];
    var stringProps = ['fileName', 'functionName', 'source'];
    var arrayProps = ['args'];

    var props = booleanProps.concat(numericProps, stringProps, arrayProps);

    function StackFrame(obj) {
        if (obj instanceof Object) {
            for (var i = 0; i < props.length; i++) {
                if (obj.hasOwnProperty(props[i]) && obj[props[i]] !== undefined) {
                    this['set' + _capitalize(props[i])](obj[props[i]]);
                }
            }
        }
    }

    StackFrame.prototype = {
        getArgs: function () {
            return this.args;
        },
        setArgs: function (v) {
            if (Object.prototype.toString.call(v) !== '[object Array]') {
                throw new TypeError('Args must be an Array');
            }
            this.args = v;
        },

        getEvalOrigin: function () {
            return this.evalOrigin;
        },
        setEvalOrigin: function (v) {
            if (v instanceof StackFrame) {
                this.evalOrigin = v;
            } else if (v instanceof Object) {
                this.evalOrigin = new StackFrame(v);
            } else {
                throw new TypeError('Eval Origin must be an Object or StackFrame');
            }
        },

        toString: function () {
            var functionName = this.getFunctionName() || '{anonymous}';
            var args = '(' + (this.getArgs() || []).join(',') + ')';
            var fileName = this.getFileName() ? ('@' + this.getFileName()) : '';
            var lineNumber = _isNumber(this.getLineNumber()) ? (':' + this.getLineNumber()) : '';
            var columnNumber = _isNumber(this.getColumnNumber()) ? (':' + this.getColumnNumber()) : '';
            return functionName + args + fileName + lineNumber + columnNumber;
        }
    };

    for (var i = 0; i < booleanProps.length; i++) {
        StackFrame.prototype['get' + _capitalize(booleanProps[i])] = _getter(booleanProps[i]);
        StackFrame.prototype['set' + _capitalize(booleanProps[i])] = (function (p) {
            return function (v) {
                this[p] = Boolean(v);
            };
        })(booleanProps[i]);
    }

    for (var j = 0; j < numericProps.length; j++) {
        StackFrame.prototype['get' + _capitalize(numericProps[j])] = _getter(numericProps[j]);
        StackFrame.prototype['set' + _capitalize(numericProps[j])] = (function (p) {
            return function (v) {
                if (!_isNumber(v)) {
                    throw new TypeError(p + ' must be a Number');
                }
                this[p] = Number(v);
            };
        })(numericProps[j]);
    }

    for (var k = 0; k < stringProps.length; k++) {
        StackFrame.prototype['get' + _capitalize(stringProps[k])] = _getter(stringProps[k]);
        StackFrame.prototype['set' + _capitalize(stringProps[k])] = (function (p) {
            return function (v) {
                this[p] = String(v);
            };
        })(stringProps[k]);
    }

    return StackFrame;
}));
<|endoftext|>