<commit_before>// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"use strict";

// This file relies on the fact that the following declaration has been made
// in runtime.js:
// var $Array = global.Array;

var $ArrayBuffer = global.ArrayBuffer;

// -------------------------------------------------------------------

function ArrayBufferConstructor(byteLength) { // length = 1
  if (%_IsConstructCall()) {
    var l = TO_POSITIVE_INTEGER(byteLength);
    %ArrayBufferInitialize(this, l);
  } else {
    return new $ArrayBuffer(byteLength);
  }
}

function ArrayBufferGetByteLength() {
  if (!IS_ARRAYBUFFER(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['ArrayBuffer.prototype.byteLength', this]);
  }
  return %ArrayBufferGetByteLength(this);
}

// ES6 Draft 15.13.5.5.3
function ArrayBufferSlice(start, end) {
  if (!IS_ARRAYBUFFER(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['ArrayBuffer.prototype.slice', this]);
  }

  var relativeStart = TO_INTEGER(start);
  var first;
  if (relativeStart < 0) {
    first = MathMax(this.byteLength + relativeStart, 0);
  } else {
    first = MathMin(relativeStart, this.byteLength);
  }
  var relativeEnd = IS_UNDEFINED(end) ? this.byteLength : TO_INTEGER(end);
  var fin;
  if (relativeEnd < 0) {
    fin = MathMax(this.byteLength + relativeEnd, 0);
  } else {
    fin = MathMin(relativeEnd, this.byteLength);
  }

  var newLen = fin - first;
  // TODO(dslomov): implement inheritance
  var result = new $ArrayBuffer(newLen);

  %ArrayBufferSliceImpl(this, result, first);
  return result;
}

// --------------- Typed Arrays ---------------------

function CreateTypedArrayConstructor(name, elementSize, arrayId, constructor) {
  function ConstructByArrayBuffer(obj, buffer, byteOffset, length) {
    var offset = IS_UNDEFINED(byteOffset) ? 0 : TO_POSITIVE_INTEGER(byteOffset);

    if (offset % elementSize !== 0) {
      throw MakeRangeError("invalid_typed_array_alignment",
          "start offset", name, elementSize);
    }
    var bufferByteLength = %ArrayBufferGetByteLength(buffer);
    if (offset >= bufferByteLength) {
      throw MakeRangeError("invalid_typed_array_offset");
    }

    var newByteLength;
    var newLength;
    if (IS_UNDEFINED(length)) {
      if (bufferByteLength % elementSize !== 0) {
        throw MakeRangeError("invalid_typed_array_alignment",
          "byte length", name, elementSize);
      }
      newByteLength = bufferByteLength - offset;
      newLength = newByteLength / elementSize;
    } else {
      var newLength = TO_POSITIVE_INTEGER(length);
      newByteLength = newLength * elementSize;
    }
    if (newByteLength > bufferByteLength) {
      throw MakeRangeError("invalid_typed_array_length");
    }
    %TypedArrayInitialize(obj, arrayId, buffer, offset, newByteLength);
  }

  function ConstructByLength(obj, length) {
    var l = IS_UNDEFINED(length) ? 0 : TO_POSITIVE_INTEGER(length);
    var byteLength = l * elementSize;
    var buffer = new $ArrayBuffer(byteLength);
    %TypedArrayInitialize(obj, arrayId, buffer, 0, byteLength);
  }

  return function (arg1, arg2, arg3) {
    if (%_IsConstructCall()) {
      if (IS_ARRAYBUFFER(arg1)) {
        ConstructByArrayBuffer(this, arg1, arg2, arg3);
      } else {
        ConstructByLength(this, arg1);
      }
    } else {
      return new constructor(arg1, arg2, arg3);
    }
  }
}

function TypedArrayGetBuffer() {
  return %TypedArrayGetBuffer(this);
}

function TypedArrayGetByteLength() {
  return %TypedArrayGetByteLength(this);
}

function TypedArrayGetByteOffset() {
  return %TypedArrayGetByteOffset(this);
}

function TypedArrayGetLength() {
  return %TypedArrayGetLength(this);
}

// -------------------------------------------------------------------

function SetUpArrayBuffer() {
  %CheckIsBootstrapping();

  // Set up the ArrayBuffer constructor function.
  %SetCode($ArrayBuffer, ArrayBufferConstructor);
  %FunctionSetPrototype($ArrayBuffer, new $Object());

  // Set up the constructor property on the ArrayBuffer prototype object.
  %SetProperty($ArrayBuffer.prototype, "constructor", $ArrayBuffer, DONT_ENUM);

  InstallGetter($ArrayBuffer.prototype, "byteLength", ArrayBufferGetByteLength);

  InstallFunctions($ArrayBuffer.prototype, DONT_ENUM, $Array(
      "slice", ArrayBufferSlice
  ));
}

SetUpArrayBuffer();

function SetupTypedArray(arrayId, name, constructor, elementSize) {
  %CheckIsBootstrapping();
  var fun = CreateTypedArrayConstructor(name, elementSize,
                                        arrayId, constructor);
  %SetCode(constructor, fun);
  %FunctionSetPrototype(constructor, new $Object());

  %SetProperty(constructor.prototype,
               "constructor", constructor, DONT_ENUM);
  %SetProperty(constructor.prototype,
               "BYTES_PER_ELEMENT", elementSize,
               READ_ONLY | DONT_ENUM | DONT_DELETE);
  InstallGetter(constructor.prototype, "buffer", TypedArrayGetBuffer);
  InstallGetter(constructor.prototype, "byteOffset", TypedArrayGetByteOffset);
  InstallGetter(constructor.prototype, "byteLength", TypedArrayGetByteLength);
  InstallGetter(constructor.prototype, "length", TypedArrayGetLength);
}

// arrayIds below should be synchronized with Runtime_TypedArrayInitialize.
SetupTypedArray(1, "Uint8Array", global.Uint8Array, 1);
SetupTypedArray(2, "Int8Array", global.Int8Array, 1);
SetupTypedArray(3, "Uint16Array", global.Uint16Array, 2);
SetupTypedArray(4, "Int16Array", global.Int16Array, 2);
SetupTypedArray(5, "Uint32Array", global.Uint32Array, 4);
SetupTypedArray(6, "Int32Array", global.Int32Array, 4);
SetupTypedArray(7, "Float32Array", global.Float32Array, 4);
SetupTypedArray(8, "Float64Array", global.Float64Array, 8);

<commit_msg>Revert "patch from issue 13993029"<commit_after>// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"use strict";

// This file relies on the fact that the following declaration has been made
// in runtime.js:
// var $Array = global.Array;

var $ArrayBuffer = global.ArrayBuffer;

// -------------------------------------------------------------------

function ArrayBufferConstructor(byteLength) { // length = 1
  if (%_IsConstructCall()) {
    var l = TO_POSITIVE_INTEGER(byteLength);
    %ArrayBufferInitialize(this, l);
  } else {
    return new $ArrayBuffer(byteLength);
  }
}

function ArrayBufferGetByteLength() {
  if (!IS_ARRAYBUFFER(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['ArrayBuffer.prototype.byteLength', this]);
  }
  return %ArrayBufferGetByteLength(this);
}

// ES6 Draft 15.13.5.5.3
function ArrayBufferSlice(start, end) {
  if (!IS_ARRAYBUFFER(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['ArrayBuffer.prototype.slice', this]);
  }

  var relativeStart = TO_INTEGER(start);
  var first;
  if (relativeStart < 0) {
    first = MathMax(this.byteLength + relativeStart, 0);
  } else {
    first = MathMin(relativeStart, this.byteLength);
  }
  var relativeEnd = IS_UNDEFINED(end) ? this.byteLength : TO_INTEGER(end);
  var fin;
  if (relativeEnd < 0) {
    fin = MathMax(this.byteLength + relativeEnd, 0);
  } else {
    fin = MathMin(relativeEnd, this.byteLength);
  }

  var newLen = fin - first;
  // TODO(dslomov): implement inheritance
  var result = new $ArrayBuffer(newLen);

  %ArrayBufferSliceImpl(this, result, first);
  return result;
}

// --------------- Typed Arrays ---------------------

function CreateTypedArrayConstructor(name, elementSize, arrayId, constructor) {
  function ConstructByArrayBuffer(obj, buffer, byteOffset, length) {
    var offset = IS_UNDEFINED(byteOffset)
      ? 0 : offset = TO_POSITIVE_INTEGER(byteOffset);

    if (offset % elementSize !== 0) {
      throw MakeRangeError("invalid_typed_array_alignment",
          "start offset", name, elementSize);
    }
    var bufferByteLength = %ArrayBufferGetByteLength(buffer);
    if (offset >= bufferByteLength) {
      throw MakeRangeError("invalid_typed_array_offset");
    }

    var newByteLength;
    var newLength;
    if (IS_UNDEFINED(length)) {
      if (bufferByteLength % elementSize !== 0) {
        throw MakeRangeError("invalid_typed_array_alignment",
          "byte length", name, elementSize);
      }
      newByteLength = bufferByteLength - offset;
      newLength = newByteLength / elementSize;
    } else {
      var newLength = TO_POSITIVE_INTEGER(length);
      newByteLength = newLength * elementSize;
    }
    if (newByteLength > bufferByteLength) {
      throw MakeRangeError("invalid_typed_array_length");
    }
    %TypedArrayInitialize(obj, arrayId, buffer, offset, newByteLength);
  }

  function ConstructByLength(obj, length) {
    var l = IS_UNDEFINED(length) ? 0 : TO_POSITIVE_INTEGER(length);
    var byteLength = l * elementSize;
    var buffer = new $ArrayBuffer(byteLength);
    %TypedArrayInitialize(obj, arrayId, buffer, 0, byteLength);
  }

  return function (arg1, arg2, arg3) {
    if (%_IsConstructCall()) {
      if (IS_ARRAYBUFFER(arg1)) {
        ConstructByArrayBuffer(this, arg1, arg2, arg3);
      } else {
        ConstructByLength(this, arg1);
      }
    } else {
      return new constructor(arg1, arg2, arg3);
    }
  }
}

function TypedArrayGetBuffer() {
  return %TypedArrayGetBuffer(this);
}

function TypedArrayGetByteLength() {
  return %TypedArrayGetByteLength(this);
}

function TypedArrayGetByteOffset() {
  return %TypedArrayGetByteOffset(this);
}

function TypedArrayGetLength() {
  return %TypedArrayGetLength(this);
}

// -------------------------------------------------------------------

function SetUpArrayBuffer() {
  %CheckIsBootstrapping();

  // Set up the ArrayBuffer constructor function.
  %SetCode($ArrayBuffer, ArrayBufferConstructor);
  %FunctionSetPrototype($ArrayBuffer, new $Object());

  // Set up the constructor property on the ArrayBuffer prototype object.
  %SetProperty($ArrayBuffer.prototype, "constructor", $ArrayBuffer, DONT_ENUM);

  InstallGetter($ArrayBuffer.prototype, "byteLength", ArrayBufferGetByteLength);

  InstallFunctions($ArrayBuffer.prototype, DONT_ENUM, $Array(
      "slice", ArrayBufferSlice
  ));
}

