<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish,
		valueOf,
		reportError,
		waitTimeout;

	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
		reportError = testUtils.reportError;
	}

	this.name = 'download';
	this.tests = [
		{name: 'checkDownload'},
		{name: 'successDownloadFlowTest'},
		{name: 'successDownloadTest'},
		{name: 'failedDownloadTest'}
	];

	this.checkDownload  = function(testRun) {
		// Test for Tizen Device API: Download
		Ti.API.debug('Checking Download object availability.');

		var downloadRequest = Ti.Tizen.Download.createDownloadRequest({
			url: 'http://download.tizen.org/sdk/InstallManager/tizen-sdk-2.0-ubuntu32.bin',
			destination: 'documents',
			fileName: 'tmp' + (new Date().getTime())
		});

		valueOf(testRun, Ti.Tizen).shouldBeObject();
		valueOf(testRun, Ti.Tizen.Download).shouldBeObject();
		valueOf(testRun, downloadRequest).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadRequest.send).shouldBeFunction();
		valueOf(testRun, downloadRequest.pause).shouldBeFunction();
		valueOf(testRun, downloadRequest.abort).shouldBeFunction();
		valueOf(testRun, downloadRequest.resume).shouldBeFunction();

		finish(testRun);
	}

	this.successDownloadFlowTest = function(testRun) {
		var localTestRun = testRun,
			downloadId,
			wasResumed,
			wasPaused,
			waitTimeout = null,
			listener = {
				onDataStream: function(downloadRequest, receivedSize, totalSize) {
					Ti.API.debug('onDataStream event. id=' + downloadRequest.id + ', receivedSize=' + receivedSize + ', totalSize=' + totalSize);

					if (!wasPaused) {
						wasPaused = true;
						valueOf(testRun, downloadRequest.pause).shouldBeFunction();
						downloadRequest.pause();
					}

					if (wasResumed) {
						valueOf(testRun, downloadRequest.abort).shouldBeFunction();
						downloadRequest.abort();
					}
				},
				onPause: function(downloadRequest) {
					Ti.API.debug('onPause event. id=' + downloadRequest.id);

					clearFakeTimeout();
					waitTimeout = setTimeout(function() {
						valueOf(testRun, downloadRequest.resume).shouldBeFunction();

						downloadRequest.resume();
						wasResumed = true;
					}, 500);
				},
				onCancel: function(downloadRequest) {
					Ti.API.debug('onCancel event. id=' + downloadRequest.id);

					clearFakeTimeout();
					valueOf(localTestRun, downloadRequest.id).shouldBeGreaterThanEqual(0);
					finish(localTestRun);
				},
				onLoad: function(downloadRequest, fileName) {
					Ti.API.debug('onLoad event. id=' + downloadRequest.id +', fileName=' + fileName);

					clearFakeTimeout();
					valueOf(localTestRun, downloadRequest.id).shouldBeGreaterThanEqual(0);
					finish(localTestRun);
				},
				onError: function(downloadRequest, error) {
					Ti.API.debug('onError event. id=' + downloadRequest.id +', error=' + JSON.stringify(error));

					valueOf(localTestRun, error).shouldBe('[object TiTizenWebAPIError]');
					clearFakeTimeout();
					reportError(localTestRun, JSON.stringify(error));
				}
			};

		// Clears timeout if it was set before.
		function clearFakeTimeout(){
			// cancel fake call if any
			waitTimeout && clearTimeout(waitTimeout);
		}

		// Downloading large file to test callbacks.
		var downloadRequest = Ti.Tizen.Download.createDownloadRequest({
			url: 'http://download.tizen.org/sdk/InstallManager/tizen-sdk-2.0-ubuntu32.bin',
			destination: 'documents',
			fileName: 'tmp' + (new Date().getTime())
		});

		downloadId = downloadRequest.send(listener);

		valueOf(testRun, downloadRequest.toString()).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadId).shouldBeNumber();
		valueOf(testRun, downloadId).shouldBeGreaterThanEqual(0);
	}

	this.failedDownloadTest = function(testRun) {
		var	downloadId,
			listener = {
				onDataStream: function(downloadRequest, receivedSize, totalSize) {
					reportError(testRun, 'onDataStream may not be called in this test!');
				},
				onPause: function(downloadRequest) {
					reportError(testRun, 'onPause may not be called in this test!');
				},
				onCancel: function(downloadRequest) {
					reportError(testRun, 'onCancel may not be called in this test!');
				},
				onLoad: function(downloadRequest, fileName) {
					reportError(testRun, 'onLoad may not be called in this test!');
				},
				onError: function(downloadRequest, error) {
					Ti.API.debug('onError event. id=' + downloadRequest.id + ', error=' + JSON.stringify(error));

					valueOf(testRun, error).shouldBe('[object TiTizenWebAPIError]');
					valueOf(testRun, error).shouldNotBeNull();

					reportError(testRun, JSON.stringify(error));
					finish(testRun);
				}
			};

		// Start downloading large file to be able to test callbacks.
		var downloadRequest = Ti.Tizen.Download.createDownloadRequest({
				url: 'http://download.tizen.org/Magic-Sofware-Package-v4.2.bin',
				destination: 'documents',
				fileName: 'tmp' + (new Date().getTime())
			});

		downloadId = downloadRequest.send(listener);

		valueOf(testRun, downloadRequest.toString()).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadId).shouldBeGreaterThanEqual(0);
	}

	this.successDownloadTest = function(testRun) {
		var	downloadId,
			listener = {
				onDataStream: function(downloadRequest, receivedSize, totalSize) {
					Ti.API.debug('onDataStream event. id=' + downloadRequest.id + ', receivedSize=' + receivedSize + ', totalSize=' + totalSize);

					valueOf(testRun, downloadRequest.id).shouldBeGreaterThanEqual(0);
					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);
					valueOf(testRun, totalSize).shouldBeGreaterThanEqual(0);
				},
				onPause: function(downloadRequest) {
					Ti.API.debug('onPause event. id=' + downloadRequest.id);

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);

					finish(testRun);
				},
				onCancel: function(downloadRequest) {
					Ti.API.debug('onCancel event. id=' + downloadRequest.id);

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);

					finish(testRun);
				},
				onLoad: function(downloadRequest, fileName) {
					Ti.API.debug('onLoad event. id=' + downloadRequest.id + ', fileName=' + fileName);

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);
					valueOf(testRun, downloadRequest.id).shouldBeGreaterThanEqual(0);

					finish(testRun);
				},
				onError: function(downloadRequest, error) {
					Ti.API.debug('onError event. id=' + downloadRequest.id + ', error=' + JSON.stringify(error));

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);
					valueOf(testRun, error).shouldBe('[object TiTizenWebAPIError]');

					reportError(testRun, JSON.stringify(error));
				}
			},

		// Start downloading large file to initate callbacks.
		downloadRequest = Ti.Tizen.Download.createDownloadRequest({
			url: 'http://download.tizen.org/sdk/1_0-larkspur/pkg_list_windows',
			destination: 'documents',
			fileName: 'tmp' + (new Date().getTime())
		});

		downloadId = downloadRequest.send(listener);

		valueOf(testRun, downloadRequest.toString()).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadId).shouldBeGreaterThanEqual(0);
		valueOf(testRun, downloadId).shouldBeNumber();
	}
}<commit_msg>Anvil. Modify download suite to use setListener function.<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish,
		valueOf,
		reportError,
		waitTimeout;

	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
		reportError = testUtils.reportError;
	}

	this.name = 'download';
	this.tests = [
		{name: 'checkDownload'},
		{name: 'successDownloadFlowTest'},
		{name: 'successDownloadTest'},
		{name: 'failedDownloadTest'}
	];

	this.checkDownload  = function(testRun) {
		// Test for Tizen Device API: Download
		Ti.API.debug('Checking Download object availability.');

		var downloadRequest = Ti.Tizen.Download.createDownloadRequest({
			url: 'http://download.tizen.org/sdk/InstallManager/tizen-sdk-2.0-ubuntu32.bin',
			destination: 'documents',
			fileName: 'tmp' + (new Date().getTime())
		});

		valueOf(testRun, Ti.Tizen).shouldBeObject();
		valueOf(testRun, Ti.Tizen.Download).shouldBeObject();
		valueOf(testRun, downloadRequest).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadRequest.send).shouldBeFunction();
		valueOf(testRun, downloadRequest.pause).shouldBeFunction();
		valueOf(testRun, downloadRequest.abort).shouldBeFunction();
		valueOf(testRun, downloadRequest.resume).shouldBeFunction();

		finish(testRun);
	}

	this.successDownloadFlowTest = function(testRun) {
		var localTestRun = testRun,
			downloadId,
			wasResumed,
			wasPaused,
			waitTimeout = null,
			listener = {
				onDataStream: function(downloadRequest, receivedSize, totalSize) {
					Ti.API.debug('onDataStream event. id=' + downloadRequest.id + ', receivedSize=' + receivedSize + ', totalSize=' + totalSize);

					if (!wasPaused) {
						wasPaused = true;
						valueOf(testRun, downloadRequest.pause).shouldBeFunction();
						downloadRequest.pause();
					}

					if (wasResumed) {
						valueOf(testRun, downloadRequest.abort).shouldBeFunction();
						downloadRequest.abort();
					}
				},
				onPause: function(downloadRequest) {
					Ti.API.debug('onPause event. id=' + downloadRequest.id);

					clearFakeTimeout();
					waitTimeout = setTimeout(function() {
						valueOf(testRun, downloadRequest.resume).shouldBeFunction();

						downloadRequest.resume();
						wasResumed = true;
					}, 500);
				},
				onCancel: function(downloadRequest) {
					Ti.API.debug('onCancel event. id=' + downloadRequest.id);

					clearFakeTimeout();
					valueOf(localTestRun, downloadRequest.id).shouldBeGreaterThanEqual(0);
					finish(localTestRun);
				},
				onLoad: function(downloadRequest, fileName) {
					Ti.API.debug('onLoad event. id=' + downloadRequest.id +', fileName=' + fileName);

					clearFakeTimeout();
					valueOf(localTestRun, downloadRequest.id).shouldBeGreaterThanEqual(0);
					finish(localTestRun);
				},
				onError: function(downloadRequest, error) {
					Ti.API.debug('onError event. id=' + downloadRequest.id +', error=' + JSON.stringify(error));

					valueOf(localTestRun, error).shouldBe('[object TiTizenWebAPIError]');
					clearFakeTimeout();
					reportError(localTestRun, JSON.stringify(error));
				}
			};

		// Clears timeout if it was set before.
		function clearFakeTimeout(){
			// cancel fake call if any
			waitTimeout && clearTimeout(waitTimeout);
		}

		// Downloading large file to test callbacks.
		var downloadRequest = Ti.Tizen.Download.createDownloadRequest({
			url: 'http://download.tizen.org/sdk/InstallManager/tizen-sdk-2.0-ubuntu32.bin',
			destination: 'documents',
			fileName: 'tmp' + (new Date().getTime())
		});

		downloadId = downloadRequest.send(listener);

		valueOf(testRun, downloadRequest.toString()).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadId).shouldBeNumber();
		valueOf(testRun, downloadId).shouldBeGreaterThanEqual(0);
	}

	this.failedDownloadTest = function(testRun) {
		var	downloadId,
			listener = {
				onDataStream: function(downloadRequest, receivedSize, totalSize) {
					reportError(testRun, 'onDataStream may not be called in this test!');
				},
				onPause: function(downloadRequest) {
					reportError(testRun, 'onPause may not be called in this test!');
				},
				onCancel: function(downloadRequest) {
					reportError(testRun, 'onCancel may not be called in this test!');
				},
				onLoad: function(downloadRequest, fileName) {
					reportError(testRun, 'onLoad may not be called in this test!');
				},
				onError: function(downloadRequest, error) {
					Ti.API.debug('onError event. id=' + downloadRequest.id + ', error=' + JSON.stringify(error));

					valueOf(testRun, error).shouldBe('[object TiTizenWebAPIError]');
					valueOf(testRun, error).shouldNotBeNull();

					reportError(testRun, JSON.stringify(error));
					finish(testRun);
				}
			};

		// Start downloading large file to be able to test callbacks.
		var downloadRequest = Ti.Tizen.Download.createDownloadRequest({
				url: 'http://download.tizen.org/Magic-Sofware-Package-v4.2.bin',
				destination: 'documents',
				fileName: 'tmp' + (new Date().getTime())
			});

		downloadId = downloadRequest.send(listener);

		valueOf(testRun, downloadRequest.toString()).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadId).shouldBeGreaterThanEqual(0);
	}

	this.successDownloadTest = function(testRun) {
		var	downloadId,
			listener = {
				onDataStream: function(downloadRequest, receivedSize, totalSize) {
					Ti.API.debug('onDataStream event. id=' + downloadRequest.id + ', receivedSize=' + receivedSize + ', totalSize=' + totalSize);

					valueOf(testRun, downloadRequest.id).shouldBeGreaterThanEqual(0);
					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);
					valueOf(testRun, totalSize).shouldBeGreaterThanEqual(0);
				},
				onPause: function(downloadRequest) {
					Ti.API.debug('onPause event. id=' + downloadRequest.id);

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);

					finish(testRun);
				},
				onCancel: function(downloadRequest) {
					Ti.API.debug('onCancel event. id=' + downloadRequest.id);

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);

					finish(testRun);
				},
				onLoad: function(downloadRequest, fileName) {
					Ti.API.debug('onLoad event. id=' + downloadRequest.id + ', fileName=' + fileName);

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);
					valueOf(testRun, downloadRequest.id).shouldBeGreaterThanEqual(0);

					finish(testRun);
				},
				onError: function(downloadRequest, error) {
					Ti.API.debug('onError event. id=' + downloadRequest.id + ', error=' + JSON.stringify(error));

					valueOf(testRun, downloadRequest.id).shouldBeEqual(downloadId);
					valueOf(testRun, error).shouldBe('[object TiTizenWebAPIError]');

					reportError(testRun, JSON.stringify(error));
				}
			},

		// Start downloading large file to initate callbacks.
		downloadRequest = Ti.Tizen.Download.createDownloadRequest({
			url: 'http://download.tizen.org/sdk/1_0-larkspur/pkg_list_windows',
			destination: 'documents',
			fileName: 'tmp' + (new Date().getTime())
		});

		downloadId = downloadRequest.send();
		downloadRequest.setListener(listener);

		valueOf(testRun, downloadRequest.toString()).shouldBe('[object TiTizenDownloadDownloadRequest]');
		valueOf(testRun, downloadId).shouldBeGreaterThanEqual(0);
		valueOf(testRun, downloadId).shouldBeNumber();
	}
}<|endoftext|>


