<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var kstest = require( '@stdlib/math/generics/statistics/kstest' );
var round = require( '@stdlib/math/base/special/round' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var factory = require( './../lib/factory.js' );

// VARIABLES //

var opts = {
	'skip': ( process.env.TEST_MODE === 'coverage' )
};

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof factory, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns a pseudorandom number generator (no seed)', function test( t ) {
	var invgamma;
	var r;
	var i;

	// When binding distribution parameters...
	invgamma = factory( 2.0, 2.0 );
	for ( i = 0; i < 100; i++ ) {
		r = invgamma();
		t.equal( typeof r, 'number', 'returns a number' );
	}

	// Without binding distribution parameters...
	invgamma = factory();
	for ( i = 0; i < 100; i++ ) {
		r = invgamma( 2.5, 2.0 );
		t.equal( typeof r, 'number', 'returns a number' );
	}

	t.end();
});

tape( 'the function returns a seeded pseudorandom number generator', function test( t ) {
	var invgamma1;
	var invgamma2;
	var seed;
	var r1;
	var r2;
	var i;

	seed = round( Date.now() / 1000 );

	invgamma1 = factory( 1.0, 1.0, {
		'seed': seed
	});
	invgamma2 = factory( 1.0, 1.0, {
		'seed': seed
	});

	t.notEqual( invgamma1, invgamma2, 'separate generators' );

	for ( i = 0; i < 100; i++ ) {
		r1 = invgamma1();
		r2 = invgamma2();
		t.equal( r1, r2, 'both return same number' );
	}
	t.end();
});

tape( 'attached to the returned function is the generator name', function test( t ) {
	var invgamma = factory();
	t.equal( invgamma.NAME, 'invgamma', 'has `NAME` property' );
	t.end();
});

tape( 'attached to the returned function is the underlying PRNG', function test( t ) {
	var invgamma = factory();
	t.equal( typeof invgamma.PRNG, 'function', 'has `PRNG` property' );
	t.end();
});

tape( 'attached to the returned function is the generator seed', function test( t ) {
	var invgamma = factory({
		'seed': 12345
	});
	t.equal( typeof invgamma.SEED, 'number', 'has `SEED` property' );
	t.equal( invgamma.SEED, 12345, 'equal to provided seed' );
	t.end();
});

tape( 'the function throws an error if `alpha` is not a positive number', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( value, 2.0 );
		};
	}
});

tape( 'the function throws an error if `invgamma` is not a positive number', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( 2.0, value );
		};
	}
});

tape( 'the function throws an error if provided an options argument which is not an object (no other arguments)', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( value );
		};
	}
});

tape( 'the function throws an error if provided an options argument which is not an object (other arguments)', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( 1.0, 1.0, value );
		};
	}
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a first argument which is `NaN`', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();
	r = invgamma( NaN, 1.0 );

	t.strictEqual( isnan( r ), true, 'returns NaN' );
	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a second argument which is `NaN`', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();
	r = invgamma( 1.0, NaN );

	t.strictEqual( isnan( r ), true, 'returns NaN' );
	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided `NaNs`', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();
	r = invgamma( NaN, NaN );

	t.strictEqual( isnan( r ), true, 'returns NaN' );
	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a first argument which is nonpositive', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();

	r = invgamma( 0.0, 1.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	r = invgamma( -1.0, 1.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a second argument which is nonpositive', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();

	r = invgamma( 1.0, 0.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	r = invgamma( 1.0, -1.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	t.end();
});

tape( 'the function returns a generator for creating random numbers from the specified inverse-gamma distribution', opts, function test( t ) {
	var invgamma;
	var rejected;
	var pValue;
	var alpha;
	var beta;
	var N;
	var i;
	var j;
	var x;

	alpha = 3.14;
	beta = 2.0;

	x = new Array( 1e3 );
	rejected = 0;
	N = 300;
	for ( i = 0; i < N; i++ ) {
		invgamma = factory( alpha, beta );
		t.ok( true, 'seed: '+invgamma.SEED );
		for ( j = 0; j < x.length; j++ ) {
			x[ j ] = invgamma();
		}
		// Test using Kolmogorov-Smirnov goodness-of-fit test:
		pValue = kstest( x, 'invgamma', alpha, beta ).pValue;
		t.equal( typeof pValue, 'number', 'returns a p-value: '+pValue );
		if ( pValue < 0.05 ) {
			rejected += 1;
		}
	}
	// Account for small sample size and few repeats...
	t.ok( rejected / N < 0.07, 'null hypothesis (i.e., that numbers are drawn from InverseGamma('+alpha+','+beta+')) is rejected in less than 7% of cases ('+rejected+' of '+N+')' );
	t.end();
});
<commit_msg>Increase test threshold<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var kstest = require( '@stdlib/math/generics/statistics/kstest' );
var round = require( '@stdlib/math/base/special/round' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var factory = require( './../lib/factory.js' );

// VARIABLES //

var opts = {
	'skip': ( process.env.TEST_MODE === 'coverage' )
};

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof factory, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns a pseudorandom number generator (no seed)', function test( t ) {
	var invgamma;
	var r;
	var i;

	// When binding distribution parameters...
	invgamma = factory( 2.0, 2.0 );
	for ( i = 0; i < 100; i++ ) {
		r = invgamma();
		t.equal( typeof r, 'number', 'returns a number' );
	}

	// Without binding distribution parameters...
	invgamma = factory();
	for ( i = 0; i < 100; i++ ) {
		r = invgamma( 2.5, 2.0 );
		t.equal( typeof r, 'number', 'returns a number' );
	}

	t.end();
});

tape( 'the function returns a seeded pseudorandom number generator', function test( t ) {
	var invgamma1;
	var invgamma2;
	var seed;
	var r1;
	var r2;
	var i;

	seed = round( Date.now() / 1000 );

	invgamma1 = factory( 1.0, 1.0, {
		'seed': seed
	});
	invgamma2 = factory( 1.0, 1.0, {
		'seed': seed
	});

	t.notEqual( invgamma1, invgamma2, 'separate generators' );

	for ( i = 0; i < 100; i++ ) {
		r1 = invgamma1();
		r2 = invgamma2();
		t.equal( r1, r2, 'both return same number' );
	}
	t.end();
});

tape( 'attached to the returned function is the generator name', function test( t ) {
	var invgamma = factory();
	t.equal( invgamma.NAME, 'invgamma', 'has `NAME` property' );
	t.end();
});

tape( 'attached to the returned function is the underlying PRNG', function test( t ) {
	var invgamma = factory();
	t.equal( typeof invgamma.PRNG, 'function', 'has `PRNG` property' );
	t.end();
});

tape( 'attached to the returned function is the generator seed', function test( t ) {
	var invgamma = factory({
		'seed': 12345
	});
	t.equal( typeof invgamma.SEED, 'number', 'has `SEED` property' );
	t.equal( invgamma.SEED, 12345, 'equal to provided seed' );
	t.end();
});

tape( 'the function throws an error if `alpha` is not a positive number', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( value, 2.0 );
		};
	}
});

tape( 'the function throws an error if `invgamma` is not a positive number', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( 2.0, value );
		};
	}
});

tape( 'the function throws an error if provided an options argument which is not an object (no other arguments)', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( value );
		};
	}
});

tape( 'the function throws an error if provided an options argument which is not an object (other arguments)', function test( t ) {
	var values;
	var i;

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

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			factory( 1.0, 1.0, value );
		};
	}
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a first argument which is `NaN`', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();
	r = invgamma( NaN, 1.0 );

	t.strictEqual( isnan( r ), true, 'returns NaN' );
	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a second argument which is `NaN`', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();
	r = invgamma( 1.0, NaN );

	t.strictEqual( isnan( r ), true, 'returns NaN' );
	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided `NaNs`', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();
	r = invgamma( NaN, NaN );

	t.strictEqual( isnan( r ), true, 'returns NaN' );
	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a first argument which is nonpositive', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();

	r = invgamma( 0.0, 1.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	r = invgamma( -1.0, 1.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	t.end();
});