SetUpArrayBuffer();

function SetupTypedArray(arrayId, name, constructor, elementSize) {
  %CheckIsBootstrapping();
  var fun = CreateTypedArrayConstructor(name, elementSize,
                                        arrayId, constructor);
  %SetCode(constructor, fun);
  %FunctionSetPrototype(constructor, new $Object());

  %SetProperty(constructor.prototype,
               "constructor", constructor, DONT_ENUM);
  %SetProperty(constructor.prototype,
               "BYTES_PER_ELEMENT", elementSize,
               READ_ONLY | DONT_ENUM | DONT_DELETE);
  InstallGetter(constructor.prototype, "buffer", TypedArrayGetBuffer);
  InstallGetter(constructor.prototype, "byteOffset", TypedArrayGetByteOffset);
  InstallGetter(constructor.prototype, "byteLength", TypedArrayGetByteLength);
  InstallGetter(constructor.prototype, "length", TypedArrayGetLength);
}

// arrayIds below should be synchronized with Runtime_TypedArrayInitialize.
SetupTypedArray(1, "Uint8Array", global.Uint8Array, 1);
SetupTypedArray(2, "Int8Array", global.Int8Array, 1);
SetupTypedArray(3, "Uint16Array", global.Uint16Array, 2);
SetupTypedArray(4, "Int16Array", global.Int16Array, 2);
SetupTypedArray(5, "Uint32Array", global.Uint32Array, 4);
SetupTypedArray(6, "Int32Array", global.Int32Array, 4);
SetupTypedArray(7, "Float32Array", global.Float32Array, 4);
SetupTypedArray(8, "Float64Array", global.Float64Array, 8);

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Matt Cain (@CainCode)
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

(function($){
    'use strict';

    $.preloadimages = function(images, options) {

        var settings = $.extend({
            // Using $.noop instead of null or undefined lets us call the callbacks without
            // having to check that they are actually a function.
            each: $.noop,
            all: $.noop
        }, options),
            loaded = [],
            counter = 0;

        $.each(images, function(i, url) {

            var image = new Image();

            $(image).on('load error', function(e) {
                var $this = $(this);

                counter++;

                // All image objects are passed to the callbacks, this is
                // how you tell whether it was successfully loaded.
                $this.data('loaded', 'error' === e.type ? false : true);

                loaded[i] = image;

                settings.each($this);

                // We use a counter because if the last image in the array loads
                // first then loaded.length === images.length will be true, even
                // though the rest of the array elements will be undefined.
                if (counter === images.length) {
                    settings.all(loaded);
                }

                // Cancel the events in case anyone wants to reuse the image objects.
                $(this).off('load error');
            });

            // Set the src to start loading the image!
            image.src = url;
        });
    };
})(jQuery);<commit_msg>Changed license contact info<commit_after>/*!
 * Copyright (c) 2014 Matt Cain (Twitter:@CainCode, Github:@MattCain)
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

(function($){
    'use strict';

    $.preloadimages = function(images, options) {

        var settings = $.extend({
            // Using $.noop instead of null or undefined lets us call the callbacks without
            // having to check that they are actually a function.
            each: $.noop,
            all: $.noop
        }, options),
            loaded = [],
            counter = 0;

        $.each(images, function(i, url) {

            var image = new Image();

            $(image).on('load error', function(e) {
                var $this = $(this);

                counter++;

                // All image objects are passed to the callbacks, this is
                // how you tell whether it was successfully loaded.
                $this.data('loaded', 'error' === e.type ? false : true);

                loaded[i] = image;

                settings.each($this);

                // We use a counter because if the last image in the array loads
                // first then loaded.length === images.length will be true, even
                // though the rest of the array elements will be undefined.
                if (counter === images.length) {
                    settings.all(loaded);
                }

                // Cancel the events in case anyone wants to reuse the image objects.
                $(this).off('load error');
            });

            // Set the src to start loading the image!
            image.src = url;
        });
    };
})(jQuery);<|endoftext|>


<commit_before>/* global describe, it, require */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Create deep copies:
	createCopy = require( 'utils-copy' ),

	// Module to be tested:
	createMergeFcn = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'utils-merge', function tests() {

	it( 'should export a function', function test() {
		expect( createMergeFcn ).to.be.a( 'function' );
	});

	it( 'should throw an error if provided a non-object options argument', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			true,
			[],
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( value );
			};
		}
	});

	it( 'should throw an error if provided a level option which is not a positive integer', function test() {
		var values = [
			'5',
			-5,
			Math.PI,
			0,
			null,
			NaN,
			undefined,
			true,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'level':value} );
			};
		}
	});

	it( 'should throw an error if provided a copy option which is not a boolean primitive', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			new Boolean( true ),
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'copy':value} );
			};
		}
	});

	it( 'should throw an error if provided an extend option which is not a boolean primitive', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			new Boolean( true ),
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'extend':value} );
			};
		}
	});

	it( 'should throw an error if provided an override option which is not either a boolean primitive or a function', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			new Boolean( true ),
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'override':value} );
			};
		}
	});

	it( 'should return a function', function test() {
		expect( createMergeFcn() ).to.be.a( 'function' );
	});

	it( 'should throw an error if provided insufficient arguments', function test() {
		var merge = createMergeFcn();
		expect( foo ).to.throw( Error );
		expect( bar ).to.throw( Error );
		function foo() {
			merge();
		}
		function bar() {
			merge( {} );
		}
	});

	it( 'should throw an error if provided a target which is not an object', function test() {
		var values, merge;

		values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			true,
			[],
			function(){}
		];

		merge = createMergeFcn();

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				merge( value, {} );
			};
		}
	});

	it( 'should throw an error if provided a source which is not an object', function test() {
		var values, merge;

		values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			true,
			[],
			function(){}
		];

		merge = createMergeFcn();

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				merge( {}, value );
			};
		}
	});

	it( 'should merge two objects', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {};
		src = {
			'a': 'beep',
			'b': 'boop'
		};

		merge = createMergeFcn();

		actual = merge( target, src );
		expected = createCopy( src );

		assert.ok( actual !== src );
		assert.ok( actual === target );
		assert.deepEqual( actual, expected );
	});

	it( 'should merge multiple objects', function test() {
		var merge,
			target,
			src1,
			src2,
			actual,
			expected;

		target = {};
		src1 = {
			'a': 'beep',
			'b': 'boop'
		};
		src2 = {
			'c': [ 1, 2, 3 ]
		};

		merge = createMergeFcn();

		actual = merge( target, src1, src2 );
		expected = {
			'a': 'beep',
			'b': 'boop',
			'c': [ 1, 2, 3 ]
		};

		assert.deepEqual( actual, expected );
	});

	it( 'should deep merge', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'c': {
				'a': 'beep',
				'b': 'boop'
			}
		};
		src = {
			'c': {
				'b': 'woot',
				'c': [ 1, 2, 3 ]
			}
		};

		merge = createMergeFcn();

		actual = merge( target, src );
		expected = {
			'c': {
				'a': 'beep',
				'b': 'woot',
				'c': [ 1, 2, 3 ]
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.c.c !== src.c.c );
	});

	it( 'should deep merge to an arbitrary depth', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'one': {
				'a': 'beep',
				'b': 'boop',
				'two': {
					'three': null,
					'c': [ 5, 6, 7 ]
				}
			}
		};
		src = {
			'one': {
				'b': 'woot',
				'two': {
					'three': [ 1, 2, 3 ]
				}
			}
		};

		merge = createMergeFcn({
			'level': 2
		});

		actual = merge( target, src );
		expected = {
			'one': {
				'a': 'beep',
				'b': 'woot',
				'two': src.one.two
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.one.two !== src.one.two );
	});

	it( 'should not perform a deep copy if instructed to not copy', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		// Simple case...
		target = {};

		src = {
			'a': [ 1, 2, 3 ]
		};

		merge = createMergeFcn({
			'copy': false
		});

		actual = merge( target, src );
		expected = {
			'a': src.a
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.a === src.a );

		// Deep merge...
		target = {
			'one': {
				'a': 'beep',
				'b': 'boop',
				'two': {
					'three': null,
					'c': [ 5, 6, 7 ]
				}
			}
		};
		src = {
			'one': {
				'b': 'woot',
				'two': {
					'three': [ 1, 2, 3 ]
				}
			}
		};

		merge = createMergeFcn({
			'level': 2,
			'copy': false
		});

		actual = merge( target, src );
		expected = {
			'one': {
				'a': 'beep',
				'b': 'woot',
				'two': src.one.two
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.one.two === src.one.two );
	});

	it( 'should not extend an object if instructed to not extend', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'a': 'woot'
		};
		src = {
			'a': 'beep',
			'b': 'boop'
		};

		merge = createMergeFcn({
			'extend': false
		});

		actual = merge( target, src );
		expected = {
			'a': 'beep'
		};

		assert.deepEqual( actual, expected );
	});

	it( 'should not override a property if instructed to not override', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'a': 'woot'
		};
		src = {
			'a': 'beep',
			'b': 'boop'
		};

		merge = createMergeFcn({
			'override': false
		});

		actual = merge( target, src );
		expected = {
			'a': 'woot',
			'b': 'boop'
		};

		assert.deepEqual( actual, expected );
	});

	it( 'should allow for a custom merge strategy (override)', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		function strategy( a, b, key ) {
			if ( typeof a === 'string' && typeof b === 'string' ) {
				return a + b;
			}
			if ( key === 'b' ) {
				return b.replace( /oo/, '00' );
			}
			if ( key === 'e' ) {
				return a;
			}
			return b;
		}

		target = {
			'a': 'woot',
			'b': null,
			'c': null
		};
		src = {
			'a': 'beep',
			'b': 'boop',
			'c': {
				'd': Math.PI
			}
		};

		merge = createMergeFcn({
			'override': strategy
		});

		actual = merge( target, src );
		expected = {
			'a': 'wootbeep',
			'b': 'b00p',
			'c': {
				'd': Math.PI
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.c !== src.c, 'simple case' );

		// No deep copies if provided existing value...
		target = {
			'a': 'woot',
			'b': null,
			'c': null,
			'e': {
				'f': true
			}
		};
		src = {
			'a': 'beep',
			'b': 'boop',
			'c': {
				'd': Math.PI
			},
			'e': null
		};

		merge = createMergeFcn({
			'override': strategy
		});

		actual = merge( target, src );
		expected = {
			'a': 'wootbeep',
			'b': 'b00p',
			'c': {
				'd': Math.PI
			},
			'e': target.e
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.e === target.e, 'existing value' );

		// No deep copies if copy is `false` and provided a new value...
		target = {
			'a': 'woot',
			'b': null,
			'c': null
		};
		src = {
			'a': 'beep',
			'b': 'boop',
			'c': {
				'd': Math.PI
			}
		};

		merge = createMergeFcn({
			'override': strategy,
			'copy': false
		});

		actual = merge( target, src );
		expected = {
			'a': 'wootbeep',
			'b': 'b00p',
			'c': {
				'd': Math.PI
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.c === src.c, 'no deep copies of new values' );
	});

});
<commit_msg>[TESTS] case where extend and override are both false.<commit_after>/* global describe, it, require */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Create deep copies:
	createCopy = require( 'utils-copy' ),

	// Module to be tested:
	createMergeFcn = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'utils-merge', function tests() {

	it( 'should export a function', function test() {
		expect( createMergeFcn ).to.be.a( 'function' );
	});

	it( 'should throw an error if provided a non-object options argument', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			true,
			[],
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( value );
			};
		}
	});

	it( 'should throw an error if provided a level option which is not a positive integer', function test() {
		var values = [
			'5',
			-5,
			Math.PI,
			0,
			null,
			NaN,
			undefined,
			true,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'level':value} );
			};
		}
	});

	it( 'should throw an error if provided a copy option which is not a boolean primitive', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			new Boolean( true ),
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'copy':value} );
			};
		}
	});

	it( 'should throw an error if provided an extend option which is not a boolean primitive', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			new Boolean( true ),
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'extend':value} );
			};
		}
	});

	it( 'should throw an error if provided an override option which is not either a boolean primitive or a function', function test() {
		var values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			new Boolean( true ),
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				createMergeFcn( {'override':value} );
			};
		}
	});

	it( 'should return a function', function test() {
		expect( createMergeFcn() ).to.be.a( 'function' );
	});

	it( 'should throw an error if provided insufficient arguments', function test() {
		var merge = createMergeFcn();
		expect( foo ).to.throw( Error );
		expect( bar ).to.throw( Error );
		function foo() {
			merge();
		}
		function bar() {
			merge( {} );
		}
	});

	it( 'should throw an error if provided a target which is not an object', function test() {
		var values, merge;

		values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			true,
			[],
			function(){}
		];

		merge = createMergeFcn();

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				merge( value, {} );
			};
		}
	});

	it( 'should throw an error if provided a source which is not an object', function test() {
		var values, merge;

		values = [
			'5',
			5,
			null,
			NaN,
			undefined,
			true,
			[],
			function(){}
		];

		merge = createMergeFcn();

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				merge( {}, value );
			};
		}
	});

	it( 'should merge two objects', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {};
		src = {
			'a': 'beep',
			'b': 'boop'
		};

		merge = createMergeFcn();

		actual = merge( target, src );
		expected = createCopy( src );

		assert.ok( actual !== src );
		assert.ok( actual === target );
		assert.deepEqual( actual, expected );
	});

	it( 'should merge multiple objects', function test() {
		var merge,
			target,
			src1,
			src2,
			actual,
			expected;

		target = {};
		src1 = {
			'a': 'beep',
			'b': 'boop'
		};
		src2 = {
			'c': [ 1, 2, 3 ]
		};

		merge = createMergeFcn();

		actual = merge( target, src1, src2 );
		expected = {
			'a': 'beep',
			'b': 'boop',
			'c': [ 1, 2, 3 ]
		};

		assert.deepEqual( actual, expected );
	});

	it( 'should deep merge', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'c': {
				'a': 'beep',
				'b': 'boop'
			}
		};
		src = {
			'c': {
				'b': 'woot',
				'c': [ 1, 2, 3 ]
			}
		};

		merge = createMergeFcn();

		actual = merge( target, src );
		expected = {
			'c': {
				'a': 'beep',
				'b': 'woot',
				'c': [ 1, 2, 3 ]
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.c.c !== src.c.c );
	});

	it( 'should deep merge to an arbitrary depth', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'one': {
				'a': 'beep',
				'b': 'boop',
				'two': {
					'three': null,
					'c': [ 5, 6, 7 ]
				}
			}
		};
		src = {
			'one': {
				'b': 'woot',
				'two': {
					'three': [ 1, 2, 3 ]
				}
			}
		};

		merge = createMergeFcn({
			'level': 2
		});

		actual = merge( target, src );
		expected = {
			'one': {
				'a': 'beep',
				'b': 'woot',
				'two': src.one.two
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.one.two !== src.one.two );
	});

	it( 'should not perform a deep copy if instructed to not copy', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		// Simple case...
		target = {};

		src = {
			'a': [ 1, 2, 3 ]
		};

		merge = createMergeFcn({
			'copy': false
		});

		actual = merge( target, src );
		expected = {
			'a': src.a
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.a === src.a );

		// Deep merge...
		target = {
			'one': {
				'a': 'beep',
				'b': 'boop',
				'two': {
					'three': null,
					'c': [ 5, 6, 7 ]
				}
			}
		};
		src = {
			'one': {
				'b': 'woot',
				'two': {
					'three': [ 1, 2, 3 ]
				}
			}
		};

		merge = createMergeFcn({
			'level': 2,
			'copy': false
		});

		actual = merge( target, src );
		expected = {
			'one': {
				'a': 'beep',
				'b': 'woot',
				'two': src.one.two
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.one.two === src.one.two );
	});

	it( 'should not extend an object if instructed to not extend', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'a': 'woot'
		};
		src = {
			'a': 'beep',
			'b': 'boop'
		};

		merge = createMergeFcn({
			'extend': false
		});

		actual = merge( target, src );
		expected = {
			'a': 'beep'
		};

		assert.deepEqual( actual, expected );
	});

	it( 'should not override a property if instructed to not override', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'a': 'woot'
		};
		src = {
			'a': 'beep',
			'b': 'boop'
		};

		merge = createMergeFcn({
			'override': false
		});

		actual = merge( target, src );
		expected = {
			'a': 'woot',
			'b': 'boop'
		};

		assert.deepEqual( actual, expected );
	});

	it( 'should allow for a custom merge strategy (override)', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		function strategy( a, b, key ) {
			if ( typeof a === 'string' && typeof b === 'string' ) {
				return a + b;
			}
			if ( key === 'b' ) {
				return b.replace( /oo/, '00' );
			}
			if ( key === 'e' ) {
				return a;
			}
			return b;
		}

		target = {
			'a': 'woot',
			'b': null,
			'c': null
		};
		src = {
			'a': 'beep',
			'b': 'boop',
			'c': {
				'd': Math.PI
			}
		};

		merge = createMergeFcn({
			'override': strategy
		});

		actual = merge( target, src );
		expected = {
			'a': 'wootbeep',
			'b': 'b00p',
			'c': {
				'd': Math.PI
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.c !== src.c, 'simple case' );

		// No deep copies if provided existing value...
		target = {
			'a': 'woot',
			'b': null,
			'c': null,
			'e': {
				'f': true
			}
		};
		src = {
			'a': 'beep',
			'b': 'boop',
			'c': {
				'd': Math.PI
			},
			'e': null
		};

		merge = createMergeFcn({
			'override': strategy
		});

		actual = merge( target, src );
		expected = {
			'a': 'wootbeep',
			'b': 'b00p',
			'c': {
				'd': Math.PI
			},
			'e': target.e
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.e === target.e, 'existing value' );

		// No deep copies if copy is `false` and provided a new value...
		target = {
			'a': 'woot',
			'b': null,
			'c': null
		};
		src = {
			'a': 'beep',
			'b': 'boop',
			'c': {
				'd': Math.PI
			}
		};

		merge = createMergeFcn({
			'override': strategy,
			'copy': false
		});

		actual = merge( target, src );
		expected = {
			'a': 'wootbeep',
			'b': 'b00p',
			'c': {
				'd': Math.PI
			}
		};

		assert.deepEqual( actual, expected );
		assert.ok( actual.c === src.c, 'no deep copies of new values' );
	});

	it( 'should return the target object if extend and override options are both false', function test() {
		var merge,
			target,
			src,
			actual,
			expected;

		target = {
			'a': 'beep'
		};

		src = {
			'a': 'boop',
			'b': 'woot'
		};

		merge = createMergeFcn({
			'extend': false,
			'override': false
		});

		actual = merge( target, src );
		expected = target;

		assert.deepEqual( actual, expected );
		assert.ok( actual === target );
	});

});
<|endoftext|>