<commit_before>const SAMPLE_BUFFER_SIZE = 1024;

export default class Sample {
	constructor (context) {

		this.context = context;
		this.buffer = this.context.createBuffer(2, 1, this.context.sampleRate);
		this.rawBuffer = new Float32Array(this.buffer.length);
		this.buffer.copyFromChannel(this.rawBuffer, 1,0);
		this.stream = null;
		this._recordProcessor = null;
		this.overdub = false;
	}

	load (path) {
		return fetch(path)
			.then((response) => response.arrayBuffer())
			.then((myBlob) => {
				return this.context.decodeAudioData(myBlob);
			})
			.then((buffer) => {
				this.rawBuffer = new Float32Array(this.buffer.length);
				this.rawBuffer = buffer.getChannelData(0);
				this.buffer = this.context.createBuffer(2, this.rawBuffer.length, this.context.sampleRate);
				this.buffer.copyToChannel(this.rawBuffer, 0);
				this.buffer.copyToChannel(this.rawBuffer, 1);
				return this;
			})
	}

	reverse () {
		let reverse = new Float32Array(this.rawBuffer);
			reverse.reverse();
		this.buffer = this.context.createBuffer(2, reverse.length, this.context.sampleRate);
		this.buffer.copyToChannel(reverse, 0);
		this.buffer.copyToChannel(reverse, 1);
	}

	pingpong () {
		let offset = this.rawBuffer.length;
		let newArray = new Float32Array(offset * 2);
		let reverse = new Float32Array(this.rawBuffer);
		reverse.reverse();
		newArray.set(this.rawBuffer, 0);
		newArray.set(reverse, offset-1);
		this.buffer = this.context.createBuffer(2, newArray.length, this.context.sampleRate);
		this.buffer.copyToChannel(newArray, 0);
		this.buffer.copyToChannel(newArray, 1);
	}

	normal () {
		this.buffer = this.context.createBuffer(2, this.rawBuffer.length, this.context.sampleRate);
		this.buffer.copyToChannel(this.rawBuffer, 0);
		this.buffer.copyToChannel(this.rawBuffer, 1);
	}

	record () {
		this.buffered = 0;
		this.stream = new Float32Array(0);
		navigator.mediaDevices.getUserMedia({audio: true, video: false})
			.then((stream) => {
				let input = this.context.createMediaStreamSource(stream);
				this._recordProcessor = this.context.createScriptProcessor(SAMPLE_BUFFER_SIZE, 1, 2);

				input.connect(this._recordProcessor);
				this._recordProcessor.connect(this.context.destination);
				this._recordProcessor.onaudioprocess = (e) => {
					let chunk = e.inputBuffer.getChannelData(0);
					var newStream = new Float32Array(this.stream.length + chunk.length);
						newStream.set(this.stream);
						newStream.set(chunk,chunk.length * this.buffered);
						this.stream = newStream;
					this.buffered++;
				};
			})
	}

	stopRecording() {
		this._recordProcessor.disconnect();
		this.rawBuffer = new Float32Array(this.stream.length);
		this.rawBuffer = this.ramp(this.stream);
		this.buffer = this.context.createBuffer(2, this.stream.length, this.context.sampleRate);
		this.buffer.copyToChannel(this.rawBuffer, 0);
		this.buffer.copyToChannel(this.rawBuffer, 1);
	}

	ramp(buffer) {
		let newBuffer = buffer;
		const BUFFER_SIZE = 512;
		if(newBuffer.length > BUFFER_SIZE) {
			for(var i = 0; i < BUFFER_SIZE; i++) {
				newBuffer[i] = newBuffer[i] * i / BUFFER_SIZE;
			}
			var j = BUFFER_SIZE;
			for(var i = newBuffer.length-BUFFER_SIZE; i < newBuffer.length; i++) {
				j--;
				newBuffer[i] = newBuffer[i] * j / BUFFER_SIZE;
			}
		}
		return newBuffer;
	}

	overwrite () {
		this._recordProcessor.disconnect();
		var bufferlength = 0;
		if (this.stream.length > this.buffer.length) {
			bufferlength = this.stream.length;
		} else {
			bufferlength = this.buffer.length;
		}
		let mixedBuffer = new Float32Array(bufferlength);
		let bufferA = this.stream;
		let bufferB = new Float32Array( this.buffer.length);
		this.buffer.copyFromChannel(bufferB, 1, 0);
		for(let i = 0; i < bufferlength; i++) {
			let aValue = 0;
			let bValue = 0;
			if(bufferA[i] != undefined) {
				aValue = bufferA[i];
			}
			if(bufferB[i] != undefined) {
				bValue = bufferB[i];
			}
			mixedBuffer[i] = aValue + bValue;
		}
		this.rawBuffer = this.ramp(mixedBuffer);
		this.buffer = this.context.createBuffer(2, bufferlength, this.context.sampleRate);
		this.buffer.copyToChannel(this.rawBuffer, 0);
		this.buffer.copyToChannel(this.rawBuffer, 1);
		this.overdub = false;
	}
}<commit_msg>Added external stream recording<commit_after>const SAMPLE_BUFFER_SIZE = 1024;