tape( 'when called without arguments, the function returns a PRNG that returns `NaN` if provided a second argument which is nonpositive', function test( t ) {
	var invgamma;
	var r;

	invgamma = factory();

	r = invgamma( 1.0, 0.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	r = invgamma( 1.0, -1.0 );
	t.strictEqual( isnan( r ), true, 'returns NaN' );

	t.end();
});

tape( 'the function returns a generator for creating random numbers from the specified inverse-gamma distribution', opts, function test( t ) {
	var invgamma;
	var rejected;
	var pValue;
	var alpha;
	var beta;
	var N;
	var i;
	var j;
	var x;

	alpha = 3.14;
	beta = 2.0;

	x = new Array( 1e3 );
	rejected = 0;
	N = 300;
	for ( i = 0; i < N; i++ ) {
		invgamma = factory( alpha, beta );
		t.ok( true, 'seed: '+invgamma.SEED );
		for ( j = 0; j < x.length; j++ ) {
			x[ j ] = invgamma();
		}
		// Test using Kolmogorov-Smirnov goodness-of-fit test:
		pValue = kstest( x, 'invgamma', alpha, beta ).pValue;
		t.equal( typeof pValue, 'number', 'returns a p-value: '+pValue );
		if ( pValue < 0.05 ) {
			rejected += 1;
		}
	}
	// Account for small sample size and few repeats...
	t.ok( rejected / N < 0.10, 'null hypothesis (i.e., that numbers are drawn from InverseGamma('+alpha+','+beta+')) is rejected in less than 10% of cases ('+rejected+' of '+N+')' );
	t.end();
});
<|endoftext|>


<commit_before>var CandyShop = (function(self) { return self; }(CandyShop || {}));

CandyShop.Colors = (function(self, Candy, $) {

	var _numColors,
		_currentColor = 0;

	self.init = function(numColors) {
		_numColors = numColors ? numColors : 8;

		self.applyTranslations();

		Candy.View.Event.Message.beforeSend = function(message) {
			if(_currentColor > 0 && $.trim(message) !== '') {
				return '|c:'+ _currentColor +'|' + message;
			}
			return message;
		};

		Candy.View.Event.Message.beforeShow = function(message) {
			message = message.replace(/^\|c:([0-9]{1,2})\|(.*)/gm, '$2');
			return message;
		};

		if(Candy.Util.cookieExists('candyshop-colors-current')) {
			var color = parseInt(Candy.Util.getCookie('candyshop-colors-current'), 10);
			if(color > 0 && color < _numColors) {
				_currentColor = color;
			}
		}
		var html = '

';
		$('#emoticons-icon').after(html);
		$('#colors-control').click(function(event) {
			CandyShop.Colors.showPicker(this);
		});
	};

	self.showPicker = function(elem) {
		elem = $(elem);
		var pos = elem.offset(),
			menu = $('#context-menu'),
			content = $('ul', menu),
			colors = '',
			i;

		$('#tooltip').hide();

		for(i = _numColors-1; i >= 0; i--) {
			colors = '' + colors;
		}
		content.html('
' + colors + '
');
		content.find('span').click(function() {
			_currentColor = $(this).attr('data-color');
			$('#colors-control-indicator').attr('class', 'color-' + _currentColor);
			Candy.Util.setCookie('candyshop-colors-current', _currentColor, 365);
			Candy.View.Pane.Room.setFocusToForm(Candy.View.getCurrent().roomJid);
			menu.hide();
		});

		var posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(menu, pos.left),
			posTop  = Candy.Util.getPosTopAccordingToWindowBounds(menu, pos.top);

		menu.css({'left': posLeft.px, 'top': posTop.px, backgroundPosition: posLeft.backgroundPositionAlignment + ' ' + posTop.backgroundPositionAlignment});
		menu.fadeIn('fast');

		return true;
	};

	self.applyTranslations = function() {
		Candy.View.Translation.en.candyshopColorsMessagecolor = 'Message color';
		Candy.View.Translation.de.candyshopColorsMessagecolor = 'Farbe für Nachrichten';
		Candy.View.Translation.fr.candyshopColorsMessagecolor = 'Couleur des messages';
	};

	return self;
}(CandyShop.Colors || {}, Candy, jQuery));<commit_msg>Dutch Translation<commit_after>var CandyShop = (function(self) { return self; }(CandyShop || {}));

CandyShop.Colors = (function(self, Candy, $) {

	var _numColors,
		_currentColor = 0;

	self.init = function(numColors) {
		_numColors = numColors ? numColors : 8;

		self.applyTranslations();

		Candy.View.Event.Message.beforeSend = function(message) {
			if(_currentColor > 0 && $.trim(message) !== '') {
				return '|c:'+ _currentColor +'|' + message;
			}
			return message;
		};

		Candy.View.Event.Message.beforeShow = function(message) {
			message = message.replace(/^\|c:([0-9]{1,2})\|(.*)/gm, '$2');
			return message;
		};

		if(Candy.Util.cookieExists('candyshop-colors-current')) {
			var color = parseInt(Candy.Util.getCookie('candyshop-colors-current'), 10);
			if(color > 0 && color < _numColors) {
				_currentColor = color;
			}
		}
		var html = '

';
		$('#emoticons-icon').after(html);
		$('#colors-control').click(function(event) {
			CandyShop.Colors.showPicker(this);
		});
	};

	self.showPicker = function(elem) {
		elem = $(elem);
		var pos = elem.offset(),
			menu = $('#context-menu'),
			content = $('ul', menu),
			colors = '',
			i;

		$('#tooltip').hide();

		for(i = _numColors-1; i >= 0; i--) {
			colors = '' + colors;
		}
		content.html('
' + colors + '
');
		content.find('span').click(function() {
			_currentColor = $(this).attr('data-color');
			$('#colors-control-indicator').attr('class', 'color-' + _currentColor);
			Candy.Util.setCookie('candyshop-colors-current', _currentColor, 365);
			Candy.View.Pane.Room.setFocusToForm(Candy.View.getCurrent().roomJid);
			menu.hide();
		});

		var posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(menu, pos.left),
			posTop  = Candy.Util.getPosTopAccordingToWindowBounds(menu, pos.top);

		menu.css({'left': posLeft.px, 'top': posTop.px, backgroundPosition: posLeft.backgroundPositionAlignment + ' ' + posTop.backgroundPositionAlignment});
		menu.fadeIn('fast');

		return true;
	};

	self.applyTranslations = function() {
		Candy.View.Translation.en.candyshopColorsMessagecolor = 'Message color';
		Candy.View.Translation.de.candyshopColorsMessagecolor = 'Farbe für Nachrichten';
		Candy.View.Translation.fr.candyshopColorsMessagecolor = 'Couleur des messages';
		Candy.View.Translation.nl.candyshopColorsMessagecolor = 'Berichtkleur';
	};

	return self;
}(CandyShop.Colors || {}, Candy, jQuery));<|endoftext|>


<commit_before>function interpret(code) {
  var program = new BefungeProgram(code);
  while (!program.isRunning)
    program.runNextInstruction();
  return program.output;
}

function BefungeProgram(code) {
  var instructions = code.split('\n').map(function (line) { return line.split(''); });
  instructions.get = function () {
    var args = arguments[0] instanceof Array ? arguments[0] : arguments;
    return this[args[0]][args[1]];
  };
  instructions.set = function () {
    var args = arguments[0] instanceof Array ? arguments[0] : arguments;
    this[args[0]][args[1]] = arguments.length - 1;
  };

  var stack = [];
  var output = '';
  var codePointer = [0, 0];
  var direction = '>';
  var asciiMode = false;

  var self = this;

  function addProperty(property, getter) {
    Object.defineProperty(self, property, { get: getter });
  }

  addProperty('stack', function () { return stack.slice(); });
  addProperty('output', function () { return output; });
  addProperty('isRunning', function () {
    var current = instructions.get(codePointer);
    return current != '@' && !current;
  });

  function nextMove() {
    switch (direction) {
      case '<':
        codePointer[0] -= 1;
        break;
      case '>':
        codePointer[0] += 1;
        break;
      case '^':
        codePointer[1] -= 1;
        break;
      case 'v':
        codePointer[1] += 1;
        break;
    }
  }

  function processInstruction(instruction) {
    var a, b;
    if (asciiMode) {
      stack.push(instruction.charCodeAt(0));
      return nextMove();
    } else if (instruction == '@')
      return;
    else if (instruction >= '0' && '9' >= instruction)
      stack.push(instruction);
    else if (instruction == '+')
      stack.push(stack.pop() + stack.pop());
    else if (instruction == '-')
      stack.push(-stack.pop() + stack.pop());
    else if (instruction == '*')
      stack.push(stack.pop() * stack.pop());
    else if (instruction == '/')
      !(a = stack.pop()) ? a : Math.ceil(stack.pop() / a);
    else if (instruction == '%')
      !(a = stack.pop()) ? a : Math.ceil(stack.pop() % a);
    else if (instruction == '!')
      !stack.pop() ? 1 : 0;
    else if (instruction == '`')
      stack.pop() >= stack.pop() ? 0 : 1;
    else if (~'<>^v'.indexOf(instruction))
      direction = instruction;
    else if (instruction == '>')
      codePointer[0] += 1;
    else if (instruction == 'v')
      codePointer[1] += 1;
    else if (instruction == '^')
      codePointer[1] -= 1;
    else if (instruction == '?')
      this.runInstruction('<>v^'[~~(Math.random() * 5)]);
    else if (instruction == '_')
      direction = stack.pop() ? '<' : '>';
    else if (instruction == '|')
      direction = stack.pop() ? '^' : 'v';
    else if (instruction == '"')
      asciiMode = !asciiMode;
    else if (instruction == ':')
      (a = stack.pop()) === undefined ? stack.push(0) : (stack.push(a), stack.push(a));
    else if (instruction == '.')
      output += stack.pop();
    else if (instruction == ',')
      output += stack.pop().charCodeAt(0);
    else if (instruction == '#')
      nextMove();
    else if (instruction == '\\')
      a = stack.pop(), b = stack.pop(), stack.push(b || 0), stack.push(a);
    else if (instruction == '$')
      stack.pop();
    else if (instruction == 'p')
      b = stack.pop(), a = stack.pop(), instructions.set(a, b, stack.pop().fromCharCode());
    else if (instruction == 'g')
      b = stack.pop(), a = stack.pop(), stack.push(instructions.get(a, b).charCodeAt(0));
    else if (instruction == ' ') ;
    else throw 'Unsupported instruction: ' + instruction;
  }

  this.runNextInstruction = function () {
    var current = instructions.get(codePointer);
    processInstruction(current);
    nextMove();
  };
}

BefungeProgram.prototype.constructor = BefungeProgram;

module.exports = interpret;<commit_msg>Fixed bug whith get and set methods of instruction object<commit_after>function interpret(code) {
  var program = new BefungeProgram(code);
  while (!program.isRunning)
    program.runNextInstruction();
  return program.output;
}

function BefungeProgram(code) {
  var instructions = code.split('\n').map(function (line) { return line.split(''); });
  instructions.get = function () {
    var args = arguments[0] instanceof Array ? arguments[0] : arguments;
    return this[args[1]][args[0]];
  };
  instructions.set = function () {
    var args = arguments[0] instanceof Array ? arguments[0] : arguments;
    this[args[1]][args[0]] = arguments.length - 1;
  };

  var stack = [];
  var output = '';
  var codePointer = [0, 0];
  var direction = '>';
  var asciiMode = false;

  var self = this;

  function addProperty(property, getter) {
    Object.defineProperty(self, property, { get: getter });
  }

  addProperty('stack', function () { return stack.slice(); });
  addProperty('output', function () { return output; });
  addProperty('isRunning', function () {
    var current = instructions.get(codePointer);
    return current != '@' && !current;
  });

  function nextMove() {
    switch (direction) {
      case '<':
        codePointer[0] -= 1;
        break;
      case '>':
        codePointer[0] += 1;
        break;
      case '^':
        codePointer[1] -= 1;
        break;
      case 'v':
        codePointer[1] += 1;
        break;
    }
  }

  function processInstruction(instruction) {
    var a, b;
    if (asciiMode) {
      stack.push(instruction.charCodeAt(0));
      return nextMove();
    } else if (instruction == '@')
      return;
    else if (instruction >= '0' && '9' >= instruction)
      stack.push(instruction);
    else if (instruction == '+')
      stack.push(stack.pop() + stack.pop());
    else if (instruction == '-')
      stack.push(-stack.pop() + stack.pop());
    else if (instruction == '*')
      stack.push(stack.pop() * stack.pop());
    else if (instruction == '/')
      !(a = stack.pop()) ? a : Math.ceil(stack.pop() / a);
    else if (instruction == '%')
      !(a = stack.pop()) ? a : Math.ceil(stack.pop() % a);
    else if (instruction == '!')
      !stack.pop() ? 1 : 0;
    else if (instruction == '`')
      stack.pop() >= stack.pop() ? 0 : 1;
    else if (~'<>^v'.indexOf(instruction))
      direction = instruction;
    else if (instruction == '>')
      codePointer[0] += 1;
    else if (instruction == 'v')
      codePointer[1] += 1;
    else if (instruction == '^')
      codePointer[1] -= 1;
    else if (instruction == '?')
      this.runInstruction('<>v^'[~~(Math.random() * 5)]);
    else if (instruction == '_')
      direction = stack.pop() ? '<' : '>';
    else if (instruction == '|')
      direction = stack.pop() ? '^' : 'v';
    else if (instruction == '"')
      asciiMode = !asciiMode;
    else if (instruction == ':')
      (a = stack.pop()) === undefined ? stack.push(0) : (stack.push(a), stack.push(a));
    else if (instruction == '.')
      output += stack.pop();
    else if (instruction == ',')
      output += stack.pop().charCodeAt(0);
    else if (instruction == '#')
      nextMove();
    else if (instruction == '\\')
      a = stack.pop(), b = stack.pop(), stack.push(b || 0), stack.push(a);
    else if (instruction == '$')
      stack.pop();
    else if (instruction == 'p')
      b = stack.pop(), a = stack.pop(), instructions.set(a, b, stack.pop().fromCharCode());
    else if (instruction == 'g')
      b = stack.pop(), a = stack.pop(), stack.push(instructions.get(a, b).charCodeAt(0));
    else if (instruction == ' ') ;
    else throw 'Unsupported instruction: ' + instruction;
  }

  this.runNextInstruction = function () {
    var current = instructions.get(codePointer);
    processInstruction(current);
    nextMove();
  };
}

BefungeProgram.prototype.constructor = BefungeProgram;

module.exports = interpret;<|endoftext|>


<commit_before>var _ = Npm.require('lodash');
var path = Npm.require('path');
var fs = Npm.require('fs');

themesGenerator = {};

/**
  Always generates assets everytime the server restarts or refreshes
*/
themesGenerator.generateAssets = function(basePath, customSemanticData, themesData, compileStep) {
  var themesFiles = requiredThemesFiles(themesData, customSemanticData);
  createAssetFiles(compileStep, themesFiles.assets);
};

/**
  Generates the themes folder.
*/
themesGenerator.generate = function(basePath, customSemanticData, themesData, compileStep) {
  cleanUp(basePath);

  var themesFiles = requiredThemesFiles(themesData, customSemanticData);
  var files = themesFiles.overrides.concat(themesFiles.variables);
  _.each(files, function(filePath) {
    createThemeFile(filePath, basePath);
  });
  createThemeConfigFile(basePath, themesData);
  createThemeLessFile(basePath, themesData);
};

var cleanUp = function(basePath) {
  fileHandler.removeDir(path.join(basePath, 'themes'));
  fileHandler.removeFile(path.join(basePath, 'theme.config'));
  fileHandler.removeFile(path.join(basePath, 'theme.import.less'));
};

var createAssetFiles = function(compileStep, assetsFiles) {
  _.each(assetsFiles, function(filePath) {
    compileStep.addAsset({
      path: filePath,
      data: fileHandler.getBinaryFileBuffer(filePath)
    });
  });
};

/**
  Creates the file theme.config.import.less if it does not exist.
*/
var createThemeConfigFile = function(basePath, themesData) {
  if (fs.existsSync(path.join(basePath, 'theme.config.import.less'))) {
    return;
  }
  var config = fileHandler.getTextFile(themesData.themeConfigFile);
  fileHandler.writeTextFile(basePath, 'theme.config.import.less', config);
};

var createThemeLessFile = function(basePath, themesData) {
  fileHandler.writeTextFile(basePath, 'theme.import.less', fileHandler.getTextFile(themesData.themeLessFile));
};

var createThemeFile = function(sourcePath, basePath) {
  var content = fileHandler.getTextFile(sourcePath);
  var relativePath = sourcePath.match(/themes\/.+/)[0];
  fileHandler.writeTextFile(basePath, relativePath, content);
};

var requiredThemesFiles = function(themesData, customSemanticData) {
  var files = {};
  files.overrides = themesData.overridesFilePaths();
  files.variables = themesData.variablesFilePaths();
  files.assets = themesData.assetsFilePaths();

  files.overrides = customSemanticData.filterThemes(files.overrides);
  files.variables = customSemanticData.filterThemes(files.variables);
  files.assets = customSemanticData.filterThemes(files.assets);

  files.overrides = customSemanticData.filterDefinitions(files.overrides);
  files.variables = customSemanticData.filterDefinitions(files.variables);
  files.assets = customSemanticData.filterDefinitions(files.assets);
  return files;
};
<commit_msg>bugfix: assets are loaded now<commit_after>var _ = Npm.require('lodash');
var path = Npm.require('path');
var fs = Npm.require('fs');

themesGenerator = {};

/**
  Always generates assets everytime the server restarts or refreshes
*/
themesGenerator.generateAssets = function(basePath, customSemanticData, themesData, compileStep) {
  var themesFiles = requiredThemesFiles(themesData, customSemanticData);
  createAssetFiles(compileStep, themesFiles.assets);
};

/**
  Generates the themes folder.
*/
themesGenerator.generate = function(basePath, customSemanticData, themesData, compileStep) {
  cleanUp(basePath);

  var themesFiles = requiredThemesFiles(themesData, customSemanticData);
  var files = themesFiles.overrides.concat(themesFiles.variables);
  _.each(files, function(filePath) {
    createThemeFile(filePath, basePath);
  });
  createThemeConfigFile(basePath, themesData);
  createThemeLessFile(basePath, themesData);
};

var cleanUp = function(basePath) {
  fileHandler.removeDir(path.join(basePath, 'themes'));
  fileHandler.removeFile(path.join(basePath, 'theme.config'));
  fileHandler.removeFile(path.join(basePath, 'theme.import.less'));
};

var createAssetFiles = function(compileStep, assetsFiles) {
  _.each(assetsFiles, function(filePath) {
    compileStep.addAsset({
      path: filePath,
      data: fileHandler.getBinaryFileBuffer(filePath)
    });
  });
};

/**
  Creates the file theme.config.import.less if it does not exist.
*/
var createThemeConfigFile = function(basePath, themesData) {
  if (fs.existsSync(path.join(basePath, 'theme.config.import.less'))) {
    return;
  }
  var config = fileHandler.getTextFile(themesData.themeConfigFile);
  fileHandler.writeTextFile(basePath, 'theme.config.import.less', config);
};

var createThemeLessFile = function(basePath, themesData) {
  fileHandler.writeTextFile(basePath, 'theme.import.less', fileHandler.getTextFile(themesData.themeLessFile));
};

var createThemeFile = function(sourcePath, basePath) {
  var content = fileHandler.getTextFile(sourcePath);
  var relativePath = sourcePath.match(/themes\/.+/)[0];
  fileHandler.writeTextFile(basePath, relativePath, content);
};

var requiredThemesFiles = function(themesData, customSemanticData) {
  var files = {};
  files.overrides = themesData.overridesFilePaths();
  files.variables = themesData.variablesFilePaths();
  files.assets = themesData.assetsFilePaths();

  files.overrides = customSemanticData.filterThemes(files.overrides);
  files.variables = customSemanticData.filterThemes(files.variables);
  files.assets = customSemanticData.filterThemes(files.assets);

  files.overrides = customSemanticData.filterDefinitions(files.overrides);
  files.variables = customSemanticData.filterDefinitions(files.variables);
  files.assets = customSemanticData.filterDefinitions(files.assets, function(string, name) {
    // icon and flag in assets end with a 's'
    var regex = new RegExp("\\W" + name + "\\w\\W", 'g');
    return string.match(regex) !== null;
  });
  return files;
};
<|endoftext|>


<commit_before>// croppie : http://foliotek.github.io/Croppie/

function RG_Thumbnail(options) {

	this.name = 'Make thumbnail';

	var self = this;
	var app = null;
	var RESIZE_EVENT = 'resize.rgUploader';
	var isMobile = false;
	var resizeInterval = null;

	this.file = null;
	this.croppie = null;
	this.$el = {
		con : null,
		wrap : null,
		bg : null,
		figure : null,
		meta : null,
		btn_close : null,
		btn_done : null
	};

	/**
	 * load external vendor files
	 */
	function loadExternalFiles()
	{
		if (window.loadedCroppie) return false;

		var head = document.getElementsByTagName('head')[0];
		var cssEl = document.createElement('link');
		var scriptEl = document.createElement('script');

		cssEl.rel = 'stylesheet';
		cssEl.href = self.options.url_croppieCSS;
		scriptEl.src = self.options.url_croppieJS;

		head.appendChild(cssEl);
		head.appendChild(scriptEl);

		window.loadedCroppie = true;
	}

	/**
	 * create container
	 */
	function createContainer()
	{
		// set elements
		self.$el.con = $('
' +
			'' +
			'
' +
			'

' +
			'
' +
			'

message

' +
			'' +
			'<button type="button" class="btn-done">done</button>' +
			'<button type="button" class="btn-close">close</button>' +
			'' +
			'
' +
			'
' +
			'
');
		self.$el.wrap = self.$el.con.children('.wrap');
		self.$el.bg = self.$el.con.children('.bg');
		self.$el.figure = self.$el.con.find('.img-wrap figure');
		self.$el.meta = self.$el.con.find('.meta > p');
		self.$el.btn_done = self.$el.con.find('.btn-done');
		self.$el.btn_close = self.$el.con.find('.btn-close');

		// insert element
		$('body').append(self.$el.con);
	}

	/**
	 * init events
	 */
	function initEvents()
	{
		// close in background
		self.$el.bg.on('click', function(){
			self.close();
		});

		// close in close button
		self.$el.btn_close.on('click', function(){
			self.close();
		});

		// done
		self.$el.btn_done.on('click', done);

		// init resize event
		$(window).on(RESIZE_EVENT, resize);
	}

	/**
	 * change mobile
	 */
	function actMobile(pass)
	{
		if (!pass && isMobile) return false;

		// set isMobile
		isMobile = true;

		// change window size
		self.$el.wrap
			.width('100%').height('100%')
			.css({ marginLeft : 0, marginTop : 0, left: 0, top: 0 });

		// rebuild croppie
		if (self.croppie)
		{
			rebuildCroppie(true);
		}
	}

	/**
	 * change desktop
	 */
	function actDesktop(pass)
	{
		if (!pass && !isMobile) return false;

		// set isMobile
		isMobile = false;

		// change window size
		self.$el.wrap
			.width(self.options.width).height(self.options.height)
			.css({
				marginLeft : (0 - self.options.width * 0.5) + 'px',
				marginTop : (0 - self.options.height * 0.5) + 'px',
				left: '50%',
				top: '50%'
			});

		// rebuild croppie
		if (self.croppie)
		{
			rebuildCroppie(true);
		}
	}

	/**
	 * resize event
	 *
	 * @Param {Object} e
	 */
	function resize(e)
	{
		var $win = $(window);

		if (!self.croppie)
		{
			clearTimeout(resizeInterval);
			return false;
		}

		if (resizeInterval)
		{
			clearTimeout(resizeInterval);
		}

		resizeInterval = setTimeout(function(){
			// 계속 모바일 사이즈상태일때 실행
			if (isMobile && ($win.width() < 640))
			{
				actMobile(true);
				return false;
			}
			if ($win.width() < 640)
			{
				actMobile(true);
			}
			else if ($win.width() > 640)
			{
				actDesktop(true);
			}
		}, 300);
	}

	/**
	 * rebuild croppie
	 *
	 * @Param {Boolean} isResize
	 */
	function rebuildCroppie(isResize)
	{
		// save option
		var save = (isResize) ? self.croppie.get() : {};

		// destroy croppie
		destroyCroppie();

		// build croppie
		self.options.croppie.boundary = {
			width : (self.options.mobileSize > $(window).width()) ? $(window).width() : self.options.width,
			height : ((self.options.mobileSize > $(window).width()) ? $(window).height() : self.options.height)-60
		};
		self.croppie = new Croppie(self.$el.figure.get(0), self.options.croppie);

		// bind croppie
		if (isResize)
		{
			self.rebind({
				src : self.file.fullSrc,
				points : save.points
			}, function(){
				self.croppie.setZoom(save.zoom);
			});
		}
	}

	/**
	 * destroy croppie
	 */
	function destroyCroppie()
	{
		if (self.croppie)
		{
			self.croppie.destroy();
			self.croppie = null;
		}
	}

	/**
	 * done event
	 *
	 * @Param {Object} e
	 */
	function done(e)
	{
		// result
		self.croppie.result(self.options.output).then(function(res){
			if (self.options.uploadScript)
			{
				$.post(
					self.options.uploadScript,
					{
						name : self.file.name,
						image : res,
						id : app.util.getUniqueNumber()
					},
					function(res){
						try {
							res = JSON.parse(res);
						} catch (e) {
							alert('parse error');
							return false;
						}
						if (res.state == 'error')
						{
							alert(res.response.message);
							return false;
						}

						if (self.options.doneCallback)
						{
							self.options.doneCallback(res.response, app, self.file);
						}
					});
			}
			else
			{
				if (self.options.doneCallback)
				{
					self.options.doneCallback({
						id : app.util.getUniqueNumber(),
						name : 'thumb-' + self.file.name,
						src : res,
						type : 'image/' + self.options.output.format,
						size : 0
					}, app, self.file);
				}
			}

			// close
			self.close();
		});
	}

	/**
	 * init
	 *
	 * @Param {Object} parent
	 */
	this.init = function(parent)
	{
		app = parent;

		// merge options
		this.assignOption(options);

		// load files
		loadExternalFiles();

		// create container
		createContainer();

		// init events
		initEvents();
	};

	/**
	 * open window
	 *
	 * @Param {Object} file
	 * @Param {Object} bind
	 */
	this.open = function(file, bind)
	{
		bind = bind || {};

		// show window
		this.$el.con.addClass('show');
		$('html').addClass('rg-popup');

		// set file value
		this.file = file;

		// act pc & mobile
		if ($(window).width() < this.options.mobileSize)
		{
			actMobile(true);
		}
		else
		{
			actDesktop(true);
		}

		// rebuild croppie
		rebuildCroppie();
		// bind image
		this.rebind({
			src : this.file.fullSrc,
			points : bind.points,
			orientation : bind.orientation
		}, function(){
			self.croppie.setZoom(bind.zoom || 0.1);
		});

		// input state
		this.$el.meta.text('output size: ' + this.options.output.size.width + '*' + this.options.output.size.height);

		// callback open window
		if (this.options.openCallback)
		{
			this.options.openCallback(app);
		}
	};

	/**
	 * close window
	 */
	this.close = function()
	{
		destroyCroppie();
		this.file = null;
		this.$el.con.removeClass('show');
		$('html').removeClass('rg-popup');

		// callback close window
		if (this.options.closeCallback)
		{
			this.options.closeCallback(app);
		}
	};

	/**
	 * rebind
	 *
	 * @Param {Object} options
	 * @Param {Function} callback
	 */
	this.rebind = function(options, callback)
	{
		this.croppie.bind({
			url : options.src,
			points : (options.points) ? options.points : [],
			orientation : (options.orientation) ? options.orientation : 1
		}, function(){
			if (callback) callback();
		});
	};

	/**
	 * assignOption
	 *
	 * @Param {Object} obj
	 */
	this.assignOption = function(obj)
	{
		this.options = $.extend(true, this.options, obj);
	}
}

RG_Thumbnail.prototype.options = {
	width : 640,
	height : 480,
	mobileSize : 640,
	url_croppieCSS : '../vendor/Croppie/croppie.css',
	url_croppieJS : '../vendor/Croppie/croppie.min.js',
	uploadScript : '',
	output : {
		type : 'canvas',
		quality : .75,
		format : 'jpeg',
		size : { width : 150, height : 150 }
	},
	croppie : {
		boundary : { width: 640, height: 480-60 },
		viewport : { width: 150, height: 150, type: 'square' }
	},
	doneCallback : null,
	openCallback : null,
	closeCallback : null
};<commit_msg>Fix cross domain issue<commit_after>// croppie : http://foliotek.github.io/Croppie/

function RG_Thumbnail(options) {

	this.name = 'Make thumbnail';

	var self = this;
	var app = null;
	var RESIZE_EVENT = 'resize.rgUploader';
	var isMobile = false;
	var resizeInterval = null;

	this.file = null;
	this.croppie = null;
	this.$el = {
		con : null,
		wrap : null,
		bg : null,
		figure : null,
		meta : null,
		btn_close : null,
		btn_done : null
	};

	/**
	 * load external vendor files
	 */
	function loadExternalFiles()
	{
		if (window.loadedCroppie) return false;

		var head = document.getElementsByTagName('head')[0];
		var cssEl = document.createElement('link');
		var scriptEl = document.createElement('script');

		cssEl.rel = 'stylesheet';
		cssEl.href = self.options.url_croppieCSS;
		scriptEl.src = self.options.url_croppieJS;

		head.appendChild(cssEl);
		head.appendChild(scriptEl);

		window.loadedCroppie = true;
	}

	/**
	 * create container
	 */
	function createContainer()
	{
		// set elements
		self.$el.con = $('
' +
			'' +
			'
' +
			'

' +
			'
' +
			'

message

' +
			'' +
			'<button type="button" class="btn-done">done</button>' +
			'<button type="button" class="btn-close">close</button>' +
			'' +
			'
' +
			'
' +
			'
');
		self.$el.wrap = self.$el.con.children('.wrap');
		self.$el.bg = self.$el.con.children('.bg');
		self.$el.figure = self.$el.con.find('.img-wrap figure');
		self.$el.meta = self.$el.con.find('.meta > p');
		self.$el.btn_done = self.$el.con.find('.btn-done');
		self.$el.btn_close = self.$el.con.find('.btn-close');

		// insert element
		$('body').append(self.$el.con);
	}

	/**
	 * init events
	 */
	function initEvents()
	{
		// close in background
		self.$el.bg.on('click', function(){
			self.close();
		});

		// close in close button
		self.$el.btn_close.on('click', function(){
			self.close();
		});

		// done
		self.$el.btn_done.on('click', done);

		// init resize event
		$(window).on(RESIZE_EVENT, resize);
	}

	/**
	 * change mobile
	 */
	function actMobile(pass)
	{
		if (!pass && isMobile) return false;

		// set isMobile
		isMobile = true;

		// change window size
		self.$el.wrap
			.width('100%').height('100%')
			.css({ marginLeft : 0, marginTop : 0, left: 0, top: 0 });

		// rebuild croppie
		if (self.croppie)
		{
			rebuildCroppie(true);
		}
	}

	/**
	 * change desktop
	 */
	function actDesktop(pass)
	{
		if (!pass && !isMobile) return false;

		// set isMobile
		isMobile = false;

		// change window size
		self.$el.wrap
			.width(self.options.width).height(self.options.height)
			.css({
				marginLeft : (0 - self.options.width * 0.5) + 'px',
				marginTop : (0 - self.options.height * 0.5) + 'px',
				left: '50%',
				top: '50%'
			});

		// rebuild croppie
		if (self.croppie)
		{
			rebuildCroppie(true);
		}
	}

	/**
	 * resize event
	 *
	 * @Param {Object} e
	 */
	function resize(e)
	{
		var $win = $(window);

		if (!self.croppie)
		{
			clearTimeout(resizeInterval);
			return false;
		}

		if (resizeInterval)
		{
			clearTimeout(resizeInterval);
		}

		resizeInterval = setTimeout(function(){
			// 계속 모바일 사이즈상태일때 실행
			if (isMobile && ($win.width() < 640))
			{
				actMobile(true);
				return false;
			}
			if ($win.width() < 640)
			{
				actMobile(true);
			}
			else if ($win.width() > 640)
			{
				actDesktop(true);
			}
		}, 300);
	}

	/**
	 * rebuild croppie
	 *
	 * @Param {Boolean} isResize
	 */
	function rebuildCroppie(isResize)
	{
		// save option
		var save = (isResize) ? self.croppie.get() : {};

		// destroy croppie
		destroyCroppie();

		// build croppie
		self.options.croppie.boundary = {
			width : (self.options.mobileSize > $(window).width()) ? $(window).width() : self.options.width,
			height : ((self.options.mobileSize > $(window).width()) ? $(window).height() : self.options.height)-60
		};
		self.croppie = new Croppie(self.$el.figure.get(0), self.options.croppie);

		// bind croppie
		if (isResize)
		{
			self.rebind({
				src : self.file.fullSrc,
				points : save.points
			}, function(){
				self.croppie.setZoom(save.zoom);
			});
		}
	}

	/**
	 * destroy croppie
	 */
	function destroyCroppie()
	{
		if (self.croppie)
		{
			self.croppie.destroy();
			self.croppie = null;
		}
	}

	/**
	 * done event
	 *
	 * @Param {Object} e
	 */
	function done(e)
	{
		// result
		self.croppie.result(self.options.output).then(function(res){
			if (self.options.uploadScript)
			{
				$.post(
					self.options.uploadScript,
					{
						name : self.file.name,
						image : res,
						id : app.util.getUniqueNumber()
					},
					function(res){
						try {
							res = JSON.parse(res);
						} catch (e) {
							alert('parse error');
							return false;
						}
						if (res.state == 'error')
						{
							alert(res.response.message);
							return false;
						}

						if (self.options.doneCallback)
						{
							self.options.doneCallback(res.response, app, self.file);
						}
					});
			}
			else
			{
				if (self.options.doneCallback)
				{
					self.options.doneCallback({
						id : app.util.getUniqueNumber(),
						name : 'thumb-' + self.file.name,
						src : res,
						type : 'image/' + self.options.output.format,
						size : 0
					}, app, self.file);
				}
			}

			// close
			self.close();
		}, function (error) {
			console.log('ERROR', error);
		});
	}

	/**
	 * init
	 *
	 * @Param {Object} parent
	 */
	this.init = function(parent)
	{
		app = parent;

		// merge options
		this.assignOption(options);

		// load files
		loadExternalFiles();

		// create container
		createContainer();

		// init events
		initEvents();
	};

	/**
	 * open window
	 *
	 * @Param {Object} file
	 * @Param {Object} bind
	 */
	this.open = function(file, bind)
	{
		bind = bind || {};

		// show window
		this.$el.con.addClass('show');
		$('html').addClass('rg-popup');

		// set file value
		this.file = file;

		// act pc & mobile
		if ($(window).width() < this.options.mobileSize)
		{
			actMobile(true);
		}
		else
		{
			actDesktop(true);
		}

		// rebuild croppie
		rebuildCroppie();
		// bind image
		this.rebind({
			src : this.file.fullSrc,
			points : bind.points,
			orientation : bind.orientation
		}, function(){
			self.croppie.setZoom(bind.zoom || 0.1);
		});

		// input state
		this.$el.meta.text('output size: ' + this.options.output.size.width + '*' + this.options.output.size.height);

		// callback open window
		if (this.options.openCallback)
		{
			this.options.openCallback(app);
		}
	};

	/**
	 * close window
	 */
	this.close = function()
	{
		destroyCroppie();
		this.file = null;
		this.$el.con.removeClass('show');
		$('html').removeClass('rg-popup');

		// callback close window
		if (this.options.closeCallback)
		{
			this.options.closeCallback(app);
		}
	};

	/**
	 * rebind
	 *
	 * @Param {Object} options
	 * @Param {Function} callback
	 */
	this.rebind = function(options, callback)
	{
		this.croppie.bind({
			url : options.src,
			points : (options.points) ? options.points : [],
			orientation : (options.orientation) ? options.orientation : 1
		}, function(){
			if (callback) callback();
		});
	};

	/**
	 * assignOption
	 *
	 * @Param {Object} obj
	 */
	this.assignOption = function(obj)
	{
		this.options = $.extend(true, this.options, obj);
	}
}

RG_Thumbnail.prototype.options = {
	width : 640,
	height : 480,
	mobileSize : 640,
	url_croppieCSS : '../vendor/Croppie/croppie.css',
	url_croppieJS : '../vendor/Croppie/croppie.min.js',
	uploadScript : '',
	output : {
		type : 'canvas',
		quality : .75,
		format : 'jpeg',
		size : { width : 150, height : 150 }
	},
	croppie : {
		enableOrientation: true,
		boundary : { width: 640, height: 480-60 },
		viewport : { width: 150, height: 150, type: 'square' }
	},
	doneCallback : null,
	openCallback : null,
	closeCallback : null
};<|endoftext|>


<commit_before>/*
 * Windows Display Settings Handler
 *
 * Copyright 2012 Raising the Floor - International
 * Copyright 2012 Antranig Basman
 * Copyright 2012 Astea Solutions AD
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The research leading to these results has received funding from the European Union's
 * Seventh Framework Programme (FP7/2007-2013)
 * under grant agreement no. 289016.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */

"use strict";

var ref = require("ref");
var struct = require("ref-struct");
var arrayType = require("ref-array");
var ffi = require("ffi");
var fluid = require("universal");

var gpii = fluid.registerNamespace("gpii");
var windows = fluid.registerNamespace("gpii.windows");

fluid.registerNamespace("gpii.windows.display");
fluid.registerNamespace("gpii.windows.displaySettingsHandler");

// https://msdn.microsoft.com/en-us/library/windows/desktop/dd183565(v=vs.85).aspx

var t = windows.types;
var c = windows.API_constants;

var CCHDEVICENAME = 32;
var CCHFORMNAME = 32;

windows.DEVMODEW = new struct([
    [arrayType(t.TCHAR, CCHDEVICENAME), "dmDeviceName"],
    [t.WORD, "dmSpecVersion"],
    [t.WORD, "dmDriverVersion"],
    [t.WORD, "dmSize"],
    [t.WORD, "dmDriverExtra"],
    [t.DWORD, "dmFields"],
    //union {   // TODO there is a ref-union npm module - but this technique is OK for now
    //  struct {
    ["short", "dmOrientation"],
    ["short", "dmPaperSize"],
    ["short", "dmPaperLength"],
    ["short", "dmPaperWidth"],
    ["short", "dmScale"],
    ["short", "dmCopies"],
    ["short", "dmDefaultSource"],
    ["short", "dmPrintQuality"],
    //  };
    //  struct {
    //      POINTL dmPosition;
    //      DWORD dmDisplayOrientation;
    //      DWORD dmDisplayFixedOutput;
    //  };
    //};
    ["short", "dmColor"],
    ["short", "dmDuplex"],
    ["short", "dmYResolution"],
    ["short", "dmTTOption"],
    ["short", "dmCollate"],
    [arrayType(t.TCHAR, CCHFORMNAME), "dmFormName"],
    [t.WORD, "dmLogPixels"],
    [t.DWORD, "dmBitsPerPel"],
    [t.DWORD, "dmPelsWidth"],
    [t.DWORD, "dmPelsHeight"],
    //union {
    [t.DWORD, "dmDisplayFlags"],
    //  DWORD dmNup;
    //};
    [t.DWORD, "dmDisplayFrequency"],
    //#if (WINVER >= 0x0400)
    [t.DWORD, "dmICMMethod"],
    [t.DWORD, "dmICMIntent"],
    [t.DWORD, "dmMediaType"],
    [t.DWORD, "dmDitherType"],
    [t.DWORD, "dmReserved1"],
    [t.DWORD, "dmReserved2"],
    //#if (WINVER >= 0x0500) || (_WIN32_WINNT >= 0x0400)
    [t.DWORD, "dmPanningWidth"],
    [t.DWORD, "dmPanningHeight"]
    //#endif
    //#endif
]);

windows.display.user32 = ffi.Library("user32", {
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dd162611(v=vs.85).aspx
    // LPCWSTR, DWORD, DEVMODE*
    "EnumDisplaySettingsW": [
        t.BOOL, ["pointer", t.DWORD, "pointer"]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dd183411(v=vs.85).aspx
    // DEVMODE*, DWORD
    "ChangeDisplaySettingsW": [
        t.LONG, ["pointer", t.DWORD]
    ]
});

/**
    *  Gets the current display's screen resolution
    *
    * @return {Object) The width and height of the screen.
    */
windows.display.getScreenResolution = function () {
    var dm = new windows.DEVMODEW();
    dm.ref().fill(0);
    dm.dmSize = windows.DEVMODEW.size;

    if (c.FALSE !== windows.display.user32.EnumDisplaySettingsW(ref.NULL, c.ENUM_CURRENT_SETTINGS, dm.ref())) {
        // note for unknown reason on win 10 the returned dmSize is 188 not expected 220
        return { width: dm.dmPelsWidth, height: dm.dmPelsHeight };
    }
    return { width: 0, height: 0 };

};

/**
    *  Sets the current display's screen resolution if possible
    *
    * @param {Object} The new sreen resolution width and height
    * @return {boolean} true if successfu
    */
windows.display.setScreenResolution = function (newRes) {
    if (undefined === newRes ||
        null === newRes ||
        "object" !== typeof (newRes) ||
        undefined === newRes.width ||
        undefined === newRes.height) {
        return false;
    }

    var index = 0;
    var dm = new windows.DEVMODEW();
    dm.ref().fill(0);
    dm.dmSize = windows.DEVMODEW.size;

    while (c.FALSE !== windows.display.user32.EnumDisplaySettingsW(ref.NULL, index++, dm.ref())) {
        if (dm.dmPelsWidth === newRes.width && dm.dmPelsHeight === newRes.height) {
            var dmCurrent = new windows.DEVMODEW();
            dmCurrent.ref().fill(0);
            dmCurrent.dmSize = windows.DEVMODEW.size;

            if (c.FALSE !== windows.display.user32.EnumDisplaySettingsW(ref.NULL, c.ENUM_CURRENT_SETTINGS, dmCurrent.ref())) {
                // Note: ChangeDisplaySettings has no effect if new is same as current
                dmCurrent.dmPelsWidth = newRes.width;
                dmCurrent.dmPelsHeight = newRes.height;
                var lRet = windows.display.user32.ChangeDisplaySettingsW(dmCurrent.ref(), 0);
                if (c.DISP_CHANGE_SUCCESSFUL === lRet) {
                    return true;
                }
                if (c.DISP_CHANGE_RESTART === lRet) {
                    //printf("Reset required\r\n"); // FIXME what should we do in this case? Alert user? Ignore? Roll back?
                    return true;
                }
            }
        }
    }

    return false;
};

windows.display.allSettings = {
    "screen-resolution": {
        get: "windows.display.getScreenResolution",
        set: "windows.display.setScreenResolution"
    }
};

windows.display.setImpl = function (settingsRequest) {
    var z = settingsRequest;
};

windows.display.getImpl = function (settingsRequest) {
    settingsRequest = settingsRequest || windows.display.allSettings;
    var settings = fluid.transform(settingsRequest, function (value, key) {
        var funcEntry = windows.display.allSettings[key];
        if (funcEntry) {
            return fluid.invokeGlobalFunction(funcEntry.get);
        } else {
            fluid.fail("Invalid key to Windows display settings handler - " +
                key + " - valid choices are " + JSON.stringify(fluid.keys(windows.display.allSettings)));
        }
    });
    return settings;
};

windows.displaySettingsHandler.get = function (payload) {
    return gpii.settingsHandlers.invokeSettingsHandler(windows.displaySettingsHandler.getImpl, payload);
};

windows.displaySettingsHandler.set = function (payload) {
    return gpii.settingsHandlers.invokeSettingsHandler(windows.displaySettingsHandler.setImpl, payload);
};

<commit_msg>Correctly implemented screenResolution getter and setter<commit_after>/*
 * Windows Display Settings Handler
 *
 * Copyright 2012 Raising the Floor - International
 * Copyright 2012 Antranig Basman
 * Copyright 2012 Astea Solutions AD
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The research leading to these results has received funding from the European Union's
 * Seventh Framework Programme (FP7/2007-2013)
 * under grant agreement no. 289016.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */

"use strict";

var ref = require("ref");
var struct = require("ref-struct");
var arrayType = require("ref-array");
var ffi = require("ffi");
var fluid = require("universal");

var gpii = fluid.registerNamespace("gpii");
var windows = fluid.registerNamespace("gpii.windows");

fluid.registerNamespace("gpii.windows.display");
fluid.registerNamespace("gpii.windows.displaySettingsHandler");

// https://msdn.microsoft.com/en-us/library/windows/desktop/dd183565(v=vs.85).aspx

var t = windows.types;
var c = windows.API_constants;

var CCHDEVICENAME = 32;
var CCHFORMNAME = 32;

windows.DEVMODEW = new struct([
    [arrayType(t.TCHAR, CCHDEVICENAME), "dmDeviceName"],
    [t.WORD, "dmSpecVersion"],
    [t.WORD, "dmDriverVersion"],
    [t.WORD, "dmSize"],
    [t.WORD, "dmDriverExtra"],
    [t.DWORD, "dmFields"],
    //union {   // TODO there is a ref-union npm module - but this technique is OK for now
    //  struct {
    ["short", "dmOrientation"],
    ["short", "dmPaperSize"],
    ["short", "dmPaperLength"],
    ["short", "dmPaperWidth"],
    ["short", "dmScale"],
    ["short", "dmCopies"],
    ["short", "dmDefaultSource"],
    ["short", "dmPrintQuality"],
    //  };
    //  struct {
    //      POINTL dmPosition;
    //      DWORD dmDisplayOrientation;
    //      DWORD dmDisplayFixedOutput;
    //  };
    //};
    ["short", "dmColor"],
    ["short", "dmDuplex"],
    ["short", "dmYResolution"],
    ["short", "dmTTOption"],
    ["short", "dmCollate"],
    [arrayType(t.TCHAR, CCHFORMNAME), "dmFormName"],
    [t.WORD, "dmLogPixels"],
    [t.DWORD, "dmBitsPerPel"],
    [t.DWORD, "dmPelsWidth"],
    [t.DWORD, "dmPelsHeight"],
    //union {
    [t.DWORD, "dmDisplayFlags"],
    //  DWORD dmNup;
    //};
    [t.DWORD, "dmDisplayFrequency"],
    //#if (WINVER >= 0x0400)
    [t.DWORD, "dmICMMethod"],
    [t.DWORD, "dmICMIntent"],
    [t.DWORD, "dmMediaType"],
    [t.DWORD, "dmDitherType"],
    [t.DWORD, "dmReserved1"],
    [t.DWORD, "dmReserved2"],
    //#if (WINVER >= 0x0500) || (_WIN32_WINNT >= 0x0400)
    [t.DWORD, "dmPanningWidth"],
    [t.DWORD, "dmPanningHeight"]
    //#endif
    //#endif
]);

windows.display.user32 = ffi.Library("user32", {
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dd162611(v=vs.85).aspx
    // LPCWSTR, DWORD, DEVMODE*
    "EnumDisplaySettingsW": [
        t.BOOL, ["pointer", t.DWORD, "pointer"]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dd183411(v=vs.85).aspx
    // DEVMODE*, DWORD
    "ChangeDisplaySettingsW": [
        t.LONG, ["pointer", t.DWORD]
    ]
});

/**
    *  Gets the current display's screen resolution
    *
    * @return {Object) The width and height of the screen.
    */
windows.display.getScreenResolution = function () {
    var dm = new windows.DEVMODEW();
    dm.ref().fill(0);
    dm.dmSize = windows.DEVMODEW.size;

    if (c.FALSE !== windows.display.user32.EnumDisplaySettingsW(ref.NULL, c.ENUM_CURRENT_SETTINGS, dm.ref())) {
        // note for unknown reason on win 10 the returned dmSize is 188 not expected 220
        return { width: dm.dmPelsWidth, height: dm.dmPelsHeight };
    }
    return { width: 0, height: 0 };

};

/**
    *  Sets the current display's screen resolution if possible
    *
    * @param {Object} The new sreen resolution width and height
    * @return {boolean} true if successfu
    */
windows.display.setScreenResolution = function (newRes) {
    if (undefined === newRes ||
        null === newRes ||
        "object" !== typeof (newRes) ||
        undefined === newRes.width ||
        undefined === newRes.height) {
        return false;
    }

    var index = 0;
    var dm = new windows.DEVMODEW();
    dm.ref().fill(0);
    dm.dmSize = windows.DEVMODEW.size;

    while (c.FALSE !== windows.display.user32.EnumDisplaySettingsW(ref.NULL, index++, dm.ref())) {
        if (dm.dmPelsWidth === newRes.width && dm.dmPelsHeight === newRes.height) {
            var dmCurrent = new windows.DEVMODEW();
            dmCurrent.ref().fill(0);
            dmCurrent.dmSize = windows.DEVMODEW.size;

            if (c.FALSE !== windows.display.user32.EnumDisplaySettingsW(ref.NULL, c.ENUM_CURRENT_SETTINGS, dmCurrent.ref())) {
                // Note: ChangeDisplaySettings has no effect if new is same as current
                dmCurrent.dmPelsWidth = newRes.width;
                dmCurrent.dmPelsHeight = newRes.height;
                var lRet = windows.display.user32.ChangeDisplaySettingsW(dmCurrent.ref(), 0);
                if (c.DISP_CHANGE_SUCCESSFUL === lRet) {
                    return true;
                }
                if (c.DISP_CHANGE_RESTART === lRet) {
                    //printf("Reset required\r\n"); // FIXME what should we do in this case? Alert user? Ignore? Roll back?
                    return true;
                }
            }
        }
    }

    return false;
};

var settingName = "screen-resolution";

windows.display.setImpl = function (payload) {
    var oldRes = windows.display.getScreenResolution();
    var newRes = oldRes;

    var targetRes = payload.settings[settingName];
    if (undefined === targetRes ||
        undefined === targetRes.width ||
        undefined === targetRes.height) {
        fluid.fail("Incorrect payload for screen resolution: " +
                    JSON.stringify(payload, null, 4));
    }
    else if (windows.display.setScreenResolution(targetRes)) {
        newRes = targetRes;
    }

    var results = {};
    results[settingName] = { oldValue: oldRes, newValue: newRes };

    fluid.log("display settings handler SET returning results ", results);
    return results;
};

windows.display.getImpl = function () {
    var curRes = windows.display.getScreenResolution();
    var results = {};
    results[settingName] = curRes;

    fluid.log("display settings handler GET returning results ", results);
    return results;
};

windows.displaySettingsHandler.get = function (payload) {
    return gpii.settingsHandlers.invokeSettingsHandler(windows.display.getImpl, payload);
};

windows.displaySettingsHandler.set = function (payload) {
    return gpii.settingsHandlers.invokeSettingsHandler(windows.display.setImpl, payload);
};

<|endoftext|>


<commit_before>define(function(require) {
  "use strict";

  var $ = require("jquery");
  var Validation = require("neue/validation");

  var shouldValidateForm = true;

  var $schoolSignupForm = $("#dosomething-signup-user-signup-data-form");
  if( $schoolSignupForm ) {
    var $schoolIDContainer = $schoolSignupForm.find(".form-item-school-id");
    var $schoolNameContainer = $schoolSignupForm.find(".form-item-school-name");
    var $stateField = $("#edit-school-administrative-area");
    var $schoolIDField = $("#edit-school-id");
    var $schoolNameField = $("#edit-school-name");
    var $notAffiliatedField = $("#edit-school-not-affiliated");

    $schoolIDContainer.hide();
    $schoolNameContainer.hide();

    $stateField.on("change", function() {
      $schoolNameContainer.show();
      $schoolNameField.focus();
    });

    $notAffiliatedField.on("change", function() {
      // If user is not entering a school, don't validate form
      shouldValidateForm = !this.checked;
    });
  }

  /**
   * Custom validation for the School Finder.
   */
  Validation.registerValidationFunction("school_finder", function($el, done) {
    if(shouldValidateForm) {
      return done({ success: false });
    }

    return done({ success: true });
  });

});
<commit_msg>Moving the action inside a document.ready.<commit_after>define(function(require) {
  "use strict";

  var $ = require("jquery");
  var Validation = require("neue/validation");

  var shouldValidateForm = true;

  $(document).ready(function() {
    var $schoolSignupForm = $("#dosomething-signup-user-signup-data-form");
    if( $schoolSignupForm ) {
      var $schoolIDContainer = $schoolSignupForm.find(".form-item-school-id");
      var $schoolNameContainer = $schoolSignupForm.find(".form-item-school-name");
      var $stateField = $("#edit-school-administrative-area");
      var $schoolIDField = $("#edit-school-id");
      var $schoolNameField = $("#edit-school-name");
      var $notAffiliatedField = $("#edit-school-not-affiliated");
      var $notAffiliatedConfirmationMessage = $("#edit-school-not-affiliated-confirm-msg");

      $schoolIDContainer.hide();
      $schoolNameContainer.hide();
      $notAffiliatedConfirmationMessage.hide();

      $stateField.on("change", function() {
        // Show the school name field once user has chosen a state.
        if($(this).val() !== "") {
          $schoolNameContainer.show();
          $schoolNameField.focus();
        } else {
          $schoolNameContainer.hide();
        }
      });

      $notAffiliatedField.on("change", function() {
        // If user is not entering a school, don't validate form.
        shouldValidateForm = !this.checked;

        if(this.checked) {
          $notAffiliatedConfirmationMessage.show();
        } else {
          $notAffiliatedConfirmationMessage.hide();
        }
      });
    }
  });

  /**
   * Custom validation for the School Finder.
   */
  Validation.registerValidationFunction("school_finder", function($el, done) {
    if(shouldValidateForm) {
      return done({ success: false });
    }

    return done({ success: true });
  });

});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import createReactClass from 'create-react-class'
import Slider from '../src/slider'

var SampleNextArrow = createReactClass({
  render: function() {
    return

;
  }
});

var SamplePrevArrow = createReactClass({
  render: function() {
    return (

    );
  }
});

export default class CustomArrows extends Component {
  render() {
    const settings = {
      dots: true,
      infinite: true,
      slidesToShow: 3,
      slidesToScroll: 1,
      nextArrow: <SampleNextArrow />,
      prevArrow: <SamplePrevArrow />
    };
    return (

Custom Arrows

        <Slider {...settings}>

1

2

3

4

5

6

        </Slider>

    );
  }
}<commit_msg>Fix an issue with custom arrows example<commit_after>import React, { Component } from 'react'
import createReactClass from 'create-react-class'
import Slider from '../src/slider'

var SampleNextArrow = createReactClass({
  render: function() {
    const {className, style, onClick} = this.props
    return (

    );
  }
});

var SamplePrevArrow = createReactClass({
  render: function() {
    const {className, style, onClick} = this.props
    return (

    );
  }
});

export default class CustomArrows extends Component {
  render() {
    const settings = {
      dots: true,
      infinite: true,
      slidesToShow: 3,
      slidesToScroll: 1,
      nextArrow: <SampleNextArrow />,
      prevArrow: <SamplePrevArrow />
    };
    return (

Custom Arrows

        <Slider {...settings}>

1

2

3

4

5

6

        </Slider>

    );
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import Formsy from 'formsy-react'
import Modal from 'react-modal';
import MyInput from '../components/my-input'
import MySelect from '../components/my-select'
import MyTextarea from '../components/my-textarea'
import SectionTitle from '../components/section-title'
import HttpHelpers from '../utils/http-helpers'
var _ = require('lodash');

const redirectUrl = (window.location.href.split("/\?", 2)[0] + '/step2').replace("//step2", "/step2");
const randomEmail = Math.random().toString(36).substr(2,10);

const FormContainer = React.createClass({
  getInitialState() {
    return {
      canSubmit: false,
      isLoading: false,
      validationErrors: {},
      serverErrorMsg: false,
      serverSuccessMsg: false,
      showSubmissionModal: false,
      loading: {
        'street': false,
        'suburb': false,
      },
      suburbs: ['Enter Postcode...'],
      streets: ['Choose Suburb...'],
      postcode: '0000',
      country: 'au',
    };
  },
  submit(data) {
    if (data.mnames === undefined) { data.mnames = ""}
    if (data.referred_by === undefined) { data.referred_by = ""}
    if (data.member_comment === undefined) { data.member_comment = ""}
    data.dob = data.dobYear + '-' + data.dobMonth + '-' + data.dobDay + 'T12:00:00';
    data.address = _.join([data.addr_street_no, data.addr_street, data.addr_suburb, data.addr_postcode], "; ");
    data.name = _.join([data.fname, data.mnames, data.lname], ", ");

    this.setState({isLoading: true, showSubmissionModal: true});
    HttpHelpers.sendForm(data, function(response){

      if (__DEV__) {
        console.log(response);
        console.log(data);
      }

      if (response.ok && response.status === 200 && response.body.success === true) {
        this.setState({
          isLoading: false,
          serverSuccessMsg: "Success"
        });
        setTimeout(function() {
          window.location.assign(redirectUrl)
        }, 1500);

        ga('send', {hitType: 'event', eventCategory: 'Membership Form', eventAction: 'Submission'});
        fbq('track', 'Complete Registration');
        fbq('track', 'NewMember');  // a different pixel thing to the above, keep both.

      } else if (response.status === 409) {
        console.log('Duplicate email detected');
        this.setState({
          isLoading: false,
          serverErrorMsg: "Error. Email already exists. Please update details instead of re-registering."
        });
      } else {
        this.setState({
          isLoading: false,
          serverErrorMsg: "Server error, " + response.statusText ? response.statusText : null
        });
      }
    }.bind(this))
  },
  enableButton() {
    this.setState({ canSubmit: true });
  },
  disableButton() {
    this.setState({ canSubmit: false });
  },
  closeModal() {
    this.setState({ showSubmissionModal: false });
  },

  checkPC(evt) {
    const pcTest = /\d{4}/;
    const pc = evt.currentTarget.value;
    console.log(pc);
    if (pcTest.test(pc)) {
      this.updateSuburbs(pc);
    }
  },

  checkSuburb(evt) {
    const suburb = evt.currentTarget.value;
    this.updateStreets(suburb);
  },

  updateSuburbs(pc){
    this.setState({loading: { suburb: true }, suburbs: ['Loading...'], postcode: pc});
    const outer = this;
    const setStateUnk = function() { outer.setState({suburbs: ["Unknown Postcode"]}); };
    HttpHelpers.getSuburbs(pc, function(err, resp){
      if (err) {
        console.log(err);
        setStateUnk();
      } else {
        console.log(resp);
        if (resp.body.suburbs.length == 0)
          setStateUnk();
        else {
          outer.setState({suburbs: _.concat(["Choose Suburb..."], resp.body.suburbs)});
          outer.updateStreets(resp.body.suburbs[0]);
        }
      }
    });
  },

  updateStreets(suburb){
    const outer = this;
    this.setState({loading: { street: true }, streets:["Loading..."], suburb: suburb});
    HttpHelpers.getStreets(this.state.postcode, suburb, function(err, resp){
      if(err){
        console.log(err);
        outer.setState({streets:["Unknown Suburb"]});
      } else {
        console.log(resp);
        outer.setState({streets: _.concat(["Choose Street..."], resp.body.streets)});
      }
    })
  },

  writeToState(_key){
    return function(evt){
      let newState = {};
      newState[_key] = evt.currentTarget.value;
      this.setState(newState);
    }
  },

  render() {
    return (
      <Formsy.Form
        onSubmit={this.submit}
        onValid={this.enableButton}
        onInvalid={this.disableButton}
        onChange={this.validateForm}>

Sign up below, it's quick and easy

              Please make sure your details exactly match those on the electoral roll. You can confirm them on the
               AEC website.

          <MyInput
            inputClass="checkbox"
            type="checkbox"
            name="onAECRoll"
            title="I am on the Australian Electoral Roll."
            validationError="First name is required"
            value={false} />

          <SectionTitle text="1. Name"/>

          <MyInput
            inputClass="input"
            name="fname"
            title="Legal first name"
            autocomplete="given-name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

            <MyInput
              inputClass="input"
              name="mnames"
              autocomplete="false"
              title="Legal middle name"
              value={__DEV__ ? "asdf" : ""}
              validationErrors={{
                isSpecialWords: 'Only letters please'
              }}
              formNoValidate />

          <MyInput
            inputClass="input"
            name="lname"
            autocomplete="family-name"
            title="Legal last name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

          <SectionTitle text="2. Address"/>

          <MySelect
            inputClass="input"
            name="addr_country"
            title="Country"
            validationError="Country Required"
            options={[{title: 'Australia', value: 'au'}]}
            onChange={this.writeToState('country')}
            />

          <MyInput
            inputClass="input"
            name="addr_postcode"
            title="Postcode"
            validations={_.includes(['au'], this.state.country) ? "isNumeric,isLength:4" : null}
            pattern={_.includes(['au'], this.state.country) ? "\\d*" : ""}
            value={__DEV__ ? "2000" : ""}
            validationErrors={{
              isRequired: 'Postcode required',
              isNumeric: 'Only numbers allowed',
              isLength: 'Length needs to be 4 digits'
            }}
            onChange={this.checkPC}
            required />

          <MySelect
            inputClass="input"
            name="addr_suburb"
            title="Suburb"
            validationError="Suburb required"
            options={this.state.suburbs}
            value={__DEV__ ? "HAYMARKET (NSW)" : ""}
            onChange={this.checkSuburb}
            validations={{
              notDefault: function(values, value){
                return !_.includes(value, '...') ? true : "Must choose a suburb";
              }
            }}
            required />

            <MyInput
              inputClass="input"
              className="col-4 inline-block px1 relative"
              name="addr_street_no"
              title="Unit / Street No."
              validationError="Unit and Street Number required"
              placeholder="eg: u32 / 117"
              value={__DEV__ ? "13 / 37" : ""}
              required
              />

            <MySelect
              className="col-8 mx-auto inline-block px1 relative"
              inputClass="input"
              name="addr_street"
              title="Street"
              validationError="Street address is required"
              value={__DEV__ ? "asdf" : ""}
              validationErrors={{
                isRequired: 'Street address required'
              }}
              options={this.state.streets}
              required />

          <SectionTitle text="3. Date of Birth" infoText="(Required by AEC)"/>

              <MyInput
                inputClass="input"
                name="dobDay"
                title="Day"
                placeholder="DD"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /(0[1-9]|[12]\d|3[01])/
                }}
                validationErrors={{
                  isRequired: 'Day required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Length must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobMonth"
                title="Month"
                placeholder="MM"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /^(0[1-9]|1[0-2])$/
                }}
                validationErrors={{
                  isRequired: 'Month required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Month must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobYear"
                title="Year"
                placeholder="YYYY"
                pattern="\d*"
                value={__DEV__ ? "2000" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 4,
                  matchRegexp: /^(190[0-9]|19[1-9]\d|200\d|201[0-6])$/
                }}
                validationErrors={{
                  isRequired: 'Year required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Year must be 4 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

          <SectionTitle text="4. Contact details"/>
          <MyInput
            inputClass="input"
            type="tel"
            name="contact_number"
            pattern="\d*"
            title="Phone"
            value={__DEV__ ? "1234567890" : ""}
            validations={{
              minLength: 8
            }}
            validationErrors={{
              isRequired: 'Phone number is required',
              minLength: 'Needs to be at least 8 digits.'
            }}
            required />

          <MyInput
            inputClass="input"
            name="email"
            title="Email"
            type="email"
            pattern="[^ @]*@[^ @]*"
            value={__DEV__ ? randomEmail + "@xk.io" : ""}
            validations="isEmail"
            validationError="This is not a valid email"
            autocomplete="email"
            required />

          <SectionTitle text="5. Get Involved"/>

          { this.props.onReferrer
            ?
            <MyInput
              inputClass="input hide"
              name="referred_by"
              value={this.props.onReferrer} />
             :

                <MyInput
                  inputClass="input"
                  name="referred_by"
                  title="How did you hear about Flux?"
                  subtext="(optional)" />

}

          {/*<MyInput
            inputClass="input"
            type="checkbox"
            name="mailing-list"
            title="Send me Flux news and important updates."
            value={true}
             />*/}

         <MyTextarea
             rows="3"
             inputClass="input"
             name="member_comment"
             title="Comments / Notes"
             value={__DEV__ ? "DEV SUBMISSION - PLEASE DELETE" : ""}
             subtext="(Optional, Anything you'd like to add, about yourself, us, or anything, really.)" />

           <MyInput
             inputClass="input"
             type="checkbox"
             name="volunteer"
             title="I'm interested in volunteering"
             value={false}
              />

              <button type="submit" className="h3 btn btn-primary" disabled={!this.state.canSubmit}>Submit chevron_right</button>

            {!this.state.canSubmit
              &&

                *

You can't submit until you fill out all required fields

}

             <Modal
              isOpen={this.state.showSubmissionModal}
              contentLabel="Processing Registration"
              onRequestClose={this.closeModal}
              style={{
                overlay: {
                  backgroundColor: "rgba(20, 20, 20, 0.5)",
                },
                content: {

                }
              }}
             >
               {this.state.isLoading
                ?

Registering...

                : this.state.serverSuccessMsg
                ?

{this.state.serverSuccessMsg}

                    Redirecting...

                : this.state.serverErrorMsg
                ?

{this.state.serverErrorMsg}

                    <button className="btn btn-primary mx-auto h1" onClick={this.closeModal}>Close</button>

                : null}
             </Modal>

            lock
            Your details will be kept absolutely confidential and will only be used for party business.

      </Formsy.Form>
    );
  }
});

export default FormContainer;
<commit_msg>disable inputs when loading<commit_after>import React from 'react'
import Formsy from 'formsy-react'
import Modal from 'react-modal';
import MyInput from '../components/my-input'
import MySelect from '../components/my-select'
import MyTextarea from '../components/my-textarea'
import SectionTitle from '../components/section-title'
import HttpHelpers from '../utils/http-helpers'
var _ = require('lodash');

const redirectUrl = (window.location.href.split("/\?", 2)[0] + '/step2').replace("//step2", "/step2");
const randomEmail = Math.random().toString(36).substr(2,10);

const FormContainer = React.createClass({
  getInitialState() {
    return {
      canSubmit: false,
      isLoading: false,
      validationErrors: {},
      serverErrorMsg: false,
      serverSuccessMsg: false,
      showSubmissionModal: false,
      loading: {
        'street': false,
        'suburb': false,
      },
      suburbs: ['Enter Postcode...'],
      streets: ['Choose Suburb...'],
      postcode: '0000',
      country: 'au',
    };
  },
  submit(data) {
    if (data.mnames === undefined) { data.mnames = ""}
    if (data.referred_by === undefined) { data.referred_by = ""}
    if (data.member_comment === undefined) { data.member_comment = ""}
    data.dob = data.dobYear + '-' + data.dobMonth + '-' + data.dobDay + 'T12:00:00';
    data.address = _.join([data.addr_street_no, data.addr_street, data.addr_suburb, data.addr_postcode], "; ");
    data.name = _.join([data.fname, data.mnames, data.lname], ", ");

    this.setState({isLoading: true, showSubmissionModal: true});
    HttpHelpers.sendForm(data, function(response){

      if (__DEV__) {
        console.log(response);
        console.log(data);
      }

      if (response.ok && response.status === 200 && response.body.success === true) {
        this.setState({
          isLoading: false,
          serverSuccessMsg: "Success"
        });
        setTimeout(function() {
          window.location.assign(redirectUrl)
        }, 1500);

        ga('send', {hitType: 'event', eventCategory: 'Membership Form', eventAction: 'Submission'});
        fbq('track', 'Complete Registration');
        fbq('track', 'NewMember');  // a different pixel thing to the above, keep both.

      } else if (response.status === 409) {
        console.log('Duplicate email detected');
        this.setState({
          isLoading: false,
          serverErrorMsg: "Error. Email already exists. Please update details instead of re-registering."
        });
      } else {
        this.setState({
          isLoading: false,
          serverErrorMsg: "Server error, " + response.statusText ? response.statusText : null
        });
      }
    }.bind(this))
  },
  enableButton() {
    this.setState({ canSubmit: true });
  },
  disableButton() {
    this.setState({ canSubmit: false });
  },
  closeModal() {
    this.setState({ showSubmissionModal: false });
  },

  checkPC(evt) {
    const pcTest = /\d{4}/;
    const pc = evt.currentTarget.value;
    console.log(pc);
    if (pcTest.test(pc)) {
      this.updateSuburbs(pc);
    }
  },

  checkSuburb(evt) {
    const suburb = evt.currentTarget.value;
    this.updateStreets(suburb);
  },

  updateSuburbs(pc){
    this.setState({loading: { suburb: true }, suburbs: ['Loading...'], postcode: pc});
    const outer = this;
    const setStateUnk = function() { outer.setState({suburbs: ["Unknown Postcode"]}); };
    HttpHelpers.getSuburbs(pc, function(err, resp){
      if (err) {
        console.log(err);
        setStateUnk();
      } else {
        console.log(resp);
        if (resp.body.suburbs.length == 0)
          setStateUnk();
        else {
          outer.setState({suburbs: _.concat(["Choose Suburb..."], resp.body.suburbs)});
          outer.updateStreets(resp.body.suburbs[0]);
        }
      }
    });
  },

  updateStreets(suburb){
    const outer = this;
    this.setState({loading: { street: true }, streets:["Loading..."], suburb: suburb});
    HttpHelpers.getStreets(this.state.postcode, suburb, function(err, resp){
      if(err){
        console.log(err);
        outer.setState({streets:["Unknown Suburb"]});
      } else {
        console.log(resp);
        outer.setState({streets: _.concat(["Choose Street..."], resp.body.streets)});
      }
    })
  },

  writeToState(_key){
    return function(evt){
      let newState = {};
      newState[_key] = evt.currentTarget.value;
      this.setState(newState);
    }
  },

  render() {
    return (
      <Formsy.Form
        onSubmit={this.submit}
        onValid={this.enableButton}
        onInvalid={this.disableButton}
        onChange={this.validateForm}>

Sign up below, it's quick and easy

              Please make sure your details exactly match those on the electoral roll. You can confirm them on the
               AEC website.

          <MyInput
            inputClass="checkbox"
            type="checkbox"
            name="onAECRoll"
            title="I am on the Australian Electoral Roll."
            validationError="First name is required"
            value={false} />

          <SectionTitle text="1. Name"/>

          <MyInput
            inputClass="input"
            name="fname"
            title="Legal first name"
            autocomplete="given-name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

            <MyInput
              inputClass="input"
              name="mnames"
              autocomplete="false"
              title="Legal middle name"
              value={__DEV__ ? "asdf" : ""}
              validationErrors={{
                isSpecialWords: 'Only letters please'
              }}
              formNoValidate />

          <MyInput
            inputClass="input"
            name="lname"
            autocomplete="family-name"
            title="Legal last name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

          <SectionTitle text="2. Address"/>

          <MySelect
            inputClass="input"
            name="addr_country"
            title="Country"
            validationError="Country Required"
            options={[{title: 'Australia', value: 'au'}]}
            onChange={this.writeToState('country')}
            />

          <MyInput
            inputClass="input"
            name="addr_postcode"
            title="Postcode"
            validations={_.includes(['au'], this.state.country) ? "isNumeric,isLength:4" : null}
            pattern={_.includes(['au'], this.state.country) ? "\\d*" : ""}
            value={__DEV__ ? "2000" : ""}
            validationErrors={{
              isRequired: 'Postcode required',
              isNumeric: 'Only numbers allowed',
              isLength: 'Length needs to be 4 digits'
            }}
            onChange={this.checkPC}
            required />

          <MySelect
            inputClass="input"
            name="addr_suburb"
            title="Suburb"
            validationError="Suburb required"
            options={this.state.suburbs}
            value={__DEV__ ? "HAYMARKET (NSW)" : ""}
            disabled={this.state.suburbs[0] == 'Loading...'}
            onChange={this.checkSuburb}
            validations={{
              notDefault: function(values, value){
                return !_.includes(value, '...') ? true : "Must choose a suburb";
              }
            }}
            required />

            <MyInput
              inputClass="input"
              className="col-4 inline-block px1 relative"
              name="addr_street_no"
              title="Unit / Street No."
              validationError="Unit and Street Number required"
              placeholder="eg: u32 / 117"
              value={__DEV__ ? "13 / 37" : ""}
              required
              />

            <MySelect
              className="col-8 mx-auto inline-block px1 relative"
              inputClass="input"
              name="addr_street"
              title="Street"
              validationError="Street address is required"
              value={__DEV__ ? "asdf" : ""}
              disabled={this.state.streets[0] == 'Loading...'}
              validationErrors={{
                isRequired: 'Street address required'
              }}
              options={this.state.streets}
              required />

          <SectionTitle text="3. Date of Birth" infoText="(Required by AEC)"/>

              <MyInput
                inputClass="input"
                name="dobDay"
                title="Day"
                placeholder="DD"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /(0[1-9]|[12]\d|3[01])/
                }}
                validationErrors={{
                  isRequired: 'Day required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Length must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobMonth"
                title="Month"
                placeholder="MM"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /^(0[1-9]|1[0-2])$/
                }}
                validationErrors={{
                  isRequired: 'Month required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Month must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobYear"
                title="Year"
                placeholder="YYYY"
                pattern="\d*"
                value={__DEV__ ? "2000" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 4,
                  matchRegexp: /^(190[0-9]|19[1-9]\d|200\d|201[0-6])$/
                }}
                validationErrors={{
                  isRequired: 'Year required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Year must be 4 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

          <SectionTitle text="4. Contact details"/>
          <MyInput
            inputClass="input"
            type="tel"
            name="contact_number"
            pattern="\d*"
            title="Phone"
            value={__DEV__ ? "1234567890" : ""}
            validations={{
              minLength: 8
            }}
            validationErrors={{
              isRequired: 'Phone number is required',
              minLength: 'Needs to be at least 8 digits.'
            }}
            required />

          <MyInput
            inputClass="input"
            name="email"
            title="Email"
            type="email"
            pattern="[^ @]*@[^ @]*"
            value={__DEV__ ? randomEmail + "@xk.io" : ""}
            validations="isEmail"
            validationError="This is not a valid email"
            autocomplete="email"
            required />

          <SectionTitle text="5. Get Involved"/>

          { this.props.onReferrer
            ?
            <MyInput
              inputClass="input hide"
              name="referred_by"
              value={this.props.onReferrer} />
             :

                <MyInput
                  inputClass="input"
                  name="referred_by"
                  title="How did you hear about Flux?"
                  subtext="(optional)" />

}

          {/*<MyInput
            inputClass="input"
            type="checkbox"
            name="mailing-list"
            title="Send me Flux news and important updates."
            value={true}
             />*/}

         <MyTextarea
             rows="3"
             inputClass="input"
             name="member_comment"
             title="Comments / Notes"
             value={__DEV__ ? "DEV SUBMISSION - PLEASE DELETE" : ""}
             subtext="(Optional, Anything you'd like to add, about yourself, us, or anything, really.)" />

           <MyInput
             inputClass="input"
             type="checkbox"
             name="volunteer"
             title="I'm interested in volunteering"
             value={false}
              />

              <button type="submit" className="h3 btn btn-primary" disabled={!this.state.canSubmit}>Submit chevron_right</button>

            {!this.state.canSubmit
              &&

                *

You can't submit until you fill out all required fields

}

             <Modal
              isOpen={this.state.showSubmissionModal}
              contentLabel="Processing Registration"
              onRequestClose={this.closeModal}
              style={{
                overlay: {
                  backgroundColor: "rgba(20, 20, 20, 0.5)",
                },
                content: {

                }
              }}
             >
               {this.state.isLoading
                ?

Registering...

                : this.state.serverSuccessMsg
                ?

{this.state.serverSuccessMsg}

                    Redirecting...

                : this.state.serverErrorMsg
                ?

{this.state.serverErrorMsg}

                    <button className="btn btn-primary mx-auto h1" onClick={this.closeModal}>Close</button>

                : null}
             </Modal>

            lock
            Your details will be kept absolutely confidential and will only be used for party business.

      </Formsy.Form>
    );
  }
});

export default FormContainer;
<|endoftext|>