<commit_before>var toAsciiMath = require('..');

var testCases = [
  // mathml input, expected asciimath output
  ['<math><mn>1</mn><mo>+</mo><mn>2</mn></math>', '1 + 2'],
  ['<math><mn>1</mn><mo>-</mo><mn>2</mn></math>', '1 - 2'],
  ['<math><mn>1</mn><mo>⋅</mo><mn>2</mn></math>', '1 * 2'],
  ['<math><mn>1</mn><mo>⋆</mo><mn>2</mn></math>', '1 ** 2'],
  ['<math><mn>1</mn><mo>×</mo><mn>2</mn></math>', '1 xx 2'],
  ['<math><mn>1</mn><mo>/</mo><mn>2</mn></math>', '1 // 2'],
  ['<math><mfrac><mn>1</mn><mn>2</mn></mfrac></math>', '1 / 2'],
  ['<math><mn>1</mn><mo>÷</mo><mn>2</mn></math>', '1 -: 2'],
  ['<math><mi>a</mi><mo>+</mo><mi>b</mi></math>', 'a + b'],
  ['<math><mn>1</mn><mo>+</mo><mi>b</mi></math>', '1 + b'],
  ['<math><msup><mi>a</mi><mn>2</mn></msup></math>', 'a ^ 2'],
  ['<math><msub><mi>x</mi><mn>1</mn></msub></math>', 'x _ 1'],
  ['<math><mi>a</mi><mo>+</mo><mn>3</mn><mo>=</mo><mn>4</mn></math>', 'a + 3 = 4'],
  ['<math><mfrac><mrow><mn>1</mn><mo>+</mo><mn>2</mn><mo>+</mo><mn>3</mn><mo>+</mo><mn>4</mn></mrow><mn>10</mn></mfrac></math>', '( 1 + 2 + 3 + 4 ) / 10'],
  ['<math><mrow><mo>(</mo><mi>x</mi><mo>+</mo><mn>1</mn><mo>)</mo></mrow></math>', '( x + 1 )'],
  ['<math><mfrac><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow><mn>4</mn></mfrac></math>', '( x + 1 ) / 4'],
  ['<math><mfrac><mrow><mn>1</mn><mo>+</mo><mn>2</mn><mo>+</mo><mn>3</mn><mo>+</mo><mn>4</mn></mrow><mrow><mn>10</mn><mo>+</mo><mi>a</mi><mo>+</mo><mi>b</mi></mrow></mfrac></math>', '( 1 + 2 + 3 + 4 ) / ( 10 + a + b )'],
  ['<math><mn>4</mn><mfrac><mn>2</mn><mn>3</mn></mfrac></math>', '4 2 / 3']
];

testCases.forEach(function(testCase) {
  var expected = testCase[1];

  exports[expected] = function(test) {
    var input = testCase[0];
    var output = toAsciiMath(input);

    test.equal(output, expected);
    test.done();
  };
});<commit_msg>tests for another kind of multiply<commit_after>var toAsciiMath = require('..');