export const RECORD_MODE = {
	USER_MEDIA: "USER_MEDIA",
	STREAN: "STREAM"
}

export default class Sample {
	constructor (context, recordMode = RECORD_MODE.USER_MEDIA) {
		this.RECORD_MODE = recordMode
		this.recordInput = context.createMediaStreamDestination();
		this.context = context;
		this.buffer = this.context.createBuffer(2, 1, this.context.sampleRate);
		this.rawBuffer = new Float32Array(this.buffer.length);
		this.buffer.copyFromChannel(this.rawBuffer, 1,0);
		this.stream = null;
		this._recordProcessor = null;
		this.overdub = false;
	}

	load (path) {
		return fetch(path)
			.then((response) => response.arrayBuffer())
			.then((myBlob) => {
				return this.context.decodeAudioData(myBlob);
			})
			.then((buffer) => {
				this.rawBuffer = new Float32Array(this.buffer.length);
				this.rawBuffer = buffer.getChannelData(0);
				this.buffer = this.context.createBuffer(2, this.rawBuffer.length, this.context.sampleRate);
				this.buffer.copyToChannel(this.rawBuffer, 0);
				this.buffer.copyToChannel(this.rawBuffer, 1);
				return this;
			})
	}

	reverse () {
		let reverse = new Float32Array(this.rawBuffer);
			reverse.reverse();
		this.buffer = this.context.createBuffer(2, reverse.length, this.context.sampleRate);
		this.buffer.copyToChannel(reverse, 0);
		this.buffer.copyToChannel(reverse, 1);
	}

	pingpong () {
		let offset = this.rawBuffer.length;
		let newArray = new Float32Array(offset * 2);
		let reverse = new Float32Array(this.rawBuffer);
		reverse.reverse();
		newArray.set(this.rawBuffer, 0);
		newArray.set(reverse, offset-1);
		this.buffer = this.context.createBuffer(2, newArray.length, this.context.sampleRate);
		this.buffer.copyToChannel(newArray, 0);
		this.buffer.copyToChannel(newArray, 1);
	}

	normal () {
		this.buffer = this.context.createBuffer(2, this.rawBuffer.length, this.context.sampleRate);
		this.buffer.copyToChannel(this.rawBuffer, 0);
		this.buffer.copyToChannel(this.rawBuffer, 1);
	}

	record() {
		switch(this.recordMode) {
			case RECORD_MODE.STREAM:
				this.recordStream(this.input.stream);
			break;
			case RECORD_MODE.USER_MEDIA:
				navigator.mediaDevices.getUserMedia({audio: true, video: false})
				.then((stream) =>this.recordStream(stream))
			break;
		}
	}

	recordStream(stream) {

			this.buffered = 0;
			this.stream = new Float32Array(0);

			let input = this.context.createMediaStreamSource(stream);
			this._recordProcessor = this.context.createScriptProcessor(SAMPLE_BUFFER_SIZE, 1, 2);

			input.connect(this._recordProcessor);
			this._recordProcessor.connect(this.context.destination);
			this._recordProcessor.onaudioprocess = (e) => {
				let chunk = e.inputBuffer.getChannelData(0);
				var newStream = new Float32Array(this.stream.length + chunk.length);
					newStream.set(this.stream);
					newStream.set(chunk,chunk.length * this.buffered);
					this.stream = newStream;
				this.buffered++;
			};
	}

	stopRecording() {
		this._recordProcessor.disconnect();
		this.rawBuffer = new Float32Array(this.stream.length);
		this.rawBuffer = this.ramp(this.stream);
		this.buffer = this.context.createBuffer(2, this.stream.length, this.context.sampleRate);
		this.buffer.copyToChannel(this.rawBuffer, 0);
		this.buffer.copyToChannel(this.rawBuffer, 1);
	}

	ramp(buffer) {
		let newBuffer = buffer;
		const BUFFER_SIZE = 512;
		if(newBuffer.length > BUFFER_SIZE) {
			for(var i = 0; i < BUFFER_SIZE; i++) {
				newBuffer[i] = newBuffer[i] * i / BUFFER_SIZE;
			}
			var j = BUFFER_SIZE;
			for(var i = newBuffer.length-BUFFER_SIZE; i < newBuffer.length; i++) {
				j--;
				newBuffer[i] = newBuffer[i] * j / BUFFER_SIZE;
			}
		}
		return newBuffer;
	}

	overwrite () {
		this._recordProcessor.disconnect();
		var bufferlength = 0;
		if (this.stream.length > this.buffer.length) {
			bufferlength = this.stream.length;
		} else {
			bufferlength = this.buffer.length;
		}
		let mixedBuffer = new Float32Array(bufferlength);
		let bufferA = this.stream;
		let bufferB = new Float32Array( this.buffer.length);
		this.buffer.copyFromChannel(bufferB, 1, 0);
		for(let i = 0; i < bufferlength; i++) {
			let aValue = 0;
			let bValue = 0;
			if(bufferA[i] != undefined) {
				aValue = bufferA[i];
			}
			if(bufferB[i] != undefined) {
				bValue = bufferB[i];
			}
			mixedBuffer[i] = aValue + bValue;
		}
		this.rawBuffer = this.ramp(mixedBuffer);
		this.buffer = this.context.createBuffer(2, bufferlength, this.context.sampleRate);
		this.buffer.copyToChannel(this.rawBuffer, 0);
		this.buffer.copyToChannel(this.rawBuffer, 1);
		this.overdub = false;
	}
}<|endoftext|>


<commit_before>/**
 * This file has been autogenerated using the command:
 *
 *    yarn run swizzle @docusaurus/theme-classic prism-include-languages
 *
 * See docs for more info: https://v2.docusaurus.io/docs/markdown-features#syntax-highlighting
 *
 * We need this to add a custom code block type for rasa training data. Please do not
 * modify this file except between the '// start|end of custom code blocks' comments.
 */
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
import siteConfig from '@generated/docusaurus.config';

const prismIncludeLanguages = (PrismObject) => {
  if (ExecutionEnvironment.canUseDOM) {
    const {
      themeConfig: {prism: {additionalLanguages = []} = {}},
    } = siteConfig;
    window.Prism = PrismObject;

    additionalLanguages.forEach((lang) => {
      require(`prismjs/components/prism-${lang}`); // eslint-disable-line
    });

    // start of custom code blocks
    PrismObject.languages['yaml-rasa'] = PrismObject.languages['yml-rasa'] = PrismObject.languages.yaml;
    // end of custom code blocks

    delete window.Prism;
  }
};

export default prismIncludeLanguages;
<commit_msg>remove prism-include-languages file<commit_after><|endoftext|>


<commit_before>function yui_autocomplete(name, ac_url, force_selection) {

    this.name = name;
    this.ac_url = ac_url;
    this.force_selection = force_selection;

    this.setup = function () {
        var datasource = new YAHOO.util.XHRDataSource(ac_url);
        datasource.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
        datasource.responseSchema = {
            resultsList: "result",
            fields: ["label", "id"]
        };

        datasource.doBeforeParseData = function (request, original, callback) {
            var parsed = {"result": []};
            for (var i in original)
                parsed.result.push({"id": original[i][0], "label": original[i][1]});
            return parsed;
        };
        datasource.resultTypeList = false;

        var input = document.getElementById("id_"+name);
        var container = document.createElement("div");
        YAHOO.util.Dom.insertAfter(container, input);
        if (!YAHOO.util.Dom.hasClass(document.body, "yui-skin-sam"))
            YAHOO.util.Dom.addClass(document.body, "yui-skin-sam");

        var autocomplete = new YAHOO.widget.AutoComplete(input, container, datasource);
        autocomplete.resultTypeList = false;
        autocomplete.queryDelay = .5;
        autocomplete.forceSelection = force_selection;
        autocomplete.generateRequest = function(sQuery) {
            return "?q="+sQuery;
        };

        var selected_item = {label: null, id: null};
        var hidden = document.getElementById("id_hidden_"+name);
        autocomplete.itemSelectEvent.subscribe(function (type, args) {
            selected_item = args[2];
            hidden.value = selected_item.id;
        });
        form = document.getElementsByTagName("form")[0];
        YAHOO.util.Event.addListener(form, "submit", function (event, form) {
            if (selected_item.label != input.value && !force_selection)
                hidden.value = input.value;
        });
        this.datasource = datasource;
        this.autocomplete = autocomplete;
    };
    YAHOO.util.Event.onDOMReady(this.setup, null, this);
};

autocomplete = yui_autocomplete;
<commit_msg>Added support for "unselecting" in yui_autocomplete.js.<commit_after>function yui_autocomplete(name, ac_url, force_selection) {

    this.name = name;
    this.ac_url = ac_url;
    this.force_selection = force_selection;

    this.setup = function () {
        var datasource = new YAHOO.util.XHRDataSource(ac_url);
        datasource.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
        datasource.responseSchema = {
            resultsList: "result",
            fields: ["label", "id"]
        };

        datasource.doBeforeParseData = function (request, original, callback) {
            var parsed = {"result": []};
            for (var i in original)
                parsed.result.push({"id": original[i][0], "label": original[i][1]});
            return parsed;
        };
        datasource.resultTypeList = false;

        var input = document.getElementById("id_"+name);
        var container = document.createElement("div");
        YAHOO.util.Dom.insertAfter(container, input);
        if (!YAHOO.util.Dom.hasClass(document.body, "yui-skin-sam"))
            YAHOO.util.Dom.addClass(document.body, "yui-skin-sam");

        var autocomplete = new YAHOO.widget.AutoComplete(input, container, datasource);
        autocomplete.resultTypeList = false;
        autocomplete.queryDelay = .5;
        autocomplete.forceSelection = force_selection;
        autocomplete.generateRequest = function(sQuery) {
            return "?q="+sQuery;
        };

        var hidden = document.getElementById("id_hidden_"+name);
        this.selected_item = {label: input.value, id: hidden.value};
        autocomplete.itemSelectEvent.subscribe(function (type, args) {
            this.selected_item = args[2];
            hidden.value = this.selected_item.id;
        });
        form = document.getElementsByTagName("form")[0];
        YAHOO.util.Event.addListener(form, "submit", function (event, form) {
            if ((!input.value) || (this.selected_item.label != input.value && !force_selection))
                hidden.value = input.value;
        });
        this.datasource = datasource;
        this.autocomplete = autocomplete;
    };
    YAHOO.util.Event.onDOMReady(this.setup, null, this);
};