var testCases = [
  // mathml input, expected asciimath output
  ['<math><mn>1</mn><mo>+</mo><mn>2</mn></math>', '1 + 2'],
  ['<math><mn>1</mn><mo>-</mo><mn>2</mn></math>', '1 - 2'],
  ['<math><mn>1</mn><mo>⋅</mo><mn>2</mn></math>', '1 * 2'],
  ['<math><mn>1</mn><mo>⋆</mo><mn>2</mn></math>', '1 ** 2'],
  ['<math><mn>1</mn><mo>×</mo><mn>2</mn></math>', '1 xx 2'],
  ['<math><mi>a</mi><mi>b</mi></math>', 'a b'],
  ['<math><mn>2</mn><mi>b</mi></math>', '2 b'],
  ['<math><mn>1</mn><mo>/</mo><mn>2</mn></math>', '1 // 2'],
  ['<math><mfrac><mn>1</mn><mn>2</mn></mfrac></math>', '1 / 2'],
  ['<math><mn>1</mn><mo>÷</mo><mn>2</mn></math>', '1 -: 2'],
  ['<math><mi>a</mi><mo>+</mo><mi>b</mi></math>', 'a + b'],
  ['<math><mn>1</mn><mo>+</mo><mi>b</mi></math>', '1 + b'],
  ['<math><msup><mi>a</mi><mn>2</mn></msup></math>', 'a ^ 2'],
  ['<math><msub><mi>x</mi><mn>1</mn></msub></math>', 'x _ 1'],
  ['<math><mi>a</mi><mo>+</mo><mn>3</mn><mo>=</mo><mn>4</mn></math>', 'a + 3 = 4'],
  ['<math><mfrac><mrow><mn>1</mn><mo>+</mo><mn>2</mn><mo>+</mo><mn>3</mn><mo>+</mo><mn>4</mn></mrow><mn>10</mn></mfrac></math>', '( 1 + 2 + 3 + 4 ) / 10'],
  ['<math><mrow><mo>(</mo><mi>x</mi><mo>+</mo><mn>1</mn><mo>)</mo></mrow></math>', '( x + 1 )'],
  ['<math><mfrac><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow><mn>4</mn></mfrac></math>', '( x + 1 ) / 4'],
  ['<math><mfrac><mrow><mn>1</mn><mo>+</mo><mn>2</mn><mo>+</mo><mn>3</mn><mo>+</mo><mn>4</mn></mrow><mrow><mn>10</mn><mo>+</mo><mi>a</mi><mo>+</mo><mi>b</mi></mrow></mfrac></math>', '( 1 + 2 + 3 + 4 ) / ( 10 + a + b )'],
  ['<math><mn>4</mn><mfrac><mn>2</mn><mn>3</mn></mfrac></math>', '4 2 / 3']
];

testCases.forEach(function(testCase) {
  var expected = testCase[1];

  exports[expected] = function(test) {
    var input = testCase[0];
    var output = toAsciiMath(input);

    test.equal(output, expected);
    test.done();
  };
});<|endoftext|>


<commit_before>(function() {

  'use strict';

  var grunt = require( 'grunt' );
  var fs = require( 'fs-extra' );

  exports['import-clean'] = {

    basic: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/basic.json' );
      var expected = grunt.file.read( 'test/basic/output.json' );
      test.equal( actual , expected , 'should describe basic behavior.' );

      test.done();
    },

    multi: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/multi.json' );
      var expected = grunt.file.read( 'test/multi/output.json' );
      test.equal( actual , expected , 'should describe multi behavior.' );

      test.done();
    },

    empty: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/multi.json' );
      var expected = grunt.file.read( 'test/multi/output.json' );
      test.equal( actual , expected , 'should describe empty behavior.' );

      test.done();
    },

    array: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/array.json' );
      var expected = grunt.file.read( 'test/array/output.json' );
      test.equal( actual , expected , 'should describe array behavior.' );

      test.done();
    }

  };

}());

<commit_msg>updating test.js<commit_after>(function() {

  'use strict';

  var grunt = require( 'grunt' );

  exports['import-clean'] = {

    basic: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/basic.json' );
      var expected = grunt.file.read( 'test/basic/output.json' );
      test.equal( actual , expected , 'should describe basic behavior.' );

      test.done();
    },

    multi: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/multi.json' );
      var expected = grunt.file.read( 'test/multi/output.json' );
      test.equal( actual , expected , 'should describe multi behavior.' );

      test.done();
    },

    empty: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/multi.json' );
      var expected = grunt.file.read( 'test/multi/output.json' );
      test.equal( actual , expected , 'should describe empty behavior.' );

      test.done();
    },

    array: function( test ) {

      test.expect( 1 );

      var actual = grunt.file.read( 'tmp/array.json' );
      var expected = grunt.file.read( 'test/array/output.json' );
      test.equal( actual , expected , 'should describe array behavior.' );

      test.done();
    }

  };

}());

<|endoftext|>


<commit_before>var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
var context;
var pluginContext;
var userColor = "#0033ff";
var userSize = 2;
var container;
var userImage;
var chatMsg = "";

function addClick(x, y, dragging)
{
  clickX.push(x);
  clickY.push(y);
  clickDrag.push(dragging);

  if(dragging!=true)
  {
	chatMsg = userColor+","+userSize+";";
  }
  else
  {
	chatMsg += x+","+y+";";
  }
}

function onStopDraw()
{
	paint=false;
	if(chatMsg.length>3)
	{
		pluginContext.addLine(chatMsg,pluginContext.channel+"#whiteboard");
	}
	chatMsg="";

	//context.closePath();
	context.stroke();
}

function clear()
{
	context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
}

function onStartDraw(x,y)
{
	context.strokeStyle = userColor;
	context.lineJoin = "round";
	context.lineWidth = userSize;

	context.beginPath();
	context.moveTo(x, y-1);
	context.lineTo(x, y);
}

function onDraw(x,y)
{
	context.lineTo(x, y);
	context.stroke();
}

function draw(style,join,width,data)
{
	if(context == null)
	{
		//TODO push cache & restore later
		return;
	}

	context.strokeStyle = style || "#000000";
	context.lineJoin = join || "round";
	context.lineWidth = width || 2;

	context.beginPath();
	for(var i=0; i < data.length; i++)
	{
		if(i==0)
		{
			context.moveTo(data[i][0]-1, data[i][1]);
		}
		context.lineTo(data[i][0], data[i][1]);
	}
	//context.closePath();
	context.stroke();
}

function placeImage(x,y)
{
	if(userImage!=null)
	{
		client.socket.emit('chat message', pluginContext.channel+"#whiteboard" + "|" + "#image,"+x+","+y+";"+userImage);
	}
	userImage=null;
}

function drawImage(src,x,y,w,h)
{
	var outlineImage = new Image();
	outlineImage.src = src;
	w = w || outlineImage.width;
	h = h || outlineImage.height;
	context.drawImage(outlineImage, x||0, y||0, w, h);
}

whiteboardChatPluginInit = function(pcontext)
{
	pluginContext = pcontext;
	log("WB init! context:"+pluginContext);

	var whiteboardID = "#whiteboard";
	var canvas;

	if(context!=null)
	{
		canvas = document.getElementById(whiteboardID.substring(1));
		$(container).show();
	}
	else
	{
		var h = $(window).height();
		var w = $(window).width();
		var headerSize = 80;
		var usersPanelSize = 155;
		var wbWidth = w-usersPanelSize;
		var wbHeight = h-headerSize;

		container = document.createElement("div");
		container.id = "whiteboard-container";
		container.style.display = "block";
		container.style.width = wbWidth;
		container.style.height = wbHeight;
		container.style.position = "fixed";
		container.style.top = headerSize+"px";
		container.style.left = usersPanelSize+"px";
		container.style.borderLeft = "5px solid #000";
		container.style.background = "#fff";
		container.style.zIndex = 2;

		var toolsPanelSize = 32;
		var tools = document.createElement("div");
		tools.style.border = "1px solid #eee";
		tools.style.background = "#eee";
		tools.style.display = "block";
		tools.style.width = "100%";
		tools.style.height = toolsPanelSize;

		var addLabel = function(label)
		{
			var btn = document.createElement("div");
			btn.className = "label label-info";
			btn.innerHTML = label;
			tools.appendChild(btn);
		};

		var addButton = function(btnText)
		{
			var btn = document.createElement("button");
			btn.className = "btn btn-default btn-xs";
			btn.innerHTML = "

";
			btn.setAttribute("userColor",btnText);
			$(btn).click(function()
			{
				userColor = this.getAttribute("userColor");
				log(userColor);
			});
			tools.appendChild(btn);
		};

		var addSizeButton = function(size)
		{
			var btn = document.createElement("button");
			btn.className = "btn btn-default btn-xs";
			btn.innerHTML = size;
			btn.setAttribute("userSize",size);
			$(btn).click(function()
			{
				userSize = this.getAttribute("userSize");
				log(userSize);
			});
			tools.appendChild(btn);
		};
		addLabel("Color");
		addButton("#000000");
		addButton("#ffffff");
		addButton("#666666");
		addButton("#ff0000");
		addButton("#00ff00");
		addButton("#0000ff");
		addButton("#00ffff");
		addButton("#ffff00");
		addButton("#ff00ff");

		addLabel("Size");
		addSizeButton(1);
		for(var i = 2; i<=10; i++)
		{
			addSizeButton(i*i);
		}

		canvas = document.createElement("canvas");
		canvas.id=whiteboardID.substring(1);
		canvas.setAttribute("width",wbWidth);
		canvas.setAttribute("height",wbHeight-toolsPanelSize);
		canvas.style.width = wbWidth;
		canvas.style.height = wbHeight;

		document.body.appendChild(container);
		container.appendChild(tools);
		container.appendChild(canvas);

		context = canvas.getContext("2d");
	}

	$(whiteboardID).mousedown(function(e)
	{
		if(userImage!=null)
		{
			placeImage(e.pageX-usersPanelSize-4, e.pageY-headerSize-toolsPanelSize+10);
			return;
		}

		paint = true;
		addClick(e.pageX-usersPanelSize-4, e.pageY-headerSize-toolsPanelSize+10);
		onStartDraw(e.pageX-usersPanelSize-4, e.pageY-headerSize-toolsPanelSize+10);
	});

	$(whiteboardID).mousemove(function(e)
	{
		if(paint)
		{
			addClick(e.pageX-usersPanelSize-4, e.pageY-headerSize-toolsPanelSize+10,true);
			onDraw(e.pageX-usersPanelSize-4, e.pageY-headerSize-toolsPanelSize+10);
		}
	});

	$(whiteboardID).mouseup(function(e){onStopDraw();});
	$(whiteboardID).mouseleave(function(e){onStopDraw();});

	pluginContext.onClose = function()
	{
		paint=false;
		$(container).hide();
	};
	pluginContext.onAddLine = function(time, who, what,marker,channel)
	{
		if(channel!=pluginContext.channel+"#whiteboard") return false;

		var data = what.split(";");
		var output = [];

		//Verify that we have proper data
		var type = data.shift().split(",");
		if(type[0][0]!="#") return false;

		if(type[0]=="#image")
		{
			drawImage(data.join(";"),type[1],type[2]);
			return;
		}

		var color = type[0];
		var size = type[1];

		for	(var i =0; i<data.length; i++)
		{
			var values = data[i].split(",");
			output.push([parseInt(values[0]),parseInt(values[1])]);
		}
		draw(color,null,size,output);
		return true;
	};

	var history = pluginContext.history;
	if(history!=null)
	{
		for(var index in history)
		{
			pluginContext.onAddLine(
				history[index][0],
				history[index][1],
				history[index][2],
				history[index][3],
				pluginContext.channel+"#whiteboard"
			);
		}
	}

	document.onpaste = function(event)
	{
		var items = (event.clipboardData || event.originalEvent.clipboardData).items;
		var blob = items[0].getAsFile();
		var reader = new FileReader();
		reader.onload = function(event)
		{
			userImage = event.target.result;
		};
		reader.readAsDataURL(blob);
	}
}<commit_msg>cursor fix<commit_after>var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
var context;
var pluginContext;
var userColor = "#000000";
var userSize = 2;
var container;
var userImage;
var chatMsg = "";

function initValues()
{
	clickX = new Array();
	clickY = new Array();
	clickDrag = new Array();
	paint = false;
	context = null;
	pluginContext = null;
	userColor = "#000000";
	userSize = 2;
	container = null;
	userImage = null;
	chatMsg = "";
}

function addClick(x, y, dragging)
{
  clickX.push(x);
  clickY.push(y);
  clickDrag.push(dragging);

  if(dragging!=true)
  {
	chatMsg = userColor+","+userSize+";";
  }
  else
  {
	chatMsg += x+","+y+";";
  }
}

function onStopDraw()
{
	paint=false;
	if(chatMsg.length>3)
	{
		pluginContext.addLine(chatMsg,pluginContext.channel+"#whiteboard");
	}
	chatMsg="";

	//context.closePath();
	context.stroke();
}

function clear()
{
	context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
}

function onStartDraw(x,y)
{
	context.strokeStyle = userColor;
	context.lineJoin = "round";
	context.lineWidth = userSize;

	context.beginPath();
	context.moveTo(x, y-1);
	context.lineTo(x, y);
}

function onDraw(x,y)
{
	context.lineTo(x, y);
	context.stroke();
}

function draw(style,join,width,data)
{
	if(context == null)
	{
		//TODO push cache & restore later
		return;
	}

	context.strokeStyle = style || "#000000";
	context.lineJoin = join || "round";
	context.lineWidth = width || 2;

	context.beginPath();
	for(var i=0; i < data.length; i++)
	{
		if(i==0)
		{
			context.moveTo(data[i][0]-1, data[i][1]);
		}
		context.lineTo(data[i][0], data[i][1]);
	}
	//context.closePath();
	context.stroke();
}

function placeImage(x,y)
{
	if(userImage!=null)
	{
		client.socket.emit('chat message', pluginContext.channel+"#whiteboard" + "|" + "#image,"+x+","+y+";"+userImage);
	}
	userImage=null;
}

function drawImage(src,x,y,w,h)
{
	var outlineImage = new Image();
	outlineImage.src = src;
	w = w || outlineImage.width;
	h = h || outlineImage.height;
	context.drawImage(outlineImage, x||0, y||0, w, h);
}

whiteboardChatPluginInit = function(pcontext)
{
	pluginContext = pcontext;
	log("WB init! context:"+pluginContext);

	var whiteboardID = "#whiteboard";
	var canvas;

	if(context!=null)
	{
		canvas = document.getElementById(whiteboardID.substring(1));
		$(container).show();
	}
	else
	{
		var h = $(window).height();
		var w = $(window).width();
		var headerSize = 80;
		var usersPanelSize = 155;
		var wbWidth = w-usersPanelSize;
		var wbHeight = h-headerSize;

		container = document.createElement("div");
		container.id = "whiteboard-container";
		container.style.display = "block";
		container.style.width = wbWidth;
		container.style.height = wbHeight;
		container.style.position = "fixed";
		container.style.top = headerSize+"px";
		container.style.left = usersPanelSize+"px";
		container.style.borderLeft = "5px solid #000";
		container.style.background = "#fff";
		container.style.zIndex = 2;

		var tools = document.createElement("div");
		tools.style.border = "1px solid #eee";
		tools.style.background = "#eee";
		tools.style.display = "block";
		tools.style.width = "100%";

		var addLabel = function(label)
		{
			var btn = document.createElement("div");
			btn.className = "label label-info";
			btn.innerHTML = label;
			tools.appendChild(btn);
		};

		var addButton = function(btnText)
		{
			var btn = document.createElement("button");
			btn.className = "btn btn-default btn-xs";
			btn.innerHTML = "

";
			btn.setAttribute("userColor",btnText);
			$(btn).click(function()
			{
				userColor = this.getAttribute("userColor");
				log(userColor);
			});
			tools.appendChild(btn);
		};

		var addSizeButton = function(size)
		{
			var btn = document.createElement("button");
			btn.className = "btn btn-default btn-xs";
			btn.innerHTML = size;
			btn.setAttribute("userSize",size);
			$(btn).click(function()
			{
				userSize = this.getAttribute("userSize");
				log(userSize);
			});
			tools.appendChild(btn);
		};
		addLabel("Color");
		addButton("#000000");
		addButton("#ffffff");
		addButton("#666666");
		addButton("#ff0000");
		addButton("#00ff00");
		addButton("#0000ff");
		addButton("#00ffff");
		addButton("#ffff00");
		addButton("#ff00ff");

		addLabel("Size");
		addSizeButton(1);
		for(var i = 2; i<=10; i++)
		{
			addSizeButton(i*i);
		}

		var toolsPanelSize = $(tools).height();

		canvas = document.createElement("canvas");
		canvas.id=whiteboardID.substring(1);
		canvas.setAttribute("width",wbWidth);
		canvas.setAttribute("height",wbHeight-toolsPanelSize);
		canvas.style.width = wbWidth;
		canvas.style.height = wbHeight;
		canvas.style.cursor = "crosshair";

		document.body.appendChild(container);
		container.appendChild(tools);
		container.appendChild(canvas);

		context = canvas.getContext("2d");
	}

	var offSetX = -usersPanelSize-4;
	var offSetY = -headerSize-toolsPanelSize-22;

	$(whiteboardID).mousedown(function(e)
	{
		if(userImage!=null)
		{
			placeImage(e.pageX+offSetX, e.pageY+offSetY);
			return;
		}

		paint = true;
		addClick(e.pageX+offSetX, e.pageY+offSetY);
		onStartDraw(e.pageX+offSetX, e.pageY+offSetY);
	});

	$(whiteboardID).mousemove(function(e)
	{
		if(paint)
		{
			addClick(e.pageX+offSetX, e.pageY+offSetY,true);
			onDraw(e.pageX+offSetX, e.pageY+offSetY);
		}
	});

	$(whiteboardID).mouseup(function(e){onStopDraw();});
	$(whiteboardID).mouseleave(function(e){onStopDraw();});

	pluginContext.onClose = function()
	{
		paint=false;
		$(container).hide();
		$(container).remove();
		initValues();
	};
	pluginContext.onAddLine = function(time, who, what,marker,channel)
	{
		if(channel!=pluginContext.channel+"#whiteboard") return false;

		var data = what.split(";");
		var output = [];

		//Verify that we have proper data
		var type = data.shift().split(",");
		if(type[0][0]!="#") return false;

		if(type[0]=="#image")
		{
			drawImage(data.join(";"),type[1],type[2]);
			return;
		}

		var color = type[0];
		var size = type[1];

		for	(var i =0; i<data.length; i++)
		{
			var values = data[i].split(",");
			output.push([parseInt(values[0]),parseInt(values[1])]);
		}
		draw(color,null,size,output);
		return true;
	};

	var history = pluginContext.history;
	if(history!=null)
	{
		for(var index in history)
		{
			pluginContext.onAddLine(
				history[index][0],
				history[index][1],
				history[index][2],
				history[index][3],
				pluginContext.channel+"#whiteboard"
			);
		}
	}

	document.onpaste = function(event)
	{
		var items = (event.clipboardData || event.originalEvent.clipboardData).items;
		var blob = items[0].getAsFile();
		var reader = new FileReader();
		reader.onload = function(event)
		{
			userImage = event.target.result;
		};
		reader.readAsDataURL(blob);
	}
}<|endoftext|>


<commit_before>'use strict';

function percent(value, max){
    return ((value / max) * 100).toFixed(7) + '%';
}

function play(selected){
    core_storage_save();

    // Check how many games player wants to play.
    if(core_storage_data['repeat'] < 1
      || isNaN(core_storage_data['repeat'])){
        return;
    }

    // Keep track of results.
    var opponent_plays = [
      0,
      0,
      0,
    ];
    var results = [
      0,
      0,
      0,
    ];
    total += core_storage_data['repeat'];

    // Loop through the games.
    var loop_counter = core_storage_data['repeat'] - 1;
    do{
        // Result is a loss by default.
        var result = 0;

        // Generate a random number (0, 1, or 2).
        opponent_choice = core_random_integer({
          'max': 3,
        });
        opponent_plays[opponent_choice] += 1;

        // Check for ties.
        if(selected === opponent_choice){
            result = 2;

        // Check for wins.
        }else if((selected === 0 && opponent_choice === 2)
          || (selected === 1 && opponent_choice === 0)
          || (selected === 2 && opponent_choice === 1)){
            result = 1;
        }

        // Update loss/tie/win values and store them in a temporary array.
        results[result] += 1;
    }while(loop_counter--);

    losses += results[0];
    ties += results[2];
    wins += results[1];

    // Create result strings.
    var paper = opponent_plays[1] + ' papers (';
    var rock = opponent_plays[0] + ' rocks (';
    var scissors = opponent_plays[2] + ' scissors (';

    if(selected === 0){
        paper += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        rock += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        scissors += 'wins) ' + percent(results[1], core_storage_data['repeat']);

    }else if(selected === 1){
        paper += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        rock += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        scissors += 'losses) ' + percent(results[0], core_storage_data['repeat']);

    }else{
        paper += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        rock += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        scissors += 'ties) ' + percent(results[2], core_storage_data['repeat']);
    }

    // Display game information.
    document.getElementById('opponent').innerHTML = 'You played '
      + ['rock', 'paper', 'scissors',][selected]
      + ' ' + core_storage_data['repeat'] + ' times.
'
      + 'Your opponent played:
'
        + rock + '
'
        + paper + '
'
        + scissors;
    document.getElementById('player').innerHTML =
      total + ' total games played
'
        + losses + ' losses (' + percent(losses, total) + ')
'
        + ties + ' ties (' + percent(ties, total) + ')
'
        + wins + ' wins (' + percent(wins, total) + ')';
}

function repo_init(){
    core_repo_init({
      'storage': {
        'repeat': 1,
      },
      'title': 'RockPaperScissors.htm',
    });
    core_events_bind({
      'keybinds': {
        80: {
          'todo': function(){
              play(1);
          },
        },
        82: {
          'todo': function(){
              play(0);
          },
        },
        83: {
          'todo': function(){
              play(2);
          },
        },
      },
    });

    core_storage_update();

    document.getElementById('paper').onclick = function(){
        play(1);
    };
    document.getElementById('reset').onclick = reset;
    document.getElementById('rock').onclick = function(){
        play(0);
    };
    document.getElementById('scissors').onclick = function(){
        play(2);
    };
}

function reset(){
    if(!core_storage_reset()){
        return;
    }

    document.getElementById('opponent').innerHTML = '';
    document.getElementById('player').innerHTML = '';

    losses = 0;
    ties = 0;
    total = 0;
    wins = 0;
}