autocomplete = yui_autocomplete;
<|endoftext|>


<commit_before>EditableListItem = ListItem.extend({
	_types: 'list',

	getEditForm: function(object, id, width, force) {
		var form = EditForm.get(object, force);
		// TODO: Since we're using cached forms, this means we cannot use
		// the same form elsewhere at the same time.
		if (id == null)
			id = object._id;
		form.entryId = id;
		// Let edit param know about edit_entry_id to be sent back
		// from client side to identify editable list entry form items.
		form.listEntryId = object.getFullId();
		// Only shrink if it does not fit. It might be the user has already
		// taken care of it.
		if (form.getWidth() >= width)
			form.setWidth(this.form.getInnerWidth(width, this.padding));
		// Update the edit form's variablePrefix to group by this
		// edit item.
		form.variablePrefix = this.getEditName() + '_' + id + '_';
		return form;
	},

	getAddPrototypeButton: function(baseForm, name, param) {
		if (!this.chooser) {
			// In order to avoid endless recursion, we are first setting
			// the chooser object to the valid name.
			// Since getPrototypeChooserList calls getAddPrototypeButton through
			// renderEntry again, this would lead to an endless recursion otherwise.
			this.chooser = { name: name + '_chooser' };
			this.chooser.list = this.getPrototypeChooserList(baseForm, function(ctor) {
				// Create an empty instance in order to render small edit form:
				// TODO: Cache created instances and produced html somehow?
				// Can we use bootstrap's internal version number?
				// Should this be exposed through a method on Function even?
				// Or simpy caching within 'this'...
				var html = this.renderEntry(baseForm, name, new ctor(this), {
					add: param.add, width: param.width,
					id: '{%' + name + '_id%}'
				});
				return baseForm.renderHandle('list_add', name, html,
					'{%' + name + '_entry_id%}');
			});
			/*
			var t = Date().now();
			User.log(Date().now() - t);
			*/
		}
		return this.getPrototypeChooserButton(baseForm, {
			name: name + (param.entryId ? '_' + param.entryId : ''),
			value: param.value
		}, this.chooser);
	},

	renderEntry: function(baseForm, name, object, param, out) {
		// Force a newly created form each time we're rendering
		var form = this.getEditForm(object, param.id, param.width, true);
		return baseForm.renderTemplate('listItem#entry', {
			id: name + '_' + form.entryId,
			name: name,
			proto: object._prototype,
			hide: this.visibility
					// Default for new items is visible in editable lists.
					? object.visible == null || object.visible ? 0 : 1
					: null,
			width: param.width,
			create: object.isTransient(),
			sortable: this.sortable,
			items: form.renderItems(baseForm, {
				itemsOnly: true
			}),
			addHandler: this.addEntries && this.getAddPrototypeButton(baseForm, name, {
				width: param.width,
				entryId: form.entryId
			}).onClick
		}, out);
	},

	render: function(baseForm, name, value, param, out) {
		var width = param.calculatedWidth;
		var buttonWidth = 16;
		if (this.addEntries)
			width -= buttonWidth;
		if (this.sortable)
			width -= buttonWidth;
		if (this.hideable || true)
			width -= buttonWidth;
		// Add the button only once to the form!
		// TODO: Rename addButton to better name?
		if (this.addButton && !this.initialized) {
			var button = this.getAddPrototypeButton(baseForm, name, {
				width: width,
				value: this.addButton
			});
			baseForm.addButtons(button);
			this.initialized = true;
		}
		var entries = [];
		var ids = [];
		var list = this.collection.list();
		for (var i = 0; i < list.length; i++) {
			var obj = list[i];
			entries.push(this.renderEntry(baseForm, name, obj, {
				width: width
			}));
			ids.push(obj._id);
		}
		baseForm.renderTemplate('listItem#list', {
			name: name,
			addEntries: this.addEntries,
			addHandler: this.addEntries && this.getAddPrototypeButton(baseForm, name, {
				width: param.calculatedWidth
			}).onClick,
			chooser: this.chooser, // needs to come after getAddPrototypeButton!
			entries: entries.join(''),
			ids: ids
		}, out);
	},

	convert: function(value) {
		// Make sure apply gets called
		return value;
	},

	apply: function(value) {
		var changed = false;
		var name = this.getEditName();
		// Scan through all values and group by id
		var create = {};
		var applied = {};
		// Link ids to entries, also for newly created ones (n*)
		var entries = {};
		for (var key in req.data) {
			if (key.startsWith(name)) {
				var rest = key.substring(name.length + 1);
				var pos = rest.indexOf('_');
				var id = rest.substring(0, pos);
				if (/^n/.test(id)) { // Create
					User.log('Create', id);
					// Group values and process later.
					// This is needed by the onCreate handler that
					// can produce an object based on e.g. file type
					var variable = rest.substring(pos + 1);
					var values = create[id];
					if (!values)
						values = create[id] = {};
					values[variable] = req.data[key];
				} else if (!applied[id]) { // Apply
					// Mark this object as applied once one field was found,
					// since form handles the rest.
					applied[id] = true;
					// Just pass this through the form. No further
					// grouping is needed.
					var obj = this.collection.getById(id);
					if (obj) {
						var prefix = name + '_' + id + '_';
						if (req.data[prefix + 'remove'] == 1) {
							changed = obj.remove();
						} else {
							var form = this.getEditForm(obj);
							if (form)
								changed = form.applyItems() || changed;
							// Set the object's visibility and position
							var visible = Base.pick(req.data[prefix + 'hide'], 0) == 0;
							entries[id] = { object: obj, visible: visible };
						}
					}
				}
			}
		}
		// Now produce the new items
		// Determine prototype in case onCreate does not produce the item.
		var prototypes = this.getPrototypes();
		var ctor = prototypes[0];
		for (var id in create) {
			var values = create[id];
			if (values.remove != 1) {
				// Pass prototype value extra, as ctor
				var proto = values.proto;
				delete values.proto;
				var ctor = global[proto];
				if (!prototypes.contains(ctor))
					throw 'Unsupported prototype: ' + proto;
				// Support an onCreate handler that can produce special types
				// e.g. based on the file type. That's also the only reason
				// why we collect all values above, so that onCreate can analyse them.
				var obj = this.onCreate && this.onCreate(proto, values);
				if (!obj)
					obj = new ctor(this); // Pass the edit item for editing parent stuff.
				if (obj) {
					// Just like in the rest of edit lib, apply first, persist after
					var form = this.getEditForm(obj, id);
					if (form) {
						form.applyItems();
						changed = this.store(obj) || changed;
						entries[id] = { object: obj, visible: true };
					}
				}
			}
		}
		// Now set positions. It is important that this happens in proper sequence,
		// in case we're modifying memory-only HopObjects through addAt...
		(value || '').split(',').each(function(id, index) {
			var entry = entries[id];
			if (entry)
				changed = this.setPosition(entry.object, index, entry.visible) || changed;
		}, this);
		return changed;
	}
});
<commit_msg>Fixed a bug with calculation of EditableListItem width.<commit_after>EditableListItem = ListItem.extend({
	_types: 'list',

	getEditForm: function(object, id, width, force) {
		var form = EditForm.get(object, force);
		// TODO: Since we're using cached forms, this means we cannot use
		// the same form elsewhere at the same time.
		if (id == null)
			id = object._id;
		form.entryId = id;
		// Let edit param know about edit_entry_id to be sent back
		// from client side to identify editable list entry form items.
		form.listEntryId = object.getFullId();
		// Only shrink if it does not fit. It might be the user has already
		// taken care of it.
		if (form.getWidth() >= width)
			form.setWidth(this.form.getInnerWidth(width, this.padding));
		// Update the edit form's variablePrefix to group by this
		// edit item.
		form.variablePrefix = this.getEditName() + '_' + id + '_';
		return form;
	},

	getAddPrototypeButton: function(baseForm, name, param) {
		if (!this.chooser) {
			// In order to avoid endless recursion, we are first setting
			// the chooser object to the valid name.
			// Since getPrototypeChooserList calls getAddPrototypeButton through
			// renderEntry again, this would lead to an endless recursion otherwise.
			this.chooser = { name: name + '_chooser' };
			this.chooser.list = this.getPrototypeChooserList(baseForm, function(ctor) {
				// Create an empty instance in order to render small edit form:
				// TODO: Cache created instances and produced html somehow?
				// Can we use bootstrap's internal version number?
				// Should this be exposed through a method on Function even?
				// Or simpy caching within 'this'...
				var html = this.renderEntry(baseForm, name, new ctor(this), {
					add: param.add, width: param.width,
					id: '{%' + name + '_id%}'
				});
				return baseForm.renderHandle('list_add', name, html,
					'{%' + name + '_entry_id%}');
			});
			/*
			var t = Date().now();
			User.log(Date().now() - t);
			*/
		}
		return this.getPrototypeChooserButton(baseForm, {
			name: name + (param.entryId ? '_' + param.entryId : ''),
			value: param.value
		}, this.chooser);
	},

	renderEntry: function(baseForm, name, object, param, out) {
		// Force a newly created form each time we're rendering
		var form = this.getEditForm(object, param.id, param.width, true);
		return baseForm.renderTemplate('listItem#entry', {
			id: name + '_' + form.entryId,
			name: name,
			proto: object._prototype,
			hide: this.visibility
					// Default for new items is visible in editable lists.
					? object.visible == null || object.visible ? 0 : 1
					: null,
			width: param.width,
			create: object.isTransient(),
			sortable: this.sortable,
			items: form.renderItems(baseForm, {
				itemsOnly: true
			}),
			addHandler: this.addEntries && this.getAddPrototypeButton(baseForm, name, {
				width: param.width,
				entryId: form.entryId
			}).onClick
		}, out);
	},

	render: function(baseForm, name, value, param, out) {
		var width = param.calculatedWidth;
		var buttonWidth = 16;
		if (this.addEntries)
			width -= buttonWidth;
		if (this.sortable)
			width -= buttonWidth;
		if (this.hideable || true)
			width -= buttonWidth;
		// Add the button only once to the form!
		// TODO: Rename addButton to better name?
		if (this.addButton && !this.initialized) {
			var button = this.getAddPrototypeButton(baseForm, name, {
				width: width,
				value: this.addButton
			});
			baseForm.addButtons(button);
			this.initialized = true;
		}
		var entries = [];
		var ids = [];
		var list = this.collection.list();
		for (var i = 0; i < list.length; i++) {
			var obj = list[i];
			entries.push(this.renderEntry(baseForm, name, obj, {
				width: width
			}));
			ids.push(obj._id);
		}
		baseForm.renderTemplate('listItem#list', {
			name: name,
			addEntries: this.addEntries,
			addHandler: this.addEntries && this.getAddPrototypeButton(baseForm, name, {
				width: width
			}).onClick,
			chooser: this.chooser, // needs to come after getAddPrototypeButton!
			entries: entries.join(''),
			ids: ids
		}, out);
	},

	convert: function(value) {
		// Make sure apply gets called
		return value;
	},

	apply: function(value) {
		var changed = false;
		var name = this.getEditName();
		// Scan through all values and group by id
		var create = {};
		var applied = {};
		// Link ids to entries, also for newly created ones (n*)
		var entries = {};
		for (var key in req.data) {
			if (key.startsWith(name)) {
				var rest = key.substring(name.length + 1);
				var pos = rest.indexOf('_');
				var id = rest.substring(0, pos);
				if (/^n/.test(id)) { // Create
					User.log('Create', id);
					// Group values and process later.
					// This is needed by the onCreate handler that
					// can produce an object based on e.g. file type
					var variable = rest.substring(pos + 1);
					var values = create[id];
					if (!values)
						values = create[id] = {};
					values[variable] = req.data[key];
				} else if (!applied[id]) { // Apply
					// Mark this object as applied once one field was found,
					// since form handles the rest.
					applied[id] = true;
					// Just pass this through the form. No further
					// grouping is needed.
					var obj = this.collection.getById(id);
					if (obj) {
						var prefix = name + '_' + id + '_';
						if (req.data[prefix + 'remove'] == 1) {
							changed = obj.remove();
						} else {
							var form = this.getEditForm(obj);
							if (form)
								changed = form.applyItems() || changed;
							// Set the object's visibility and position
							var visible = Base.pick(req.data[prefix + 'hide'], 0) == 0;
							entries[id] = { object: obj, visible: visible };
						}
					}
				}
			}
		}
		// Now produce the new items
		// Determine prototype in case onCreate does not produce the item.
		var prototypes = this.getPrototypes();
		var ctor = prototypes[0];
		for (var id in create) {
			var values = create[id];
			if (values.remove != 1) {
				// Pass prototype value extra, as ctor
				var proto = values.proto;
				delete values.proto;
				var ctor = global[proto];
				if (!prototypes.contains(ctor))
					throw 'Unsupported prototype: ' + proto;
				// Support an onCreate handler that can produce special types
				// e.g. based on the file type. That's also the only reason
				// why we collect all values above, so that onCreate can analyse them.
				var obj = this.onCreate && this.onCreate(proto, values);
				if (!obj)
					obj = new ctor(this); // Pass the edit item for editing parent stuff.
				if (obj) {
					// Just like in the rest of edit lib, apply first, persist after
					var form = this.getEditForm(obj, id);
					if (form) {
						form.applyItems();
						changed = this.store(obj) || changed;
						entries[id] = { object: obj, visible: true };
					}
				}
			}
		}
		// Now set positions. It is important that this happens in proper sequence,
		// in case we're modifying memory-only HopObjects through addAt...
		(value || '').split(',').each(function(id, index) {
			var entry = entries[id];
			if (entry)
				changed = this.setPosition(entry.object, index, entry.visible) || changed;
		}, this);
		return changed;
	}
});
<|endoftext|>