var losses = 0;
var opponent_choice = 0;
var selected = 0;
var ties = 0;
var total = 0;
var wins = 0;
<commit_msg>added keybinds/mousebinds args to core_repo_init()<commit_after>'use strict';

function percent(value, max){
    return ((value / max) * 100).toFixed(7) + '%';
}

function play(selected){
    core_storage_save();

    // Check how many games player wants to play.
    if(core_storage_data['repeat'] < 1
      || isNaN(core_storage_data['repeat'])){
        return;
    }

    // Keep track of results.
    var opponent_plays = [
      0,
      0,
      0,
    ];
    var results = [
      0,
      0,
      0,
    ];
    total += core_storage_data['repeat'];

    // Loop through the games.
    var loop_counter = core_storage_data['repeat'] - 1;
    do{
        // Result is a loss by default.
        var result = 0;

        // Generate a random number (0, 1, or 2).
        opponent_choice = core_random_integer({
          'max': 3,
        });
        opponent_plays[opponent_choice] += 1;

        // Check for ties.
        if(selected === opponent_choice){
            result = 2;

        // Check for wins.
        }else if((selected === 0 && opponent_choice === 2)
          || (selected === 1 && opponent_choice === 0)
          || (selected === 2 && opponent_choice === 1)){
            result = 1;
        }

        // Update loss/tie/win values and store them in a temporary array.
        results[result] += 1;
    }while(loop_counter--);

    losses += results[0];
    ties += results[2];
    wins += results[1];

    // Create result strings.
    var paper = opponent_plays[1] + ' papers (';
    var rock = opponent_plays[0] + ' rocks (';
    var scissors = opponent_plays[2] + ' scissors (';

    if(selected === 0){
        paper += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        rock += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        scissors += 'wins) ' + percent(results[1], core_storage_data['repeat']);

    }else if(selected === 1){
        paper += 'ties) ' + percent(results[2], core_storage_data['repeat']);
        rock += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        scissors += 'losses) ' + percent(results[0], core_storage_data['repeat']);

    }else{
        paper += 'wins) ' + percent(results[1], core_storage_data['repeat']);
        rock += 'losses) ' + percent(results[0], core_storage_data['repeat']);
        scissors += 'ties) ' + percent(results[2], core_storage_data['repeat']);
    }

    // Display game information.
    document.getElementById('opponent').innerHTML = 'You played '
      + ['rock', 'paper', 'scissors',][selected]
      + ' ' + core_storage_data['repeat'] + ' times.
'
      + 'Your opponent played:
'
        + rock + '
'
        + paper + '
'
        + scissors;
    document.getElementById('player').innerHTML =
      total + ' total games played
'
        + losses + ' losses (' + percent(losses, total) + ')
'
        + ties + ' ties (' + percent(ties, total) + ')
'
        + wins + ' wins (' + percent(wins, total) + ')';
}

function repo_init(){
    core_repo_init({
      'keybinds': {
        80: {
          'todo': function(){
              play(1);
          },
        },
        82: {
          'todo': function(){
              play(0);
          },
        },
        83: {
          'todo': function(){
              play(2);
          },
        },
      },
      'storage': {
        'repeat': 1,
      },
      'title': 'RockPaperScissors.htm',
    });

    core_storage_update();

    document.getElementById('paper').onclick = function(){
        play(1);
    };
    document.getElementById('reset').onclick = reset;
    document.getElementById('rock').onclick = function(){
        play(0);
    };
    document.getElementById('scissors').onclick = function(){
        play(2);
    };
}

function reset(){
    if(!core_storage_reset()){
        return;
    }

    document.getElementById('opponent').innerHTML = '';
    document.getElementById('player').innerHTML = '';

    losses = 0;
    ties = 0;
    total = 0;
    wins = 0;
}

var losses = 0;
var opponent_choice = 0;
var selected = 0;
var ties = 0;
var total = 0;
var wins = 0;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var a = require( "assert" ),
    parse = require( "./../lib/argsparser" ).parse,
    sys = require( "sys" );

sys.print( "Run tests...\n" );

a.deepEqual( parse(), {node: __filename}, "node script.js" );

a.deepEqual( parse(["-o"]), {"-o": true}, "node script.js -o" );

a.deepEqual( parse(["-o", "true"]), {"-o": true}, "node script.js -o true" );

a.deepEqual( parse(["-o", "false"]), {"-o": false}, "node script.js -o false" );

a.deepEqual( parse(["-o", "123"]), {"-o": 123}, "node script.js -o 123" );

a.deepEqual( parse(["-o", "123.456"]), {"-o": 123.456}, "node script.js -o 123.456" );

a.deepEqual( parse(["-o", "test"]), {"-o": "test"}, "node script.js -o test" );

a.deepEqual( parse(["-a", "testa", "-b", "testb"]), {"-a": "testa", "-b": "testb"}, "node script.js -a testa -b testb" );

a.deepEqual( parse(["--a", "testa", "--b", "testb"]), {"--a": "testa", "--b": "testb"}, "node script.js --a testa --b testb " );

a.deepEqual( parse(["-a", "testa", "--b", "testb"]), {"-a": "testa", "--b": "testb"}, "node script.js -a testa --b testb" );

a.deepEqual( parse(["--a", "testa", "-b", "testb"]), {"--a": "testa", "-b": "testb"}, "node script.js --a testa -b testb" );

a.deepEqual( parse(["-paths", "/test.js", "/test1.js"]), {"-paths": ["/test.js", "/test1.js"]}, "node script.js -paths /test.js /test1.js" );

a.deepEqual( parse(["--paths", "/test.js", "/test1.js"]), {"--paths": ["/test.js", "/test1.js"]}, "node script.js --paths /test.js /test1.js" );

a.deepEqual( parse(["--paths", "/test.js", "/test1.js", "-a", "testa"]), {"--paths": ["/test.js", "/test1.js"], "-a": "testa"}, "node script.js --paths /test.js /test1.js -a testa" );

sys.print( "All tests ok\n" );
<commit_msg>rename sys to util<commit_after>#!/usr/bin/env node

var a = require( "assert" ),
    parse = require( "./../lib/argsparser" ).parse,
    util = require( "util" );

util.print( "Run tests...\n" );

a.deepEqual( parse(), {node: __filename}, "node script.js" );

a.deepEqual( parse(["-o"]), {"-o": true}, "node script.js -o" );

a.deepEqual( parse(["-o", "true"]), {"-o": true}, "node script.js -o true" );

a.deepEqual( parse(["-o", "false"]), {"-o": false}, "node script.js -o false" );

a.deepEqual( parse(["-o", "123"]), {"-o": 123}, "node script.js -o 123" );

a.deepEqual( parse(["-o", "123.456"]), {"-o": 123.456}, "node script.js -o 123.456" );

a.deepEqual( parse(["-o", "test"]), {"-o": "test"}, "node script.js -o test" );

a.deepEqual( parse(["-a", "testa", "-b", "testb"]), {"-a": "testa", "-b": "testb"}, "node script.js -a testa -b testb" );

a.deepEqual( parse(["--a", "testa", "--b", "testb"]), {"--a": "testa", "--b": "testb"}, "node script.js --a testa --b testb " );

a.deepEqual( parse(["-a", "testa", "--b", "testb"]), {"-a": "testa", "--b": "testb"}, "node script.js -a testa --b testb" );

a.deepEqual( parse(["--a", "testa", "-b", "testb"]), {"--a": "testa", "-b": "testb"}, "node script.js --a testa -b testb" );

a.deepEqual( parse(["-paths", "/test.js", "/test1.js"]), {"-paths": ["/test.js", "/test1.js"]}, "node script.js -paths /test.js /test1.js" );

a.deepEqual( parse(["--paths", "/test.js", "/test1.js"]), {"--paths": ["/test.js", "/test1.js"]}, "node script.js --paths /test.js /test1.js" );

a.deepEqual( parse(["--paths", "/test.js", "/test1.js", "-a", "testa"]), {"--paths": ["/test.js", "/test1.js"], "-a": "testa"}, "node script.js --paths /test.js /test1.js -a testa" );

util.print( "All tests ok\n" );
<|endoftext|>


<commit_before>KiddoPaint.Tools.Toolbox.Pencil = function() {
    this.size = 7;
    this.spacing = 10;
    this.texture = function() {
        return KiddoPaint.Textures.Solid(KiddoPaint.Current.color);
    };

    this.mousedown = function(ev) {
        KiddoPaint.Current.modifiedToggle ? KiddoPaint.Tools.LinePencil.mousedown(ev) : KiddoPaint.Tools.PixelPencil.mousedown(ev);
    };

    this.mousemove = function(ev) {
        KiddoPaint.Current.modifiedToggle ? KiddoPaint.Tools.LinePencil.mousemove(ev) : KiddoPaint.Tools.PixelPencil.mousemove(ev);
    };

    this.mouseup = function(ev) {
        KiddoPaint.Current.modifiedToggle ? KiddoPaint.Tools.LinePencil.mouseup(ev) : KiddoPaint.Tools.PixelPencil.mouseup(ev);
    };
};
KiddoPaint.Tools.Pencil = new KiddoPaint.Tools.Toolbox.Pencil();

KiddoPaint.Tools.Toolbox.PixelPencil = function() {
    var tool = this;
    this.isDown = false;
    this.size = function() {
        return KiddoPaint.Tools.Pencil.size;
    }
    this.previousEv = null;
    this.spacing = 10;
    this.texture = function() {
        return KiddoPaint.Tools.Pencil.texture();
    };

    this.mousedown = function(ev) {
        tool.isDown = true;
        tool.mousemove(ev);
        tool.previousEv = ev;
    };

    this.mousemove = function(ev) {
        var ctx = tool.isDown ? KiddoPaint.Display.context : KiddoPaint.Display.previewContext;
        ctx.fillStyle = tool.texture();
        if (KiddoPaint.Current.modifiedAlt) {
            ev._x = ev._x - (ev._x % (tool.size() * KiddoPaint.Current.scaling));
            ev._y = ev._y - (ev._y % (tool.size() * KiddoPaint.Current.scaling));
        }
        if (tool.previousEv == null || distanceBetween(tool.previousEv, ev) < tool.spacing) {
            ctx.fillRect(Math.round(ev._x), Math.round(ev._y), tool.size() * KiddoPaint.Current.scaling, tool.size() * KiddoPaint.Current.scaling);
        } else {
            bresenham(tool.previousEv._x, tool.previousEv._y, ev._x, ev._y, function(x, y) {
                ctx.fillRect(Math.round(ev._x), Math.round(ev._y), tool.size() * KiddoPaint.Current.scaling, tool.size() * KiddoPaint.Current.scaling);
            });
        }
        tool.previousEv = ev;
    };

    this.mouseup = function(ev) {
        if (tool.isDown) {
            tool.mousemove(ev);
            tool.isDown = false;
            tool.previousEv = null;
            KiddoPaint.Display.saveMain();
        }
    };
};

KiddoPaint.Tools.PixelPencil = new KiddoPaint.Tools.Toolbox.PixelPencil();

KiddoPaint.Tools.Toolbox.LinePencil = function() {
    var tool = this;
    this.isDown = false;
    this.size = function() {
        return KiddoPaint.Tools.Pencil.size;
    }
    this.texture = function() {
        return KiddoPaint.Tools.Pencil.texture();
    };

    this.mousedown = function(ev) {
        tool.isDown = true;
        KiddoPaint.Display.context.beginPath();
        KiddoPaint.Display.context.strokeStyle = tool.texture();
        KiddoPaint.Display.context.lineWidth = tool.size();
        KiddoPaint.Display.context.lineCap = 'round';
        KiddoPaint.Display.context.lineJoin = 'round';
        KiddoPaint.Display.context.moveTo(ev._x, ev._y);
    };

    this.mousemove = function(ev) {
        if (tool.isDown) {
            KiddoPaint.Display.context.lineTo(ev._x, ev._y);
            KiddoPaint.Display.context.stroke();
        }
    };

    this.mouseup = function(ev) {
        if (tool.isDown) {
            tool.mousemove(ev);
            KiddoPaint.Display.context.closePath();
            tool.isDown = false;
            KiddoPaint.Display.saveMain();
        }
    };
};
KiddoPaint.Tools.LinePencil = new KiddoPaint.Tools.Toolbox.LinePencil();<commit_msg>Mouse wheel pencil size control.<commit_after>KiddoPaint.Tools.Toolbox.Pencil = function() {
    this.size = 7;
    this.spacing = 10;
    this.texture = function() {
        return KiddoPaint.Textures.Solid(KiddoPaint.Current.color);
    };

    this.mousedown = function(ev) {
        KiddoPaint.Current.modifiedToggle ? KiddoPaint.Tools.LinePencil.mousedown(ev) : KiddoPaint.Tools.PixelPencil.mousedown(ev);
    };

    this.mousemove = function(ev) {
        KiddoPaint.Current.modifiedToggle ? KiddoPaint.Tools.LinePencil.mousemove(ev) : KiddoPaint.Tools.PixelPencil.mousemove(ev);
    };

    this.mouseup = function(ev) {
        KiddoPaint.Current.modifiedToggle ? KiddoPaint.Tools.LinePencil.mouseup(ev) : KiddoPaint.Tools.PixelPencil.mouseup(ev);
    };
};
KiddoPaint.Tools.Pencil = new KiddoPaint.Tools.Toolbox.Pencil();

KiddoPaint.Tools.Toolbox.PixelPencil = function() {
    var tool = this;
    this.isDown = false;
    this.size = function() {
        return KiddoPaint.Tools.Pencil.size * (1 + KiddoPaint.Current.modifiedRange / 100.0);
    }
    this.previousEv = null;
    this.spacing = 10;
    this.texture = function() {
        return KiddoPaint.Tools.Pencil.texture();
    };

    this.mousedown = function(ev) {
        tool.isDown = true;
        tool.mousemove(ev);
        tool.previousEv = ev;
    };

    this.mousemove = function(ev) {
        var ctx = tool.isDown ? KiddoPaint.Display.context : KiddoPaint.Display.previewContext;
        ctx.fillStyle = tool.texture();
        if (KiddoPaint.Current.modifiedAlt) {
            ev._x = ev._x - (ev._x % (tool.size()));
            ev._y = ev._y - (ev._y % (tool.size()));
        }
        if (tool.previousEv == null || distanceBetween(tool.previousEv, ev) < tool.spacing) {
            ctx.fillRect(Math.round(ev._x), Math.round(ev._y), tool.size(), tool.size());
        } else {
            bresenham(tool.previousEv._x, tool.previousEv._y, ev._x, ev._y, function(x, y) {
                ctx.fillRect(Math.round(ev._x), Math.round(ev._y), tool.size(), tool.size());
            });
        }
        tool.previousEv = ev;
    };

    this.mouseup = function(ev) {
        if (tool.isDown) {
            tool.mousemove(ev);
            tool.isDown = false;
            tool.previousEv = null;
            KiddoPaint.Display.saveMain();
        }
    };
};

KiddoPaint.Tools.PixelPencil = new KiddoPaint.Tools.Toolbox.PixelPencil();

KiddoPaint.Tools.Toolbox.LinePencil = function() {
    var tool = this;
    this.isDown = false;
    this.size = function() {
        return KiddoPaint.Tools.Pencil.size * (1 + KiddoPaint.Current.modifiedRange / 100.0);
    }

    this.texture = function() {
        return KiddoPaint.Tools.Pencil.texture();
    };

    this.mousedown = function(ev) {
        tool.isDown = true;
        KiddoPaint.Display.context.beginPath();
        KiddoPaint.Display.context.strokeStyle = tool.texture();
        KiddoPaint.Display.context.lineWidth = tool.size();
        KiddoPaint.Display.context.lineCap = 'round';
        KiddoPaint.Display.context.lineJoin = 'round';
        KiddoPaint.Display.context.moveTo(ev._x, ev._y);
    };

    this.mousemove = function(ev) {
        if (tool.isDown) {
            KiddoPaint.Display.context.lineTo(ev._x, ev._y);
            KiddoPaint.Display.context.stroke();
        }
    };

    this.mouseup = function(ev) {
        if (tool.isDown) {
            tool.mousemove(ev);
            KiddoPaint.Display.context.closePath();
            tool.isDown = false;
            KiddoPaint.Display.saveMain();
        }
    };
};
KiddoPaint.Tools.LinePencil = new KiddoPaint.Tools.Toolbox.LinePencil();<|endoftext|>


<commit_before>/*
======== A Handy Little QUnit Reference ========
  http://api.qunitjs.com/

  Test methods:
    module(name, {[beforeEach][, afterEach]})
    test(name, callback)
  Test assertions:
    expect(numberOfAssertions)
    async()
    ok(value, [message])
    notOk(value, [message])
    equal(actual, expected, [message])
    notEqual(actual, expected, [message])
    deepEqual(actual, expected, [message])
    notDeepEqual(actual, expected, [message])
    strictEqual(actual, expected, [message])
    notStrictEqual(actual, expected, [message])
    throws(block, [expected], [message])
*/