<commit_before>import DefineMap from 'can-define/map/map';
import DefineList from 'can-define/list/list';
import {Field} from '../../util/field';
import {makeSentenceCase} from '../../util/string';
import assign from 'object-assign';

/**
 * @property filter-widget.FilterOptions FilterOptions
 * @parent filter-widget
 *
 * @description The default filter operator options
 */
export const FilterOptions = [{
    label: 'Does not contain',
    value: 'not_like',
    types: ['string']
}, {
    label: 'Contains',
    value: 'like',
    types: ['string']
}, {
    label: 'Starts with',
    value: 'starts_with',
    types: ['string']
}, {
    label: 'Ends with',
    value: 'ends_with',
    types: ['string']
}, {
    label: 'Exactly equal to',
    value: 'equals'
}, {
    label: 'Not exactly equal to',
    operator: 'not_equal_to',
    value: 'not_equal_to'
}, {
    label: 'Greater Than',
    value: 'greater_than',
    types: ['number']
}, {
    label: 'Less Than',
    value: 'less_than',
    types: ['number']
}, {
    label: 'Before',
    value: 'before',
    types: ['date'],
    valueField: {
        name: 'value',
        alias: 'Value',
        fieldType: 'date',
        properties: {
            placeholder: 'Select a date'
        }
    }
}, {
    label: 'After',
    value: 'after',
    types: ['date'],
    valueField: {
        name: 'value',
        alias: 'Value',
        fieldType: 'date',
        properties: {
            placeholder: 'Select a date'
        }
    }
}];

/**
 * @constructor filter-widget.Filter Filter
 * @parent filter-widget
 * @group filter-widget.Filter.props Properties
 *
 * @description Creates a new filter object
 * @signature `new Filter(properties)`
 */
export const Filter = DefineMap.extend('Filter', {
    /**
     * A value to filter on. Can be any primitive type
     * @property {*} filter-widget.Filter.props.value value
     * @parent filter-widget.Filter.props
     */
    value: {
        type: '*'
    },
    /**
     * The name of the field to filter on
     * @property {String} filter-widget.Filter.props.name name
     * @parent filter-widget.Filter.props
     */
    name: {
        type: 'string',
        get (name) {
            return this.field ? this.field.name : name;
        },
        serialize (name) {
            return name;
        }
    },
    /**
     * The operator to filter with. The default is `like`.
     * @property {String} Ffilter-widget.Filter.props.operator operator
     * @parent filter-widget.Filter.props
     */
    operator: {
        type: 'string',
        value: 'like'
    },
    /**
     * A field object that defines the available operator options and properties.
     * This is used to create the dropdown choice for each filter in the filter-widget
     * @property {Object} filter-widget.Filter.props.operatorField operatorField
     * @parent filter-widget.Filter.props
     */
    operatorField: {
        serialize: false,
        get () {
            const field = this.field;
            return new Field({
                name: 'operator',
                alias: 'is',
                inline: true,
                placeholder: 'Choose an operator',
                fieldType: 'select',
                options: field ? FilterOptions.filter((filter) => {
                    return !field.type || field.type === 'observable' || !filter.types || filter.types.indexOf(field.type) > -1;
                }) : FilterOptions
            });
        }
    },
    alias: {
        get () {
            return this.field ? this.field.alias : makeSentenceCase(this.name);
        }
    },
    /**
     * A field object that defines the value field properties.
     * This is used to create the value field for each filter in the filter-widget
     * @property {util/field.Field} filter-widget.Filter.props.valueField valueField
     * @parent filter-widget.Filter.props
     */
    valueField: {
        serialize: false,
        get () {
            const fieldProps = this.field ? assign(this.field.serialize(), {inline: true}) : {
                inline: true,
                name: this.name,
                alias: 'Value',
                fieldType: 'text',
                placeholder: 'Enter a filter value'
            };
            return new Field(fieldProps);
        }
    },
    /**
     * creates a dummmy form object for use with the field template
     * @property {Object}  filter-widget.Filter.props.formObject formObject
     */
    formObject: {
        serialize: false,
        get () {
            const obj = {};
            obj[this.name] = this.value;
            return obj;
        }
    },
    /**
     * The field object used to initialize this filter
     * @property {util/field.Field}  filter-widget.Filter.props.field field
     */
    field: {
        Type: Field,
        serialize: false
    },
    /**
     * a setter for the value field for use with the field template
     * @param {util/field.Field} field the field object
     * @param {domElement} dom the input element
     * @param {Object} scope the view model scope
     * @param {*} props the object with the value set on the form
     */
    setField (field, dom, scope, props) {
        this.value = props.value;
    }
});

/**
 * @constructor filter-widget.FilterList FilterList
 * @parent filter-widget
 *
 * @description Creates a new filter list
 * @signature `new FilterList([filters])`
 */
export const FilterList = DefineList.extend('FilterList', {
    '#': Filter
});
<commit_msg>FIX: filter-widget - make sure field type uses textarea: false<commit_after>import DefineMap from 'can-define/map/map';
import DefineList from 'can-define/list/list';
import {Field} from '../../util/field';
import {makeSentenceCase} from '../../util/string';
import assign from 'object-assign';

/**
 * @property filter-widget.FilterOptions FilterOptions
 * @parent filter-widget
 *
 * @description The default filter operator options
 */
export const FilterOptions = [{
    label: 'Does not contain',
    value: 'not_like',
    types: ['string']
}, {
    label: 'Contains',
    value: 'like',
    types: ['string']
}, {
    label: 'Starts with',
    value: 'starts_with',
    types: ['string']
}, {
    label: 'Ends with',
    value: 'ends_with',
    types: ['string']
}, {
    label: 'Exactly equal to',
    value: 'equals'
}, {
    label: 'Not exactly equal to',
    operator: 'not_equal_to',
    value: 'not_equal_to'
}, {
    label: 'Greater Than',
    value: 'greater_than',
    types: ['number']
}, {
    label: 'Less Than',
    value: 'less_than',
    types: ['number']
}, {
    label: 'Before',
    value: 'before',
    types: ['date'],
    valueField: {
        name: 'value',
        alias: 'Value',
        fieldType: 'date',
        properties: {
            placeholder: 'Select a date'
        }
    }
}, {
    label: 'After',
    value: 'after',
    types: ['date'],
    valueField: {
        name: 'value',
        alias: 'Value',
        fieldType: 'date',
        properties: {
            placeholder: 'Select a date'
        }
    }
}];

/**
 * @constructor filter-widget.Filter Filter
 * @parent filter-widget
 * @group filter-widget.Filter.props Properties
 *
 * @description Creates a new filter object
 * @signature `new Filter(properties)`
 */
export const Filter = DefineMap.extend('Filter', {
    /**
     * A value to filter on. Can be any primitive type
     * @property {*} filter-widget.Filter.props.value value
     * @parent filter-widget.Filter.props
     */
    value: {
        type: '*'
    },
    /**
     * The name of the field to filter on
     * @property {String} filter-widget.Filter.props.name name
     * @parent filter-widget.Filter.props
     */
    name: {
        type: 'string',
        get (name) {
            return this.field ? this.field.name : name;
        },
        serialize (name) {
            return name;
        }
    },
    /**
     * The operator to filter with. The default is `like`.
     * @property {String} Ffilter-widget.Filter.props.operator operator
     * @parent filter-widget.Filter.props
     */
    operator: {
        type: 'string',
        value: 'like'
    },
    /**
     * A field object that defines the available operator options and properties.
     * This is used to create the dropdown choice for each filter in the filter-widget
     * @property {Object} filter-widget.Filter.props.operatorField operatorField
     * @parent filter-widget.Filter.props
     */
    operatorField: {
        serialize: false,
        get () {
            const field = this.field;
            return new Field({
                name: 'operator',
                alias: 'is',
                inline: true,
                placeholder: 'Choose an operator',
                fieldType: 'select',
                options: field ? FilterOptions.filter((filter) => {
                    return !field.type || field.type === 'observable' || !filter.types || filter.types.indexOf(field.type) > -1;
                }) : FilterOptions
            });
        }
    },
    alias: {
        get () {
            return this.field ? this.field.alias : makeSentenceCase(this.name);
        }
    },
    /**
     * A field object that defines the value field properties.
     * This is used to create the value field for each filter in the filter-widget
     * @property {util/field.Field} filter-widget.Filter.props.valueField valueField
     * @parent filter-widget.Filter.props
     */
    valueField: {
        serialize: false,
        get () {
            const fieldProps = this.field ? assign(this.field.serialize(), {inline: true, textarea: false}) : {
                inline: true,
                name: this.name,
                alias: 'Value',
                fieldType: 'text',
                placeholder: 'Enter a filter value'
            };
            return new Field(fieldProps);
        }
    },
    /**
     * The field object used to initialize this filter
     * @property {util/field.Field}  filter-widget.Filter.props.field field
     */
    field: {
        Type: Field,
        serialize: false
    }
});

/**
 * @constructor filter-widget.FilterList FilterList
 * @parent filter-widget
 *
 * @description Creates a new filter list
 * @signature `new FilterList([filters])`
 */
export const FilterList = DefineList.extend('FilterList', {
    '#': Filter
});
<|endoftext|>


<commit_before>$(function(){
  $('#signUp').submit(function (e) {
    e.preventDefault();
    var form = $('form#signUp');
    $.post('/add-watcher/', form.serialize(), function (data) {
      console.log('response: ' + data)
    })
  });

  var millisecondsInYear = 1000*60*60*24*365;
  var now = new Date();
  var nowPlusTwo = new Date(now.getTime() + (millisecondsInYear * 2));

  var picker1 = new Pikaday({
    field: $('input[name=checkin]')[0],
    minDate: now,
    maxDate: nowPlusTwo,
    container: $("#moveInContainer")[0]
  });

  var picker2 = new Pikaday({
    field: $('input[name=checkout]')[0],
    minDate: now,
    maxDate: nowPlusTwo,
    container: $("#moveOutContainer")[0]
  });
});<commit_msg>Smarter calendar on sign-up page. Fixes #2<commit_after>$(function(){
  $('#signUp').submit(function (e) {
    e.preventDefault();
    var form = $('form#signUp');
    $.post('/add-watcher/', form.serialize(), function (data) {
      console.log('response: ' + data)
    })
  });

  var millisecondsInYear = 1000*60*60*24*365;
  var now = new Date();
  var twoYearsFromNow = new Date(now.getTime() + (millisecondsInYear * 2));

  var $checkin = $('input[name=checkin]');
  var $checkout = $('input[name=checkout]');

  var checkin_picker = new Pikaday({
    field: $checkin[0],
    minDate: now,
    maxDate: twoYearsFromNow,
    container: $("#moveInContainer")[0]
  });

  var checkout_picker = new Pikaday({
    field: $checkout[0],
    minDate: now,
    maxDate: twoYearsFromNow,
    container: $("#moveOutContainer")[0]
  });

  $checkin.change(function () {
    var next_date = new Date($checkin.val());
    if (isNaN(next_date.getTime())) {
      checkout_picker.setMinDate(now);
      return;
    }
    next_date.setDate(next_date.getDate() + 1);
    var checkout_date = checkout_picker.getDate();

    if (checkout_date !== null && checkout_date < next_date) {
      checkout_picker.setDate(next_date, false);
    } else if (checkout_date === null) {
      checkout_picker.gotoDate(next_date);
    }
    checkout_picker.setMinDate(next_date);
  });

  $checkout.change(function () {
    var prev_date = new Date($checkout.val());
    if (isNaN(prev_date.getTime())) {
      checkin_picker.setMaxDate(twoYearsFromNow);
      return;
    }
    prev_date.setDate(prev_date.getDate() - 1);
    var checkin_date = checkin_picker.getDate();

    if (checkin_date !== null && checkin_date > prev_date) {
      checkin_picker.setDate(prev_date, false);
    } else if (checkin_date === null) {
      checkin_picker.gotoDate(prev_date);
    }
    checkin_picker.setMaxDate(prev_date);
  })
});<|endoftext|>