(function (window, document, QUnit, $, sinon) {

    QUnit.module('basics', {
        beforeEach: function() {
            this.elems = $('#qunit-fixture').children();
        }
    });

    QUnit.test('is chainable', function (assert) {
        assert.expect(1);
        // Not a bad test to run on collection methods.
        assert.strictEqual(this.elems.formDialog(), this.elems, 'should be chainable');
    });

    QUnit.module('buttons');

    QUnit.test('button properties', function (assert) {
        assert.expect(3);

        var element = $('

').formDialog(),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.equal(btn.length, 2, 'dialog should have 2 buttons');
        assert.equal(btn.eq(0).text(), 'Save', 'submit button should be named "Save"');
        assert.equal(btn.eq(1).text(), 'Cancel', 'abort button should be named "Cancel"');
    });

    QUnit.test('custom button label', function (assert) {
        assert.expect(1);

        var element = $('

').formDialog({ actionLabel: 'FizzBuzz' }),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.equal(btn.eq(0).text(), 'FizzBuzz', 'submit button should have custom label');
    });

    QUnit.test('translate button label', function (assert) {
        assert.expect(2);

        var element = $('

').formDialog({ language: 'de' }),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.equal(btn.eq(0).text(), 'Speichern', 'submit button label should be translated');
        assert.equal(btn.eq(1).text(), 'Abbrechen', 'abort button label should be translated');
    });

    QUnit.test('cancel button', function (assert) {
        assert.expect(2);

        var element = $('

').formDialog({ autoOpen: true }),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.ok(element.dialog('isOpen'), 'dialog should be open');
        btn.eq(1).trigger('click');
        assert.notOk(element.dialog('isOpen'), 'dialog should be closed');
    });

    QUnit.module('global dialog options');

    QUnit.test('autoOpen', function (assert) {
        var element;
        assert.expect(2);

        element = $('

').formDialog();
        assert.notOk(element.dialog("widget").is(":visible"), 'dialog should not be open by default');
        element.remove();

        element = $('

').formDialog({ autoOpen: true });
        assert.ok(element.dialog("widget").is(":visible"), 'dialog should be open by default');
        element.remove();
    });

    QUnit.test('width', function (assert) {
        assert.expect(1);

        var element = $('

').formDialog({ autoOpen: true });
        assert.close(element.dialog("widget").width(), 500, 1, 'default width should be 500px');
        element.remove();
    });

    QUnit.module('self configuration', {
        beforeEach: function () {
            this.elems = $('#qunit-fixture').children();
        },
        afterEach: function () {
            this.elems.dialog('destroy');
        }
    });

    QUnit.test('individual config', function (assert) {
        var fd1 = $('#form-3');
        var fd2 = $('#form-4');
        assert.expect(9);

        this.elems.formDialog();

        //fd1.dialog('open');
        assert.equal(fd1.dialog('option', 'appendTo'), fd1.data('appendTo'), 'option should be same as attribute');
        assert.equal(fd1.dialog('widget').parent()[0], $(fd1.data('appendTo'))[0], 'container should match option');

        assert.equal(fd1.dialog('option', 'width'), fd1.data('width'), 'option should be same as attribute');
        assert.close(fd1.dialog('widget').width(), fd1.data('width'), 1, 'width should be 400px');

        assert.equal(fd1.dialog('option', 'maxHeight'), fd1.data('maxHeight'), 'option should be same as attribute');
        assert.equal(fd1.dialog('option', 'hide'), fd1.data('hide'), 'option should be same as attribute');
        fd1.dialog('close');

        fd2.dialog('open');
        assert.equal(fd2.dialog('option', 'maxWidth'), fd2.data('maxWidth'), 'option should be same as attribute');
        assert.equal(fd2.dialog('option', 'minHeight'), fd2.data('minHeight'), 'option should be same as attribute');
        assert.equal(fd2.dialog('option', 'show'), fd2.data('show'), 'option should be same as attribute');
        fd2.dialog('close');
    });

    QUnit.test('option precedence', function (assert) {
        var fd = $('#form-3');
        assert.expect(2);

        this.elems.formDialog({
            width: 200
        });

        assert.equal(fd.dialog('option', 'width'), 200, 'option should overwrite attribute');
        assert.close(fd.dialog('widget').width(), 200, 1, 'width should be 200px');
        fd.dialog('close');
    });

    // "save" button actions
    QUnit.module('AJAX', {
        beforeEach: function () {
            this.server = sinon.fakeServer.create();
            // success
            this.server.respondWith(/\/ajax\/success/, [200, {
                "Content-Type": "text/plain"
            }, 'success']);
            // server error
            this.server.respondWith(/\/ajax\/error\/500/, [500, {
                "Content-Type": "text/plain"
            }, 'internal server error']);
            // validation error
            this.server.respondWith(/\/ajax\/error\/400/, [400, {
                "Content-Type": "application/json"
            }, '{"error":["operation cancelled"],"form":{"test":["invalid value"]}}']);
        },
        afterEach: function () {
            this.server.restore();
        }
    });

    QUnit.test('wrapped form', function (assert) {
        var done = assert.async();
        assert.expect(1);

        var element = $('#form-1').formDialog(function (txt) {
            assert.strictEqual(txt, 'success', 'should have success message');
            done();
        });

        element.dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('unwrapped form', function (assert) {
        var done = assert.async();
        assert.expect(1);

        var element = $('#form-2').formDialog(function (txt) {
            assert.strictEqual(txt, 'success', 'should have success message');
            done();
        });
        element.dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('server error', function (assert) {
        var done = assert.async();
        assert.expect(4);

        var element = $('<form action="/ajax/error/500" method="post"></form>').formDialog();

        $(document).one('ajaxComplete', function () {
            var popup = $('.ui-dialog pre');
            assert.strictEqual(element.dialog('isOpen'), false, 'form dialog should be closed');
            assert.strictEqual(popup.length, 1, 'error popup should be created');
            assert.strictEqual(popup.text(), 'internal server error', 'should be using correct error message');

            popup.dialog('close');
            assert.strictEqual($('pre').length, 0, 'error popup should be removed');

            done();
        });

        element.dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('validation error', function (assert) {
        var done = assert.async();
        assert.expect(6);

        var element = $('<form action="/ajax/error/400" method="post"><input name="test"></form>').formDialog();

        $(document).one('ajaxComplete', function () {
            var popup = $('.ui-dialog pre');
            assert.strictEqual(popup.length, 0, 'there should be no error popup');
            assert.strictEqual(element.dialog('isOpen'), true, 'form dialog should be open');

            var errors = element.find('ul.error');
            assert.strictEqual(errors.length, 2, 'form dialog should have 2 error notes');

            assert.equal(errors.eq(0).text(), 'operation cancelled', '1st error should be general');
            assert.equal(errors.eq(1).text(), 'invalid value', '2nd error should be specific');

            var sibling_name = errors.eq(1).next().prop('name');
            assert.equal(sibling_name, 'test', 'specific error should be before form field');

            element.dialog('close');

            done();
        });

        element.dialog('open').dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('form data processor', function (assert) {
        var done = assert.async(),
            server = this.server,
            html = '<form action="/ajax/success" method="post"><input name="test" value="foo"></form>';
        assert.expect(2);

        var element = $(html).formDialog({
            formData: function () {
                return 'test=bar';
            },
            success: function (txt) {
                assert.strictEqual(txt, 'success', 'should have success message');
                assert.strictEqual(server.requests[0].requestBody, 'test=bar', 'should have modified request body');
                done();
            }
        });

        element.dialog('open').dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

}(window, document, QUnit, jQuery, window.sinon));
<commit_msg>added scope test in processing callback<commit_after>/*
======== A Handy Little QUnit Reference ========
  http://api.qunitjs.com/

  Test methods:
    module(name, {[beforeEach][, afterEach]})
    test(name, callback)
  Test assertions:
    expect(numberOfAssertions)
    async()
    ok(value, [message])
    notOk(value, [message])
    equal(actual, expected, [message])
    notEqual(actual, expected, [message])
    deepEqual(actual, expected, [message])
    notDeepEqual(actual, expected, [message])
    strictEqual(actual, expected, [message])
    notStrictEqual(actual, expected, [message])
    throws(block, [expected], [message])
*/

(function (window, document, QUnit, $, sinon) {

    QUnit.module('basics', {
        beforeEach: function() {
            this.elems = $('#qunit-fixture').children();
        }
    });

    QUnit.test('is chainable', function (assert) {
        assert.expect(1);
        // Not a bad test to run on collection methods.
        assert.strictEqual(this.elems.formDialog(), this.elems, 'should be chainable');
    });

    QUnit.module('buttons');

    QUnit.test('button properties', function (assert) {
        assert.expect(3);

        var element = $('

').formDialog(),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.equal(btn.length, 2, 'dialog should have 2 buttons');
        assert.equal(btn.eq(0).text(), 'Save', 'submit button should be named "Save"');
        assert.equal(btn.eq(1).text(), 'Cancel', 'abort button should be named "Cancel"');
    });

    QUnit.test('custom button label', function (assert) {
        assert.expect(1);

        var element = $('

').formDialog({ actionLabel: 'FizzBuzz' }),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.equal(btn.eq(0).text(), 'FizzBuzz', 'submit button should have custom label');
    });

    QUnit.test('translate button label', function (assert) {
        assert.expect(2);

        var element = $('

').formDialog({ language: 'de' }),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.equal(btn.eq(0).text(), 'Speichern', 'submit button label should be translated');
        assert.equal(btn.eq(1).text(), 'Abbrechen', 'abort button label should be translated');
    });

    QUnit.test('cancel button', function (assert) {
        assert.expect(2);

        var element = $('

').formDialog({ autoOpen: true }),
            btn = element.dialog('widget').find('.ui-dialog-buttonpane button');

        assert.ok(element.dialog('isOpen'), 'dialog should be open');
        btn.eq(1).trigger('click');
        assert.notOk(element.dialog('isOpen'), 'dialog should be closed');
    });

    QUnit.module('global dialog options');

    QUnit.test('autoOpen', function (assert) {
        var element;
        assert.expect(2);

        element = $('

').formDialog();
        assert.notOk(element.dialog("widget").is(":visible"), 'dialog should not be open by default');
        element.remove();

        element = $('

').formDialog({ autoOpen: true });
        assert.ok(element.dialog("widget").is(":visible"), 'dialog should be open by default');
        element.remove();
    });

    QUnit.test('width', function (assert) {
        assert.expect(1);

        var element = $('

').formDialog({ autoOpen: true });
        assert.close(element.dialog("widget").width(), 500, 1, 'default width should be 500px');
        element.remove();
    });

    QUnit.module('self configuration', {
        beforeEach: function () {
            this.elems = $('#qunit-fixture').children();
        },
        afterEach: function () {
            this.elems.dialog('destroy');
        }
    });

    QUnit.test('individual config', function (assert) {
        var fd1 = $('#form-3');
        var fd2 = $('#form-4');
        assert.expect(9);

        this.elems.formDialog();

        //fd1.dialog('open');
        assert.equal(fd1.dialog('option', 'appendTo'), fd1.data('appendTo'), 'option should be same as attribute');
        assert.equal(fd1.dialog('widget').parent()[0], $(fd1.data('appendTo'))[0], 'container should match option');

        assert.equal(fd1.dialog('option', 'width'), fd1.data('width'), 'option should be same as attribute');
        assert.close(fd1.dialog('widget').width(), fd1.data('width'), 1, 'width should be 400px');

        assert.equal(fd1.dialog('option', 'maxHeight'), fd1.data('maxHeight'), 'option should be same as attribute');
        assert.equal(fd1.dialog('option', 'hide'), fd1.data('hide'), 'option should be same as attribute');
        fd1.dialog('close');

        fd2.dialog('open');
        assert.equal(fd2.dialog('option', 'maxWidth'), fd2.data('maxWidth'), 'option should be same as attribute');
        assert.equal(fd2.dialog('option', 'minHeight'), fd2.data('minHeight'), 'option should be same as attribute');
        assert.equal(fd2.dialog('option', 'show'), fd2.data('show'), 'option should be same as attribute');
        fd2.dialog('close');
    });

    QUnit.test('option precedence', function (assert) {
        var fd = $('#form-3');
        assert.expect(2);

        this.elems.formDialog({
            width: 200
        });

        assert.equal(fd.dialog('option', 'width'), 200, 'option should overwrite attribute');
        assert.close(fd.dialog('widget').width(), 200, 1, 'width should be 200px');
        fd.dialog('close');
    });

    // "save" button actions
    QUnit.module('AJAX', {
        beforeEach: function () {
            this.server = sinon.fakeServer.create();
            // success
            this.server.respondWith(/\/ajax\/success/, [200, {
                "Content-Type": "text/plain"
            }, 'success']);
            // server error
            this.server.respondWith(/\/ajax\/error\/500/, [500, {
                "Content-Type": "text/plain"
            }, 'internal server error']);
            // validation error
            this.server.respondWith(/\/ajax\/error\/400/, [400, {
                "Content-Type": "application/json"
            }, '{"error":["operation cancelled"],"form":{"test":["invalid value"]}}']);
        },
        afterEach: function () {
            this.server.restore();
        }
    });

    QUnit.test('wrapped form', function (assert) {
        var done = assert.async();
        assert.expect(1);

        var element = $('#form-1').formDialog(function (txt) {
            assert.strictEqual(txt, 'success', 'should have success message');
            done();
        });

        element.dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('unwrapped form', function (assert) {
        var done = assert.async();
        assert.expect(1);

        var element = $('#form-2').formDialog(function (txt) {
            assert.strictEqual(txt, 'success', 'should have success message');
            done();
        });
        element.dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('server error', function (assert) {
        var done = assert.async();
        assert.expect(4);

        var element = $('<form action="/ajax/error/500" method="post"></form>').formDialog();

        $(document).one('ajaxComplete', function () {
            var popup = $('.ui-dialog pre');
            assert.strictEqual(element.dialog('isOpen'), false, 'form dialog should be closed');
            assert.strictEqual(popup.length, 1, 'error popup should be created');
            assert.strictEqual(popup.text(), 'internal server error', 'should be using correct error message');

            popup.dialog('close');
            assert.strictEqual($('pre').length, 0, 'error popup should be removed');

            done();
        });

        element.dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('validation error', function (assert) {
        var done = assert.async();
        assert.expect(6);

        var element = $('<form action="/ajax/error/400" method="post"><input name="test"></form>').formDialog();

        $(document).one('ajaxComplete', function () {
            var popup = $('.ui-dialog pre');
            assert.strictEqual(popup.length, 0, 'there should be no error popup');
            assert.strictEqual(element.dialog('isOpen'), true, 'form dialog should be open');

            var errors = element.find('ul.error');
            assert.strictEqual(errors.length, 2, 'form dialog should have 2 error notes');

            assert.equal(errors.eq(0).text(), 'operation cancelled', '1st error should be general');
            assert.equal(errors.eq(1).text(), 'invalid value', '2nd error should be specific');

            var sibling_name = errors.eq(1).next().prop('name');
            assert.equal(sibling_name, 'test', 'specific error should be before form field');

            element.dialog('close');

            done();
        });

        element.dialog('open').dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

    QUnit.test('form data processor', function (assert) {
        var done = assert.async(),
            server = this.server,
            html = '<form action="/ajax/success" method="post"><input name="test" value="foo"></form>';
        assert.expect(5);

        var element = $(html).formDialog({
            formData: function (form) {
                assert.ok(this instanceof HTMLFormElement, 'scope should be form element');
                // 'jQuery' has been removed from the global scope
                assert.ok(form instanceof $, 'parameter should be jQuery object');
                assert.ok(form[0] instanceof HTMLFormElement, 'scope should be form element');

                return 'test=bar';
            },
            success: function (txt) {
                assert.strictEqual(txt, 'success', 'should have success message');
                assert.strictEqual(server.requests[0].requestBody, 'test=bar', 'should have modified request body');
                done();
            }
        });

        element.dialog('open').dialog('widget').find('.ui-dialog-buttonpane button').eq(0).trigger('click');
        this.server.respond();
    });

}(window, document, QUnit, jQuery, window.sinon));
<|endoftext|>