<commit_before>(function (window, io, $, _, Backbone, location, app) {
//    "use strict";

    var ID = "id",
        SECURE = "{{secureClient}}" == "true",
        PORT = "{{port}}",
        watchedEvents = {};

    app.middle = app.middle || {};

    function getServerURL() {
        var protocol = SECURE ? "https://" : "http://",
            port = PORT || location.port;

        if (port) {
            port = ":" + port;
        }

        return protocol + 'http://192.168.1.188' + port;
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, loggingLevel, _args) {

        var logToServer = false;
        if('error' === loggingLevel === level) {
            logToServer = true;
            console.error.apply(console, _args);
        } else if ('debug' === loggingLevel) {
            logToServer = true;
            console.log.apply(console, _args);
        }

        if(logToServer) {
            var args = Array.prototype.slice.call(_args),
                params = [
                    "log",
                    level,
                    new Date()
                ];

            _.each(args, function (arg) {
                var param = convert(arg);
                params.push(param);
            });

            return socket.emit.apply(socket, params);
        }
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function connect(url, cb) {
        try {
            return cb(io.connect(
                'http://192.168.1.188', {
                "reconnection limit":4001, // four second max delay
                "max reconnection attempts":Infinity,
                "match origin protocol": true,
                "force new connection":true,
                "secure": SECURE
            }));
        }
        catch (e) {
            setTimeout(function () {
                connect(url, cb);
            }, 500);

            return app.error("io.connect exception", e);
        }
    }

    function openSocket(cb) {
        var tryAgain = function () {
                if (cb) {
                    app.log("middle trying to connect again");
                    setTimeout(function () {
                        openSocket(cb);
                    }, 500);
                }
            },
            app_log = app.log,
            app_debug = app.debug,
            app_error = app.error,
            url = getServerURL();

        return connect(url, function (socket) {
            socket.on('error', function (err) {
                app.error("middle socket error", err);
                tryAgain();
            });
            socket.on('connecting', function () {
                return app.log("middle connecting");
            });
            socket.on('connect_failed', function (err) {
                app.error("connect_failed", err);
                tryAgain();
            });
            socket.on('reconnect', function () {
                return app.log("middle reconnect");
            });
            socket.on('reconnecting', function () {
                return app.log("middle reconnecting");
            });
            socket.on('connect', function () {
                app.middle.connected = true;

                var _cb = cb,
                    device = window.device || {},
                    userAgent = navigator.userAgent || {};

                cb = undefined;

                socket.emit("middle-initialize", {
                    id:app.middle.id,
                    uuid:device.uuid,
                    name:device.name,
                    platform:device.platform,
                    version:device.version,
                    cordova:device.cordova,
                    userAgent: userAgent
                }, function(err, result) {

                    app.log = function () {
                        return log(socket, "info", result.loggingLevel, arguments);
                    };
                    app.debug = function () {
                        return log(socket, "debug", result.loggingLevel, arguments);
                    };
                    app.error = function () {
                        return log(socket, "error", result.loggingLevel, arguments);
                    };

                    app.log("middle connected");

                    return _cb && _cb(socket);
                });

            });
            socket.on('disconnect', function () {
                app.middle.connected = false;

                app.log = app_log;
                app.debug = app_debug;
                app.error = app_error;
                app.middle.trigger("disconnect", app.middle.id);

                return app.log("disconnected", app.middle.id);
            });
        });
    }

    app.starter.$(function (next) {
        if (app.middle.disable) {
            return next();
        }

        app.store("middle", function (store) {
            store.get(ID, function (id) {
                app.middle.id = (id && id.id) || app.utils.uuid();

                if (!id) {
                    store.save(ID, app.middle.id);
                }

                var bindSocketListeners = function(socket) {
                    app.middle.bind = app.middle.on = app.middle.on || function (event, callback, context) {
                        var events = event.split(/\s+/);

                        _.each(events, function (event) {
                            if (!watchedEvents[event]) {
                                watchedEvents[event] = true;
                                socket.on(event, function () {
                                    var args = Array.prototype.slice.call(arguments);

                                    args.unshift(event);

                                    return app.middle.trigger.apply(app.middle, args);
                                });
                            }
                        });

                        Backbone.Events.on.call(app.middle, event, callback, context);
                    };
                    app.middle.unbind = app.middle.off = app.middle.off || function () {
                        Backbone.Events.off.apply(app.middle, arguments);
                    };
                    app.middle.trigger = app.middle.trigger = app.middle.trigger || function () {
                        Backbone.Events.trigger.apply(app.middle, arguments);
                    };

                    app.middle.stop = function() {
                        console.log("disconnect");
                        socket.disconnect();
                    };

                    app.middle.restart = function() {
                        console.log("restart");
                        if(socket) {
                            socket.connect();
                        } else {
                            openSocket(function (socket) {
                                bindSocketListeners(socket);
                            });
                        }
                    };

                    app.middle.emit = emitter(socket);
                };

                return openSocket(function (socket) {
                    bindSocketListeners(socket);
                    return next();
                });
            });
        });
    });
})(window, window.io, $, _, Backbone, window.location, window["web-app"]);
<commit_msg>location.hostname<commit_after>(function (window, io, $, _, Backbone, location, app) {
//    "use strict";

    var ID = "id",
        SECURE = "{{secureClient}}" == "true",
        PORT = "{{port}}",
        watchedEvents = {};

    app.middle = app.middle || {};

    function getServerURL() {
        var protocol = SECURE ? "https://" : "http://",
            port = PORT || location.port;

        if (port) {
            port = ":" + port;
        }

        return protocol + location.hostname + port;
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, loggingLevel, _args) {

        var logToServer = false;
        if('error' === loggingLevel === level) {
            logToServer = true;
            console.error.apply(console, _args);
        } else if ('debug' === loggingLevel) {
            logToServer = true;
            console.log.apply(console, _args);
        }

        if(logToServer) {
            var args = Array.prototype.slice.call(_args),
                params = [
                    "log",
                    level,
                    new Date()
                ];

            _.each(args, function (arg) {
                var param = convert(arg);
                params.push(param);
            });

            return socket.emit.apply(socket, params);
        }
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function connect(url, cb) {
        try {
            return cb(io.connect(
                'http://192.168.1.188', {
                "reconnection limit":4001, // four second max delay
                "max reconnection attempts":Infinity,
                "match origin protocol": true,
                "force new connection":true,
                "secure": SECURE
            }));
        }
        catch (e) {
            setTimeout(function () {
                connect(url, cb);
            }, 500);

            return app.error("io.connect exception", e);
        }
    }

    function openSocket(cb) {
        var tryAgain = function () {
                if (cb) {
                    app.log("middle trying to connect again");
                    setTimeout(function () {
                        openSocket(cb);
                    }, 500);
                }
            },
            app_log = app.log,
            app_debug = app.debug,
            app_error = app.error,
            url = getServerURL();

        return connect(url, function (socket) {
            socket.on('error', function (err) {
                app.error("middle socket error", err);
                tryAgain();
            });
            socket.on('connecting', function () {
                return app.log("middle connecting");
            });
            socket.on('connect_failed', function (err) {
                app.error("connect_failed", err);
                tryAgain();
            });
            socket.on('reconnect', function () {
                return app.log("middle reconnect");
            });
            socket.on('reconnecting', function () {
                return app.log("middle reconnecting");
            });
            socket.on('connect', function () {
                app.middle.connected = true;

                var _cb = cb,
                    device = window.device || {},
                    userAgent = navigator.userAgent || {};

                cb = undefined;

                socket.emit("middle-initialize", {
                    id:app.middle.id,
                    uuid:device.uuid,
                    name:device.name,
                    platform:device.platform,
                    version:device.version,
                    cordova:device.cordova,
                    userAgent: userAgent
                }, function(err, result) {

                    app.log = function () {
                        return log(socket, "info", result.loggingLevel, arguments);
                    };
                    app.debug = function () {
                        return log(socket, "debug", result.loggingLevel, arguments);
                    };
                    app.error = function () {
                        return log(socket, "error", result.loggingLevel, arguments);
                    };

                    app.log("middle connected");

                    return _cb && _cb(socket);
                });

            });
            socket.on('disconnect', function () {
                app.middle.connected = false;

                app.log = app_log;
                app.debug = app_debug;
                app.error = app_error;
                app.middle.trigger("disconnect", app.middle.id);

                return app.log("disconnected", app.middle.id);
            });
        });
    }

    app.starter.$(function (next) {
        if (app.middle.disable) {
            return next();
        }

        app.store("middle", function (store) {
            store.get(ID, function (id) {
                app.middle.id = (id && id.id) || app.utils.uuid();

                if (!id) {
                    store.save(ID, app.middle.id);
                }

                var bindSocketListeners = function(socket) {
                    app.middle.bind = app.middle.on = app.middle.on || function (event, callback, context) {
                        var events = event.split(/\s+/);

                        _.each(events, function (event) {
                            if (!watchedEvents[event]) {
                                watchedEvents[event] = true;
                                socket.on(event, function () {
                                    var args = Array.prototype.slice.call(arguments);

                                    args.unshift(event);

                                    return app.middle.trigger.apply(app.middle, args);
                                });
                            }
                        });

                        Backbone.Events.on.call(app.middle, event, callback, context);
                    };
                    app.middle.unbind = app.middle.off = app.middle.off || function () {
                        Backbone.Events.off.apply(app.middle, arguments);
                    };
                    app.middle.trigger = app.middle.trigger = app.middle.trigger || function () {
                        Backbone.Events.trigger.apply(app.middle, arguments);
                    };

                    app.middle.stop = function() {
                        console.log("disconnect");
                        socket.disconnect();
                    };

                    app.middle.restart = function() {
                        console.log("restart");
                        if(socket) {
                            socket.connect();
                        } else {
                            openSocket(function (socket) {
                                bindSocketListeners(socket);
                            });
                        }
                    };

                    app.middle.emit = emitter(socket);
                };

                return openSocket(function (socket) {
                    bindSocketListeners(socket);
                    return next();
                });
            });
        });
    });
})(window, window.io, $, _, Backbone, window.location, window["web-app"]);
<|endoftext|>


<commit_before>function puts(){
  console.log.apply(console, arguments);
}

// global namespace
var Jdbcwb = {};

(function(){

  "use strict";

  var _g = Jdbcwb; // global namespace alias

  ////////////////////////////////

  var Database = {

    singleQuery: function(mode, schema, tablePName, sql, fnOk, fnNg){
      this.multiQuery(mode, schema, tablePName, [sql], function(results){
        fnOk(results[0]);
      }, fnNg);
    },

    multiQuery: function(mode, schema, tablePName, sqls, fnOk, fnNg){
      $.post("/api/query", {
        mode: mode,
        schema: schema,
        table: tablePName,
        sqls: JSON.stringify(sqls)
      }).done(function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data.results);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    },

    update: function(sql, fnOk, fnNg){
      $.post("/api/update", {
        sql: sql
      }, function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    }
  };

  ////////////////////////////////

  _g.AppM = Backbone.Model.extend({
    defaults: {
      ajaxResponse: ""
    }
  });

  _g.AppV = Backbone.View.extend({

    el: "body",

    initialize: function(){
      this.listenTo(this.model, "change", this.render);
    },

    render: function(){
      $("#ajax_response").val(this.model.get("ajaxResponse"));
    },

    guard:   function(){ this.$("#guard_layer").show(); },
    unguard: function(){ this.$("#guard_layer").hide(); }
  });

  ////////////////////////////////

  _g.GenericOperationM = Backbone.Model.extend({

    doQuery: function(sql, viewFnOk, viewFnNg){
      var resboxM = _g.genericOperationResultBoxM;
      Database.singleQuery('generic', null, null, sql, function(result){
        resboxM.set("numRows", result.numRows, {silent: true});
        resboxM.set("colDefs", result.colDefs, {silent: true});
        resboxM.set("rows", result.rows, {silent: true});
        resboxM.trigger("change");
        viewFnOk();
      }, function(data){
        viewFnNg();
      });
    }
  });

  _g.GenericOperationV = Backbone.View.extend({

    el: "#_generic_operation",

    events: {
      "click .btn_query": "doQuery",
      "click .btn_update": "doUpdate"
    },

    doQuery: function(){
      _g.appV.guard();

      var sql = this.$("textarea").val();

      this.model.doQuery(sql, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    },

    doUpdate: function(){
      var resboxM = _g.genericOperationResultBoxM;
      _g.appV.guard();

      var sql = this.$("textarea").val();

      Database.update(sql, function(data){
        resboxM.set("numRows", data.count);
        _g.appV.unguard();
      }, function(data){
        _g.appV.unguard();
      });
    }
  });

  ////////////////////////////////

  _g.TableEditM = Backbone.Model.extend({

    doQuery: function(schema, tablePName, sql, viewFnOk, viewFnNg){
      var resboxM = _g.tableEditResultBoxM;

      Database.singleQuery('single_table', schema, tablePName, sql, function(result){
        // OK
        resboxM.set("numRows", result.numRows, {silent: true});
        resboxM.set("colDefs", result.colDefs, {silent: true});
        resboxM.set("rows", result.rows, {silent: true});
        resboxM.trigger("change");

        viewFnOk();
      }, function(data){
        // NG
        viewFnNg();
      });
    }
  });

  _g.TableEditV = Backbone.View.extend({

    el: "#_table_edit",

    events: {
      "click .btn_query": "doQuery"
    },

    doQuery: function(ev){
      ev.preventDefault();
      var resboxM = _g.tableEditResultBoxM;

      _g.appV.guard();
      // _g.appV.hideMsg(); // TODO
      resboxM.reset();
      this.colDefs = null;

      var schema = this.$("[name=schema]").val();
      var tablePName = this.$("[name=table_pname]").val();
      var sql = this.makeSql(tablePName);

      this.model.doQuery(schema, tablePName, sql, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    },

    makeSql: function(tablePName){
      return [
        "SELECT *",
        "FROM " + tablePName
      ].join("\n");
    }
  });

  ////////////////////////////////

  _g.ResultBoxM = Backbone.Model.extend({
    defaults: {
      numRows: null,
      rows: [],
      colDefs: []
    },

    reset: function(){
      this.set("data", {
        colDefs: [],
        rows: [],
        numRows: "-",
        numRowsAll: "-"
      });
      this.set("colDefs", [], {silent: true});
      this.set("rows", [], {silent: true});
      this.set("numRows", "-", {silent: true});
      this.set("numRowsAll", "-", {silent: true});
      this.trigger("change");
    }
  });

  _g.ResultBoxV = Backbone.View.extend({
    initialize: function(){
      this.listenTo(this.model, "change", this.render);
    },

    render: function(){
      // clear
      this.$(".result thead").empty();
      this.$(".result tbody").empty();

      var numRows = this.model.get("numRows");
      this.$(".num_rows").text(numRows != null ? numRows : "-");

      // header
      var $thead = this.$(".result thead");
      var $tr = $('
#
');
      _.each(this.model.get("colDefs"), function(colDef){
        $tr.append('' + colDef.name + '	');
      });
      $thead.append($tr);

      // rows
      var $tbody = this.$(".result tbody");
      _.each(this.model.get("rows"), function(row, ri){
        var rn = ri + 1;
        var $tr = $('
'+rn+'
');
        _.each(row, function(col){
          $tr.append(''+ _.escape(col) +'	');
        });
        $tbody.append($tr);
      });
    }
  });

  ////////////////////////////////

  _g.start = function(){

    _g.genericOperationResultBoxM = new _g.ResultBoxM();
    _g.genericOperationResultBoxV = new _g.ResultBoxV({
      el: $("#_generic_operation ._result_box"),
      model: _g.genericOperationResultBoxM
    });

    _g.tableEditResultBoxM = new _g.ResultBoxM();
    _g.tableEditResultBoxV = new _g.ResultBoxV({
      el: $("#_table_edit ._result_box"),
      model: _g.tableEditResultBoxM
    });

    _g.genericOperationM = new _g.GenericOperationM();
    _g.genericOperationV = new _g.GenericOperationV({
      model: _g.genericOperationM
    });

    _g.tableEditM = new _g.TableEditM();
    _g.tableEditV = new _g.TableEditV({
      model: _g.tableEditM
    });

    _g.appM = new _g.AppM();
    _g.appV = new _g.AppV({
      model: _g.appM
    });
  };

})();

////////////////////////////////

$(Jdbcwb.start);
<commit_msg>reset ResultBox when error occured<commit_after>function puts(){
  console.log.apply(console, arguments);
}

// global namespace
var Jdbcwb = {};

(function(){

  "use strict";

  var _g = Jdbcwb; // global namespace alias

  ////////////////////////////////

  var Database = {

    singleQuery: function(mode, schema, tablePName, sql, fnOk, fnNg){
      this.multiQuery(mode, schema, tablePName, [sql], function(results){
        fnOk(results[0]);
      }, fnNg);
    },

    multiQuery: function(mode, schema, tablePName, sqls, fnOk, fnNg){
      $.post("/api/query", {
        mode: mode,
        schema: schema,
        table: tablePName,
        sqls: JSON.stringify(sqls)
      }).done(function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data.results);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    },

    update: function(sql, fnOk, fnNg){
      $.post("/api/update", {
        sql: sql
      }, function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    }
  };

  ////////////////////////////////

  _g.AppM = Backbone.Model.extend({
    defaults: {
      ajaxResponse: ""
    }
  });

  _g.AppV = Backbone.View.extend({

    el: "body",

    initialize: function(){
      this.listenTo(this.model, "change", this.render);
    },

    render: function(){
      $("#ajax_response").val(this.model.get("ajaxResponse"));
    },

    guard:   function(){ this.$("#guard_layer").show(); },
    unguard: function(){ this.$("#guard_layer").hide(); }
  });

  ////////////////////////////////

  _g.GenericOperationM = Backbone.Model.extend({

    doQuery: function(sql, viewFnOk, viewFnNg){
      var resboxM = _g.genericOperationResultBoxM;
      Database.singleQuery('generic', null, null, sql, function(result){
        resboxM.set("numRows", result.numRows, {silent: true});
        resboxM.set("colDefs", result.colDefs, {silent: true});
        resboxM.set("rows", result.rows, {silent: true});
        resboxM.trigger("change");
        viewFnOk();
      }, function(data){
        viewFnNg();
      });
    }
  });

  _g.GenericOperationV = Backbone.View.extend({

    el: "#_generic_operation",

    events: {
      "click .btn_query": "doQuery",
      "click .btn_update": "doUpdate"
    },

    doQuery: function(){
      var resboxM = _g.genericOperationResultBoxM;

      _g.appV.guard();
      resboxM.reset();

      var sql = this.$("textarea").val();

      this.model.doQuery(sql, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    },

    doUpdate: function(){
      var resboxM = _g.genericOperationResultBoxM;
      _g.appV.guard();

      var sql = this.$("textarea").val();

      Database.update(sql, function(data){
        resboxM.set("numRows", data.count);
        _g.appV.unguard();
      }, function(data){
        _g.appV.unguard();
      });
    }
  });

  ////////////////////////////////

  _g.TableEditM = Backbone.Model.extend({

    doQuery: function(schema, tablePName, sql, viewFnOk, viewFnNg){
      var resboxM = _g.tableEditResultBoxM;

      Database.singleQuery('single_table', schema, tablePName, sql, function(result){
        // OK
        resboxM.set("numRows", result.numRows, {silent: true});
        resboxM.set("colDefs", result.colDefs, {silent: true});
        resboxM.set("rows", result.rows, {silent: true});
        resboxM.trigger("change");

        viewFnOk();
      }, function(data){
        // NG
        viewFnNg();
      });
    }
  });

  _g.TableEditV = Backbone.View.extend({

    el: "#_table_edit",

    events: {
      "click .btn_query": "doQuery"
    },

    doQuery: function(ev){
      ev.preventDefault();
      var resboxM = _g.tableEditResultBoxM;

      _g.appV.guard();
      // _g.appV.hideMsg(); // TODO
      resboxM.reset();
      this.colDefs = null;

      var schema = this.$("[name=schema]").val();
      var tablePName = this.$("[name=table_pname]").val();
      var sql = this.makeSql(tablePName);

      this.model.doQuery(schema, tablePName, sql, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    },

    makeSql: function(tablePName){
      return [
        "SELECT *",
        "FROM " + tablePName
      ].join("\n");
    }
  });

  ////////////////////////////////

  _g.ResultBoxM = Backbone.Model.extend({
    defaults: {
      numRows: null,
      rows: [],
      colDefs: []
    },

    reset: function(){
      this.set("data", {
        colDefs: [],
        rows: [],
        numRows: "-",
        numRowsAll: "-"
      });
      this.set("colDefs", [], {silent: true});
      this.set("rows", [], {silent: true});
      this.set("numRows", "-", {silent: true});
      this.set("numRowsAll", "-", {silent: true});
      this.trigger("change");
    }
  });

  _g.ResultBoxV = Backbone.View.extend({
    initialize: function(){
      this.listenTo(this.model, "change", this.render);
    },

    render: function(){
      // clear
      this.$(".result thead").empty();
      this.$(".result tbody").empty();

      var numRows = this.model.get("numRows");
      this.$(".num_rows").text(numRows != null ? numRows : "-");

      // header
      var $thead = this.$(".result thead");
      var $tr = $('
#
');
      _.each(this.model.get("colDefs"), function(colDef){
        $tr.append('' + colDef.name + '	');
      });
      $thead.append($tr);

      // rows
      var $tbody = this.$(".result tbody");
      _.each(this.model.get("rows"), function(row, ri){
        var rn = ri + 1;
        var $tr = $('
'+rn+'
');
        _.each(row, function(col){
          $tr.append(''+ _.escape(col) +'	');
        });
        $tbody.append($tr);
      });
    }
  });

  ////////////////////////////////

  _g.start = function(){

    _g.genericOperationResultBoxM = new _g.ResultBoxM();
    _g.genericOperationResultBoxV = new _g.ResultBoxV({
      el: $("#_generic_operation ._result_box"),
      model: _g.genericOperationResultBoxM
    });

    _g.tableEditResultBoxM = new _g.ResultBoxM();
    _g.tableEditResultBoxV = new _g.ResultBoxV({
      el: $("#_table_edit ._result_box"),
      model: _g.tableEditResultBoxM
    });

    _g.genericOperationM = new _g.GenericOperationM();
    _g.genericOperationV = new _g.GenericOperationV({
      model: _g.genericOperationM
    });

    _g.tableEditM = new _g.TableEditM();
    _g.tableEditV = new _g.TableEditV({
      model: _g.tableEditM
    });

    _g.appM = new _g.AppM();
    _g.appV = new _g.AppV({
      model: _g.appM
    });
  };

})();

////////////////////////////////

$(Jdbcwb.start);
<|endoftext|>