<commit_before>/*
 * jquery.lighty
 *
 *
 * Copyright (c) 2012 Andreas Hultgren
 * Licensed under the MIT license.
 */

 /*
  * Todo and other ponderings
  *
  */

(function($) {
	// Private vars
	var settings = {
			baseZ: 5,
			bgColor: 'rgba(0,0,0,0.85)',
			data: function(){
				return {
					jsonposts: 1
				};
			},
			prefix: 'lighty-',
			itemTemplate: function(data){
				var contents = '' + '
' + data[0].the_excerpt + '
';

				return {
					markup: contents,
					width: data[0].the_post_thumbnail[1],
					height: data[0].the_post_thumbnail[2]
				};
			}
		},
		bg,
		container,
		current,
		selector;

	// Private methods
	var showLightbox = function(){
		var that = $(this);

		// Save this as currently lightboxed
		current = that;

		// Show bg and loading icon
		bg.show();
		container
			.empty()
			.append('

')
			.css({
				top: that.offset().top - $(window).scrollTop,
				left: that.offset().left,
				width: that.width(),
				height: that.height()
			})
			.show();

		// Get data
		$.ajax({
			url: that.attr('href'),
			data: settings.data.call(that),
			dataType: 'json',
			error: function(xhr, text){
				//## errorTemplate?
			},
			success: function(data){
				// Input the fetched data into template
				var content = settings.itemTemplate.call(this, data);

				// Resize the container
				container.lighty('resize', {width: content.width, height: content.height}, function(){
					// Swap from loader to content
					container.empty().append(content.markup);
				});
			}
		});

		return this;
	},
	hideLightbox = function(){
		bg.hide();
		container.hide().empty();
		current = undefined;
	};

	// Public methods
	var methods = {
		init: function(options){
			selector = this;

			// Extend default settings
			$.extend(settings, options);

			// Prepare bakground
			bg = $(document.createElement('div'))
				.attr('id', settings.prefix + 'bg')
				.css({
					background: settings.bgColor,
					position: 'fixed',
					top: 0,
					left: 0,
					right: 0,
					bottom: 0,
					'z-index': settings.baseZ
				})
				.hide()
				.appendTo('body')
				.click(function(){
					hideLightbox();
				});

			// Prepare lightbox container
			container = $(document.createElement('div'))
				.attr('id', settings.prefix + 'container')
				.css({
					position: 'fixed',
					left: $(window).width()/2,
					top: $(window).height()/2,
					'z-index': settings.baseZ + 1
				})
				.hide()
				.appendTo('body');

			// Pressing right and left keys
			$(window).keydown(function(e){
				var newBox;

				if( current ){
					if( e.which === 39 ){
						// Right
						newBox = selector[selector.index(current)+1];
					}
					else if( e.which === 37 ){
						// Left
						newBox = selector[selector.index(current)-1];
					}

					if( newBox ){
						showLightbox.call(newBox);
					}
					else if( !newBox || e.which === 27 ){
						// Escape
						hideLightbox();
					}
				}
			});

			// Prepare each lightboxed item
			return this.each(function(){
				$(this).click(function(e){
					e.preventDefault();
					showLightbox.call(this);
				});
			});
		},
		resize: function(args, callback){
			return this.each(function(){
				var $window = $(window),
					windowWidth = $window.width(),
					windowHeight = $window.height(),
					diff;

				// Make sure args is an object
				args = args || {};

				// Make sure there's something to animate to
				args.height = args.height || $(this).height();
				args.width = args.width || $(this).width();

				// Make sure the image is never larger than the screen
				//## Must compensate for padding and shit...
				if( args.width > windowWidth - 50 ){
					diff = (windowWidth - 50) / args.width;
					args.width *= diff;
					args.height *= diff;
				}
				if( args.height > windowHeight - 100 ){
					diff = (windowHeight - 100) / args.height;
					args.width *= diff;
					args.height *= diff;
				}

				// Animate to the center
				$(this).animate({
					width: args.width,
					height: args.height,
					left: windowWidth/2 - args.width/2,
					top: windowHeight/2 - args.height/2
				},
				{
					duration: 200,
					complete: function(){
						if( typeof callback === 'function' ){
							callback();
						}
					}
				});
			});
		}
	};

	// Make things accessible
	$.fn.lighty = function(method) {
		// Method calling logic
		if( methods[method] ){
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		}
		else if( typeof method === 'object' || ! method ){
			return methods.init.apply( this, arguments );
		}
		else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.lighty' );
		}
	};
}(jQuery));<commit_msg>Minor fix, removed styling from the js<commit_after>/*
 * jquery.lighty
 *
 *
 * Copyright (c) 2012 Andreas Hultgren
 * Licensed under the MIT license.
 */

 /*
  * Todo and other ponderings
  *
  */

(function($) {
	// Private vars
	var settings = {
			baseZ: 5,
			data: function(){
				return {
					jsonposts: 1
				};
			},
			prefix: 'lighty-',
			itemTemplate: function(data){
				var contents = '' + '
' + data[0].the_excerpt + '
';

				return {
					markup: contents,
					width: data[0].the_post_thumbnail[1],
					height: data[0].the_post_thumbnail[2]
				};
			}
		},
		bg,
		container,
		current,
		selector;

	// Private methods
	var showLightbox = function(){
		var that = $(this);

		// Save this as currently lightboxed
		current = that;

		// Show bg and loading icon
		bg.show();
		container
			.empty()
			.append('

')
			.css({
				top: that.offset().top - $(window).scrollTop,
				left: that.offset().left,
				width: that.width(),
				height: that.height()
			})
			.show();

		// Get data
		$.ajax({
			url: that.attr('href'),
			data: settings.data.call(that),
			dataType: 'json',
			error: function(xhr, text){
				//## errorTemplate?
			},
			success: function(data){
				// Input the fetched data into template
				var content = settings.itemTemplate.call(this, data);

				// Resize the container
				container.lighty('resize', {width: content.width, height: content.height}, function(){
					// Swap from loader to content
					container.empty().append(content.markup);
				});
			}
		});

		return this;
	},
	hideLightbox = function(){
		bg.hide();
		container.hide().empty();
		current = undefined;
	};

	// Public methods
	var methods = {
		init: function(options){
			selector = this;

			// Extend default settings
			$.extend(settings, options);

			// Prepare bakground
			bg = $(document.createElement('div'))
				.attr('id', settings.prefix + 'bg')
				.css({
					position: 'fixed',
					top: 0,
					left: 0,
					right: 0,
					bottom: 0,
					'z-index': settings.baseZ
				})
				.hide()
				.appendTo('body')
				.click(function(){
					hideLightbox();
				});

			// Prepare lightbox container
			container = $(document.createElement('div'))
				.attr('id', settings.prefix + 'container')
				.css({
					position: 'fixed',
					left: $(window).width()/2,
					top: $(window).height()/2,
					'z-index': settings.baseZ + 1
				})
				.hide()
				.appendTo('body');

			// Pressing right and left keys
			$(window).keydown(function(e){
				var newBox;

				if( current ){
					if( e.which === 39 ){
						// Right
						newBox = selector[selector.index(current)+1];
					}
					else if( e.which === 37 ){
						// Left
						newBox = selector[selector.index(current)-1];
					}

					if( newBox ){
						showLightbox.call(newBox);
					}
					else if( !newBox || e.which === 27 ){
						// Escape
						hideLightbox();
					}
				}
			});

			// Prepare each lightboxed item
			return this.each(function(){
				$(this).click(function(e){
					e.preventDefault();
					showLightbox.call(this);
				});
			});
		},
		resize: function(args, callback){
			return this.each(function(){
				var $window = $(window),
					windowWidth = $window.width(),
					windowHeight = $window.height(),
					diff;

				// Make sure args is an object
				args = args || {};

				// Make sure there's something to animate to
				args.height = args.height || $(this).height();
				args.width = args.width || $(this).width();

				// Make sure the image is never larger than the screen
				//## Must compensate for padding and shit...
				if( args.width > windowWidth - 50 ){
					diff = (windowWidth - 50) / args.width;
					args.width *= diff;
					args.height *= diff;
				}
				if( args.height > windowHeight - 100 ){
					diff = (windowHeight - 100) / args.height;
					args.width *= diff;
					args.height *= diff;
				}

				// Animate to the center
				$(this).animate({
					width: args.width,
					height: args.height,
					left: windowWidth/2 - args.width/2,
					top: windowHeight/2 - args.height/2
				},
				{
					duration: 200,
					complete: function(){
						if( typeof callback === 'function' ){
							callback();
						}
					}
				});
			});
		}
	};

	// Make things accessible
	$.fn.lighty = function(method) {
		// Method calling logic
		if( methods[method] ){
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		}
		else if( typeof method === 'object' || ! method ){
			return methods.init.apply( this, arguments );
		}
		else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.lighty' );
		}
	};
}(jQuery));<|endoftext|>


<commit_before>var validator = require('../index');
var format = require('util').format;

function test(options) {
  var args = options.args || [];

  args.unshift(null);

  Object.keys(options.expect).forEach(function (input) {
    args[0] = input;
    var result = validator[options.sanitizer].apply(validator, args);
    var expected = options.expect[input];
    if (isNaN(result) && !result.length && isNaN(expected)) {
      return;
    }

    if (result !== expected) {
      var warning = format('validator.%s(%s) returned "%s" but should have returned "%s"',
        options.sanitizer, args.join(', '), result, expected);

      throw new Error(warning);
    }
  });
}

describe('Sanitizers', function () {
  it('should sanitize boolean strings', function () {
    test({
      sanitizer: 'toBoolean',
      expect: {
        '0': false,
        '': false,
        '1': true,
        'true': true,
        'foobar': true,
        '   ': true,
      },
    });
    test({
      sanitizer: 'toBoolean',
      args: [true], // strict
      expect: {
        '0': false,
        '': false,
        '1': true,
        'true': true,
        'foobar': false,
        '   ': false,
      },
    });
  });

  it('should trim whitespace', function () {
    test({
      sanitizer: 'trim',
      expect: {
        '  \r\n\tfoo  \r\n\t   ': 'foo',
        '      \r': '',
      },
    });

    test({
      sanitizer: 'ltrim',
      expect: {
        '  \r\n\tfoo  \r\n\t   ': 'foo  \r\n\t   ',
        '   \t  \n': '',
      },
    });

    test({
      sanitizer: 'rtrim',
      expect: {
        '  \r\n\tfoo  \r\n\t   ': '  \r\n\tfoo',
        ' \r\n  \t': '',
      },
    });
  });

  it('should trim custom characters', function () {
    test({
      sanitizer: 'trim',
      args: ['01'],
      expect: { '010100201000': '2' },
    });

    test({
      sanitizer: 'ltrim',
      args: ['01'],
      expect: { '010100201000': '201000' },
    });

    test({
      sanitizer: 'rtrim',
      args: ['01'],
      expect: { '010100201000': '0101002' },
    });
  });

  it('should convert strings to integers', function () {
    test({
      sanitizer: 'toInt',
      expect: {
        '3': 3,
        ' 3 ': 3,
        '2.4': 2,
        'foo': NaN,
      },
    });

    test({
      sanitizer: 'toInt',
      args: [16],
      expect: { 'ff': 255 },
    });
  });

  it('should convert strings to floats', function () {
    test({
      sanitizer: 'toFloat',
      expect: {
        '2': 2.0,
        '2.': 2.0,
        '-2.5': -2.5,
        '.5': 0.5,
        'foo': NaN,
      },
    });
  });

  it('should escape HTML', function () {
    test({
      sanitizer: 'escape',
      expect: {
        '<script> alert("xss&fun"); </script>':
            '<script> alert("xss&fun"); </script>',

        "<script> alert('xss&fun'); </script>":
            '<script> alert('xss&fun'); </script>',

        'Backtick: `':
            'Backtick: `',
      },
    });
  });

  it('should unescape HTML', function () {
    test({
      sanitizer: 'unescape',
      expect: {
        '<script> alert("xss&fun"); </script>':
             '<script> alert("xss&fun"); </script>',

        '<script> alert('xss&fun'); </script>':
            "<script> alert('xss&fun'); </script>",

        'Backtick: `':
            'Backtick: `',
      },
    });
  });

  it('should remove control characters (<32 and 127)', function () {
    // Check basic functionality
    test({
      sanitizer: 'stripLow',
      expect: {
        'foo\x00': 'foo',
        '\x7Ffoo\x02': 'foo',
        '\x01\x09': '',
        'foo\x0A\x0D': 'foo',
      },
    });
    // Unicode safety
    test({
      sanitizer: 'stripLow',
      expect: {
        'perch\u00e9': 'perch\u00e9',
        '\u20ac': '\u20ac',
        '\u2206\x0A': '\u2206',
        '\ud83d\ude04': '\ud83d\ude04',
      },
    });
    // Preserve newlines
    test({
      sanitizer: 'stripLow',
      args: [true], // keep_new_lines
      expect: {
        'foo\x0A\x0D': 'foo\x0A\x0D',
        '\x03foo\x0A\x0D': 'foo\x0A\x0D',
      },
    });
  });

  it('should sanitize a string based on a whitelist', function () {
    test({
      sanitizer: 'whitelist',
      args: ['abc'],
      expect: {
        'abcdef': 'abc',
        'aaaaaaaaaabbbbbbbbbb': 'aaaaaaaaaabbbbbbbbbb',
        'a1b2c3': 'abc',
        '   ': '',
      },
    });
  });

  it('should sanitize a string based on a blacklist', function () {
    test({
      sanitizer: 'blacklist',
      args: ['abc'],
      expect: {
        'abcdef': 'def',
        'aaaaaaaaaabbbbbbbbbb': '',
        'a1b2c3': '123',
        '   ': '   ',
      },
    });
  });

  it('should normalize an email based on domain', function () {
    test({
      sanitizer: 'normalizeEmail',
      expect: {
        'test@me.com': 'test@me.com',
        'some.name@gmail.com': 'somename@gmail.com',
        'some.name@googleMail.com': 'somename@gmail.com',
        'some.name+extension@gmail.com': 'somename@gmail.com',
        'some.Name+extension@GoogleMail.com': 'somename@gmail.com',
        'some.name.middleName+extension@gmail.com': 'somenamemiddlename@gmail.com',
        'some.name.middleName+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
        'some.name.midd.leNa.me.+extension@gmail.com': 'somenamemiddlename@gmail.com',
        'some.name.midd.leNa.me.+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
        'some.name+extension@unknown.com': 'some.name+extension@unknown.com',
        'hans@m端ller.com': 'hans@m端ller.com',
        'an invalid email address': false,
        '': false,
        '+extension@gmail.com': false,
        '...@gmail.com': false,
        '.+extension@googlemail.com': false,
        'some.name.midd..leNa...me...+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
      },
    });

    test({
      sanitizer: 'normalizeEmail',
      args: [{ lowercase: false }],
      expect: {
        'test@me.com': 'test@me.com',
        'hans@m端ller.com': 'hans@m端ller.com',
        'test@ME.COM': 'test@me.com', // Hostname is always lowercased,
        'TEST@me.com': 'TEST@me.com',
        'TEST@ME.COM': 'TEST@me.com',
        'blAH@x.com': 'blAH@x.com',
          // Domains that are known for being case-insensitive are always lowercased,
        'SOME.name@GMAIL.com': 'somename@gmail.com',
        'SOME.name.middleName+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
        'SOME.name.midd.leNa.me.+extension@gmail.com': 'somenamemiddlename@gmail.com',
      },
    });

    test({
      sanitizer: 'normalizeEmail',
      args: [{ remove_dots: false }],
      expect: {
        'SOME.name@GMAIL.com': 'some.name@gmail.com',
      },
    });

    test({
      sanitizer: 'normalizeEmail',
      args: [{ remove_extension: false }],
      expect: {
        'foo+bar@gmail.com': 'foo+bar@gmail.com',
      },
    });
  });
});
<commit_msg>Adding tests for previous commit<commit_after>var validator = require('../index');
var format = require('util').format;

function test(options) {
  var args = options.args || [];

  args.unshift(null);

  Object.keys(options.expect).forEach(function (input) {
    args[0] = input;
    var result = validator[options.sanitizer].apply(validator, args);
    var expected = options.expect[input];
    if (isNaN(result) && !result.length && isNaN(expected)) {
      return;
    }

    if (result !== expected) {
      var warning = format('validator.%s(%s) returned "%s" but should have returned "%s"',
        options.sanitizer, args.join(', '), result, expected);

      throw new Error(warning);
    }
  });
}

describe('Sanitizers', function () {
  it('should sanitize boolean strings', function () {
    test({
      sanitizer: 'toBoolean',
      expect: {
        '0': false,
        '': false,
        '1': true,
        'true': true,
        'foobar': true,
        '   ': true,
      },
    });
    test({
      sanitizer: 'toBoolean',
      args: [true], // strict
      expect: {
        '0': false,
        '': false,
        '1': true,
        'true': true,
        'foobar': false,
        '   ': false,
      },
    });
  });

  it('should trim whitespace', function () {
    test({
      sanitizer: 'trim',
      expect: {
        '  \r\n\tfoo  \r\n\t   ': 'foo',
        '      \r': '',
      },
    });

    test({
      sanitizer: 'ltrim',
      expect: {
        '  \r\n\tfoo  \r\n\t   ': 'foo  \r\n\t   ',
        '   \t  \n': '',
      },
    });

    test({
      sanitizer: 'rtrim',
      expect: {
        '  \r\n\tfoo  \r\n\t   ': '  \r\n\tfoo',
        ' \r\n  \t': '',
      },
    });
  });

  it('should trim custom characters', function () {
    test({
      sanitizer: 'trim',
      args: ['01'],
      expect: { '010100201000': '2' },
    });

    test({
      sanitizer: 'ltrim',
      args: ['01'],
      expect: { '010100201000': '201000' },
    });

    test({
      sanitizer: 'rtrim',
      args: ['01'],
      expect: { '010100201000': '0101002' },
    });
  });

  it('should convert strings to integers', function () {
    test({
      sanitizer: 'toInt',
      expect: {
        '3': 3,
        ' 3 ': 3,
        '2.4': 2,
        'foo': NaN,
      },
    });

    test({
      sanitizer: 'toInt',
      args: [16],
      expect: { 'ff': 255 },
    });
  });

  it('should convert strings to floats', function () {
    test({
      sanitizer: 'toFloat',
      expect: {
        '2': 2.0,
        '2.': 2.0,
        '-2.5': -2.5,
        '.5': 0.5,
        'foo': NaN,
      },
    });
  });

  it('should escape HTML', function () {
    test({
      sanitizer: 'escape',
      expect: {
        '<script> alert("xss&fun"); </script>':
            '<script> alert("xss&fun"); </script>',

        "<script> alert('xss&fun'); </script>":
            '<script> alert('xss&fun'); </script>',

        'Backtick: `':
            'Backtick: `',
      },
    });
  });

  it('should unescape HTML', function () {
    test({
      sanitizer: 'unescape',
      expect: {
        '<script> alert("xss&fun"); </script>':
             '<script> alert("xss&fun"); </script>',

        '<script> alert('xss&fun'); </script>':
            "<script> alert('xss&fun'); </script>",

        'Backtick: `':
            'Backtick: `',
      },
    });
  });

  it('should remove control characters (<32 and 127)', function () {
    // Check basic functionality
    test({
      sanitizer: 'stripLow',
      expect: {
        'foo\x00': 'foo',
        '\x7Ffoo\x02': 'foo',
        '\x01\x09': '',
        'foo\x0A\x0D': 'foo',
      },
    });
    // Unicode safety
    test({
      sanitizer: 'stripLow',
      expect: {
        'perch\u00e9': 'perch\u00e9',
        '\u20ac': '\u20ac',
        '\u2206\x0A': '\u2206',
        '\ud83d\ude04': '\ud83d\ude04',
      },
    });
    // Preserve newlines
    test({
      sanitizer: 'stripLow',
      args: [true], // keep_new_lines
      expect: {
        'foo\x0A\x0D': 'foo\x0A\x0D',
        '\x03foo\x0A\x0D': 'foo\x0A\x0D',
      },
    });
  });

  it('should sanitize a string based on a whitelist', function () {
    test({
      sanitizer: 'whitelist',
      args: ['abc'],
      expect: {
        'abcdef': 'abc',
        'aaaaaaaaaabbbbbbbbbb': 'aaaaaaaaaabbbbbbbbbb',
        'a1b2c3': 'abc',
        '   ': '',
      },
    });
  });

  it('should sanitize a string based on a blacklist', function () {
    test({
      sanitizer: 'blacklist',
      args: ['abc'],
      expect: {
        'abcdef': 'def',
        'aaaaaaaaaabbbbbbbbbb': '',
        'a1b2c3': '123',
        '   ': '   ',
      },
    });
  });

  it('should normalize an email based on domain', function () {
    test({
      sanitizer: 'normalizeEmail',
      expect: {
        'test@me.com': 'test@me.com',
        'some.name@gmail.com': 'somename@gmail.com',
        'some.name@googleMail.com': 'somename@gmail.com',
        'some.name+extension@gmail.com': 'somename@gmail.com',
        'some.Name+extension@GoogleMail.com': 'somename@gmail.com',
        'some.name.middleName+extension@gmail.com': 'somenamemiddlename@gmail.com',
        'some.name.middleName+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
        'some.name.midd.leNa.me.+extension@gmail.com': 'somenamemiddlename@gmail.com',
        'some.name.midd.leNa.me.+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
        'some.name+extension@unknown.com': 'some.name+extension@unknown.com',
        'hans@m端ller.com': 'hans@m端ller.com',
        'an invalid email address': false,
        '': false,
        '+extension@gmail.com': false,
        '...@gmail.com': false,
        '.+extension@googlemail.com': false,
        'some.name.midd..leNa...me...+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
      },
    });

    // Testing all_lowercase switch, should apply to domains not known to be case-insensitive
    test({
      sanitizer: 'normalizeEmail',
      args: [{ all_lowercase: false }],
      expect: {
        'test@foo.com': 'test@foo.com',
        'hans@m端ller.com': 'hans@m端ller.com',
        'test@FOO.COM': 'test@foo.com', // Hostname is always lowercased
        'blAH@x.com': 'blAH@x.com',
        // In case of domains that are known to be case-insensitive, there's a separate switch
        'TEST@me.com': 'test@me.com',
        'TEST@ME.COM': 'test@me.com',
        'SOME.name@GMAIL.com': 'somename@gmail.com',
        'SOME.name.middleName+extension@GoogleMail.com': 'somenamemiddlename@gmail.com',
        'SOME.name.midd.leNa.me.+extension@gmail.com': 'somenamemiddlename@gmail.com',
        'SOME.name@gmail.com': 'somename@gmail.com',
        'SOME.name@yahoo.ca': 'some.name@yahoo.ca',
        'SOME.name@outlook.ie': 'some.name@outlook.ie',
        'SOME.name@me.com': 'some.name@me.com',
      },
    });

    // Testing *_lowercase
    test({
      sanitizer: 'normalizeEmail',
      args: [{
        all_lowercase: false,
        gmail_lowercase: false,
        icloud_lowercase: false,
        outlookdotcom_lowercase: false,
        yahoo_lowercase: false,
      }],
      expect: {
        'TEST@FOO.COM': 'TEST@foo.com', // all_lowercase
        'ME@gMAil.com': 'ME@gmail.com', // gmail_lowercase
        'ME@me.COM': 'ME@me.com', // icloud_lowercase
        'ME@icloud.COM': 'ME@icloud.com', // icloud_lowercase
        'ME@outlook.COM': 'ME@outlook.com', // outlookdotcom_lowercase
        'JOHN@live.CA': 'JOHN@live.ca', // outlookdotcom_lowercase
        'ME@ymail.COM': 'ME@ymail.com', // yahoo_lowercase
      },
    });

    // Testing all_lowercase
    // Should overwrite all the *_lowercase options
    test({
      sanitizer: 'normalizeEmail',
      args: [{
        all_lowercase: true,
        gmail_lowercase: false, // Overruled
        icloud_lowercase: false, // Overruled
        outlookdotcom_lowercase: false, // Overruled
        yahoo_lowercase: false, // Overruled
      }],
      expect: {
        'TEST@FOO.COM': 'test@foo.com', // all_lowercase
        'ME@gMAil.com': 'me@gmail.com', // gmail_lowercase
        'ME@me.COM': 'me@me.com', // icloud_lowercase
        'ME@icloud.COM': 'me@icloud.com', // icloud_lowercase
        'ME@outlook.COM': 'me@outlook.com', // outlookdotcom_lowercase
        'JOHN@live.CA': 'john@live.ca', // outlookdotcom_lowercase
        'ME@ymail.COM': 'me@ymail.com', // yahoo_lowercase
      },
    });

    // Testing *_remove_dots
    test({
      sanitizer: 'normalizeEmail',
      args: [{
        gmail_remove_dots: false,
      }],
      expect: {
        'SOME.name@GMAIL.com': 'some.name@gmail.com',
        'SOME.name+me@GMAIL.com': 'some.name@gmail.com',
        'my.self@foo.com': 'my.self@foo.com',
      },
    });

    test({
      sanitizer: 'normalizeEmail',
      args: [{
        gmail_remove_dots: true,
      }],
      expect: {
        'SOME.name@GMAIL.com': 'somename@gmail.com',
        'SOME.name+me@GMAIL.com': 'somename@gmail.com',
        'my.self@foo.com': 'my.self@foo.com',
      },
    });

    // Testing *_remove_subaddress
    test({
      sanitizer: 'normalizeEmail',
      args: [{
        gmail_remove_subaddress: false,
        icloud_remove_subaddress: false,
        outlookdotcom_remove_subaddress: false,
        yahoo_remove_subaddress: false, // Note Yahoo uses "-"
      }],
      expect: {
        'foo+bar@unknown.com': 'foo+bar@unknown.com',
        'foo+bar@gmail.com': 'foo+bar@gmail.com', // gmail_remove_subaddress
        'foo+bar@me.com': 'foo+bar@me.com', // icloud_remove_subaddress
        'foo+bar@icloud.com': 'foo+bar@icloud.com', // icloud_remove_subaddress
        'foo+bar@live.fr': 'foo+bar@live.fr', // outlookdotcom_remove_subaddress
        'foo+bar@hotmail.co.uk': 'foo+bar@hotmail.co.uk', // outlookdotcom_remove_subaddress
        'foo-bar@yahoo.com': 'foo-bar@yahoo.com', // yahoo_remove_subaddress
        'foo+bar@yahoo.com': 'foo+bar@yahoo.com', // yahoo_remove_subaddress
      },
    });

    test({
      sanitizer: 'normalizeEmail',
      args: [{
        gmail_remove_subaddress: true,
        icloud_remove_subaddress: true,
        outlookdotcom_remove_subaddress: true,
        yahoo_remove_subaddress: true, // Note Yahoo uses "-"
      }],
      expect: {
        'foo+bar@unknown.com': 'foo+bar@unknown.com',
        'foo+bar@gmail.com': 'foo@gmail.com', // gmail_remove_subaddress
        'foo+bar@me.com': 'foo@me.com', // icloud_remove_subaddress
        'foo+bar@icloud.com': 'foo@icloud.com', // icloud_remove_subaddress
        'foo+bar@live.fr': 'foo@live.fr', // outlookdotcom_remove_subaddress
        'foo+bar@hotmail.co.uk': 'foo@hotmail.co.uk', // outlookdotcom_remove_subaddress
        'foo-bar@yahoo.com': 'foo@yahoo.com', // yahoo_remove_subaddress
        'foo+bar@yahoo.com': 'foo+bar@yahoo.com', // yahoo_remove_subaddress
      },
    });

    // Testing gmail_convert_googlemaildotcom
    test({
      sanitizer: 'normalizeEmail',
      args: [{
        gmail_convert_googlemaildotcom: false,
      }],
      expect: {
        'SOME.name@GMAIL.com': 'somename@gmail.com',
        'SOME.name+me@GMAIL.com': 'somename@gmail.com',
        'SOME.name+me@googlemail.com': 'somename@googlemail.com',
        'SOME.name+me@googlemail.COM': 'somename@googlemail.com',
        'SOME.name+me@googlEmail.com': 'somename@googlemail.com',
        'my.self@foo.com': 'my.self@foo.com',
      },
    });

    test({
      sanitizer: 'normalizeEmail',
      args: [{
        gmail_convert_googlemaildotcom: true,
      }],
      expect: {
        'SOME.name@GMAIL.com': 'somename@gmail.com',
        'SOME.name+me@GMAIL.com': 'somename@gmail.com',
        'SOME.name+me@googlemail.com': 'somename@gmail.com',
        'SOME.name+me@googlemail.COM': 'somename@gmail.com',
        'SOME.name+me@googlEmail.com': 'somename@gmail.com',
        'my.self@foo.com': 'my.self@foo.com',
      },
    });
  });
});
<|endoftext|>


<commit_before>var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/ipsum', {maxAge: 60*60*24*7}));

module.exports.app = app;

app.get(/.*\/.*\/.*/, function(req, res) {

  res.end('<meta charset="UTF-8">
' + go(req.url) + '
');
})

if(!String.prototype.repeat) {
  String.prototype.repeat = function(n) {
    return new Array(n+1).join(this);
  }
}

/* IPSUM GENERATOR */
var general = require('./general.json');
var dictionary = {
  'design': require('./design.json')
}
var normal = 'لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است. چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است و برای شرایط فعلی تکنولوژی مورد نیاز و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد. کتابهای زیادی در شصت و سه درصد گذشته، حال و آینده شناخت فراوان جامعه و متخصصان را می طلبد تا با نرم افزارها شناخت بیستری را برای طراحان رایانه ای و فرهنگ پیشرو در زبان فارسی ایجاد کرد. در این صورت می توان امید داشت که تمام و دشواری موجود در ارائه راهکارها و شرایط سخت تایپ به پایان رسد وزمان مورد نیاز شامل حروفچینی دستاوردهای اصلی و جوابگوی سوالات پیوسته اهل دنیای موجود طراحی اساسا مورد استفاده قرار گیرد.';
function randomAlamat() {
  if(Math.floor(Math.random() * 4) > 0) return ' ';
  else {
    if(Math.floor(Math.random() * 4) > 0) return ' ';
    else return '، ';
  }
}
function loremipsum(data) {
  var method = data[0],
      unit = data[1],
      amount = +data[2];

  if(method == 'normal') {
    switch(unit) {
      case 'c':
        return normal.slice(0, amount);
      case 'p':
        return normal.repeat(amount);
      case 'w':
        return normal.split(' ').slice(0, amount).join(' ');
    }
  }

  var d = dictionary[method].concat(general),
      r = d.sort(function(a, b) {
        return Math.random() > 0.5;
      });

  var stretch = function stretch(a, n) {
    var d = a;
    while(d.length < n) {
      d = d.concat(a);
    }
    return d;
  }

  switch(unit) {
    case 'c':
      r = stretch(r, amount/2);
      return r.slice(0, amount/2).join(' ').slice(0, amount + (amount/4-1));
    case 'w':
      r = stretch(r, amount);
      return r.slice(0, amount).join(' ');
    case 'p':
      r = stretch(r, 15*(Math.random()+1));
      var s = r.join(' ') + '.
';
      for(var i = 1; i < amount; i++) {
        r = r.sort(function() { return Math.random() > 0.5; });
        r = stretch(r, 15*(Math.random()*3+2));

        s += r.join(' ') + '.
';
      }
      return s;
  }
}
function go(url) {
  var req = url.split('/'),
      data = {};
  req.splice(0, 1);
  for(var i = 0, len = req.length; i < len; i++) {
    data[i] = req[i];
  }
  return loremipsum(data);
}
<commit_msg>Trash useless code<commit_after>var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/ipsum', {maxAge: 60*60*24*7}));

module.exports.app = app;

app.get(/.*\/.*\/.*/, function(req, res) {

  res.end(go(req.url));
})

if(!String.prototype.repeat) {
  String.prototype.repeat = function(n) {
    return new Array(n+1).join(this);
  }
}

/* IPSUM GENERATOR */
var general = require('./general.json');
var dictionary = {
  'design': require('./design.json')
}
var normal = 'لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است. چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است و برای شرایط فعلی تکنولوژی مورد نیاز و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد. کتابهای زیادی در شصت و سه درصد گذشته، حال و آینده شناخت فراوان جامعه و متخصصان را می طلبد تا با نرم افزارها شناخت بیستری را برای طراحان رایانه ای و فرهنگ پیشرو در زبان فارسی ایجاد کرد. در این صورت می توان امید داشت که تمام و دشواری موجود در ارائه راهکارها و شرایط سخت تایپ به پایان رسد وزمان مورد نیاز شامل حروفچینی دستاوردهای اصلی و جوابگوی سوالات پیوسته اهل دنیای موجود طراحی اساسا مورد استفاده قرار گیرد.';

function loremipsum(data) {
  var method = data[0],
      unit = data[1],
      amount = +data[2];

  if(method == 'normal') {
    switch(unit) {
      case 'c':
        return normal.slice(0, amount);
      case 'p':
        return normal.repeat(amount);
      case 'w':
        return normal.split(' ').slice(0, amount).join(' ');
    }
  }

  var d = dictionary[method].concat(general),
      r = d.sort(function(a, b) {
        return Math.random() > 0.5;
      });

  var stretch = function stretch(a, n) {
    var d = a;
    while(d.length < n) {
      d = d.concat(a);
    }
    return d;
  }

  switch(unit) {
    case 'c':
      r = stretch(r, amount/2);
      return r.slice(0, amount/2).join(' ').slice(0, amount + (amount/4-1));
    case 'w':
      r = stretch(r, amount);
      return r.slice(0, amount).join(' ');
    case 'p':
      r = stretch(r, 15*(Math.random()+1));
      var s = r.join(' ') + '.
';
      for(var i = 1; i < amount; i++) {
        r = r.sort(function() { return Math.random() > 0.5; });
        r = stretch(r, 15*(Math.random()*3+2));

        s += r.join(' ') + '.
';
      }
      return s;
  }
}
function go(url) {
  var req = url.split('/');
  return loremipsum(req.slice(1));
}
<|endoftext|>


<commit_before>/*global seqJS:true  */

(function($) {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */
    module('seqJS#seq');

    test('setting and get data', function(){
        expect(3);
        var l = new seqJS.Seq("ATcGAT", seqJS.ALPH_PROT);
        equal(l.seq(), "ATCGAT");
        equal(l.length(), 6);
        equal(l.alphabet(), seqJS.ALPH_PROT);
    });

    test('require an alphabet', function(){
        expect(1);
        throws(function() {new seqJS.Seq("ATcGAT");},
               'Argument alphabet is required');
    });

    test('invalid operator', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(4, -1);
        }, "Invalid location operator '-1'");
    });

    test('invalid location', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(-1);
        }, "Invalid location '-1'");
    });

    module('seqJS#location');

    test('setting implicit exact', function(){
        expect(2);
        var l = new seqJS.Location(5);
        equal(l.location(), 5);
        equal(l.operator(), '');
    });

    test('setting explicit before', function(){
        expect(2);
        var l = new seqJS.Location(6, '<');
        equal(l.location(), 6);
        equal(l.operator(), '<');
    });

    test('setting explicit range', function(){
        expect(3);
        var l = new seqJS.Location(6, '.', 8);
        equal(l.location(), 6);
        equal(l.operator(), '.');
        equal(l.location2(), 8);
    });

    test('set invalid range', function(){
        expect(1);
        throws(function() {
            new seqJS.Location(8, '.', 6);
        });
    });

    test('invalid operator', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(4, '!');
        }, "Invalid location operator '!'");
    });

    test('invalid location', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(-1);
        }, "Invalid location '-1'");
    });

    test('fixed location from string', function(){
        expect(3);
        var l = new seqJS.Location('6');
        equal(l.location(), 6);
        equal(l.operator(), '');
        equal(l.location2(), undefined);
    });

    test('before location from string', function(){
        expect(3);
        var l = new seqJS.Location('<6');
        equal(l.location(), 6);
        equal(l.operator(), '<');
        equal(l.location2(), undefined);
    });
    test('after location from string', function(){
        expect(3);
        var l = new seqJS.Location('>6');
        equal(l.location(), 6);
        equal(l.operator(), '>');
        equal(l.location2(), undefined);
    });
    test('range location from string', function(){
        expect(3);
        var l = new seqJS.Location('6.8');
        equal(l.location(), 6);
        equal(l.operator(), '.');
        equal(l.location2(), 8);
    });
    test('invalid location string format', function(){
        expect(1);
        throws(function(){
            new seqJS.Location('!6');
        }, "Invalid location format '!6'");
    });
    test('invalid location string format 2', function(){
        expect(1);
        throws(function(){
            new seqJS.Location('67sds');
        }, "Invalid location format '67sds'");
    });

    test('invalid location range string', function(){
        expect(1);
        throws(function(){
            new seqJS.Location('8.6');
        });
    });
    /*
    module('seqJS#parser_genbank', {
        setup: function() {
            this.parser = seqJS.getParser('genbank');
            this.data = TEST_DATA.parser_genbank;
        }
    });

    test('parse valid 0', function(){
        expect(1);
        deepEqual(this.parser.parse(this.data.valid[0].string),
                  this.data.valid[0].object);
    });

  module('jQuery#seqJS', {
    // This will run before each test in this module.
    setup: function() {
      this.elems = $('#qunit-fixture').children();
    }
  });

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

  test('is awesome', function() {
    expect(1);
    strictEqual(this.elems.seqJS().text(), 'awesome0awesome1awesome2', 'should be awesome');
  });
*/
  module('jQuery.seqJS');

  test('is awesome', function() {
    expect(2);
    strictEqual($.seqJS(), 'awesome.', 'should be awesome');
    strictEqual($.seqJS({punctuation: '!'}), 'awesome!', 'should be thoroughly awesome');
  });

  module(':seqJS selector', {
    // This will run before each test in this module.
    setup: function() {
      this.elems = $('#qunit-fixture').children();
    }
  });

  test('is awesome', function() {
    expect(1);
    // Use deepEqual & .get() when comparing jQuery objects.
    deepEqual(this.elems.filter(':seqJS').get(), this.elems.last().get(), 'knows awesome when it sees it');
  });

}(jQuery));
<commit_msg>test seqJS.span - fails<commit_after>/*global seqJS:true  */

(function($) {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */
    module('seqJS#seq');

    test('setting and get data', function(){
        expect(3);
        var l = new seqJS.Seq("ATcGAT", seqJS.ALPH_PROT);
        equal(l.seq(), "ATCGAT");
        equal(l.length(), 6);
        equal(l.alphabet(), seqJS.ALPH_PROT);
    });

    test('require an alphabet', function(){
        expect(1);
        throws(function() {new seqJS.Seq("ATcGAT");},
               'Argument alphabet is required');
    });

    test('invalid operator', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(4, -1);
        }, "Invalid location operator '-1'");
    });

    test('invalid location', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(-1);
        }, "Invalid location '-1'");
    });

    module('seqJS#location');

    test('setting implicit exact', function(){
        expect(2);
        var l = new seqJS.Location(5);
        equal(l.location(), 5);
        equal(l.operator(), '');
    });

    test('setting explicit before', function(){
        expect(2);
        var l = new seqJS.Location(6, '<');
        equal(l.location(), 6);
        equal(l.operator(), '<');
    });

    test('setting explicit range', function(){
        expect(3);
        var l = new seqJS.Location(6, '.', 8);
        equal(l.location(), 6);
        equal(l.operator(), '.');
        equal(l.location2(), 8);
    });

    test('set invalid range', function(){
        expect(1);
        throws(function() {
            new seqJS.Location(8, '.', 6);
        });
    });

    test('invalid operator', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(4, '!');
        }, "Invalid location operator '!'");
    });

    test('invalid location', function(){
        expect(1);
        throws(function(){
            new seqJS.Location(-1);
        }, "Invalid location '-1'");
    });

    test('fixed location from string', function(){
        expect(3);
        var l = new seqJS.Location('6');
        equal(l.location(), 6);
        equal(l.operator(), '');
        equal(l.location2(), undefined);
    });

    test('before location from string', function(){
        expect(3);
        var l = new seqJS.Location('<6');
        equal(l.location(), 6);
        equal(l.operator(), '<');
        equal(l.location2(), undefined);
    });
    test('after location from string', function(){
        expect(3);
        var l = new seqJS.Location('>6');
        equal(l.location(), 6);
        equal(l.operator(), '>');
        equal(l.location2(), undefined);
    });
    test('range location from string', function(){
        expect(3);
        var l = new seqJS.Location('6.8');
        equal(l.location(), 6);
        equal(l.operator(), '.');
        equal(l.location2(), 8);
    });
    test('invalid location string format', function(){
        expect(1);
        throws(function(){
            new seqJS.Location('!6');
        }, "Invalid location format '!6'");
    });
    test('invalid location string format 2', function(){
        expect(1);
        throws(function(){
            new seqJS.Location('67sds');
        }, "Invalid location format '67sds'");
    });

    test('invalid location range string', function(){
        expect(1);
        throws(function(){
            new seqJS.Location('8.6');
        });
    });

    module('seqJS#span');

    test('span from string A', function(){
        expect(6);
        var s = new seqJS.span('100..150');
        equal(s.location1().location(), 100);
        equal(s.location1().operator(), '');
        equal(s.location1().location1(), undefined);

        equal(s.location2().location(), 150);
        equal(s.location2().operator(), '');
        equal(s.location2().location1(), undefined);
    });

    test('span from string B', function(){
        expect(6);
        var s = new seqJS.span('<100..>150');
        equal(s.location1().location(), 100);
        equal(s.location1().operator(), '<');
        equal(s.location1().location1(), undefined);

        equal(s.location2().location(), 150);
        equal(s.location2().operator(), '>');
        equal(s.location2().location1(), undefined);
    });

    test('span from string C', function(){
        expect(6);
        var s = new seqJS.span('100.105..150');
        equal(s.location1().location(), 100);
        equal(s.location1().operator(), '.');
        equal(s.location1().location1(), 105);

        equal(s.location2().location(), 150);
        equal(s.location2().operator(), '');
        equal(s.location2().location1(), undefined);
    });

    test('span from string D', function(){
        expect(6);
        var s = new seqJS.span('100..150.160');
        equal(s.location1().location(), 100);
        equal(s.location1().operator(), '');
        equal(s.location1().location1(), undefined);

        equal(s.location2().location(), 150);
        equal(s.location2().operator(), '.');
        equal(s.location2().location1(), 160);
    });

    test('locations inverted', function(){
        expect(1);
        throws(function(){
            new seqJS.span('200..100');
        });
    });

    test('bad formating', function(){
        expect(1);
        throws(function(){
            new seqJS.span('100.200');
        });
    });

    /*
    module('seqJS#parser_genbank', {
        setup: function() {
            this.parser = seqJS.getParser('genbank');
            this.data = TEST_DATA.parser_genbank;
        }
    });

    test('parse valid 0', function(){
        expect(1);
        deepEqual(this.parser.parse(this.data.valid[0].string),
                  this.data.valid[0].object);
    });

  module('jQuery#seqJS', {
    // This will run before each test in this module.
    setup: function() {
      this.elems = $('#qunit-fixture').children();
    }
  });

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

  test('is awesome', function() {
    expect(1);
    strictEqual(this.elems.seqJS().text(), 'awesome0awesome1awesome2', 'should be awesome');
  });
*/
  module('jQuery.seqJS');

  test('is awesome', function() {
    expect(2);
    strictEqual($.seqJS(), 'awesome.', 'should be awesome');
    strictEqual($.seqJS({punctuation: '!'}), 'awesome!', 'should be thoroughly awesome');
  });

  module(':seqJS selector', {
    // This will run before each test in this module.
    setup: function() {
      this.elems = $('#qunit-fixture').children();
    }
  });

  test('is awesome', function() {
    expect(1);
    // Use deepEqual & .get() when comparing jQuery objects.
    deepEqual(this.elems.filter(':seqJS').get(), this.elems.last().get(), 'knows awesome when it sees it');
  });

}(jQuery));
<|endoftext|>


<commit_before>//- JavaScript source code

//- qspec.js ~~
//
//  Jasmine (http://pivotal.github.com/jasmine/) BDD Specs for Quanah, written
//  in an effort to:
//    * Provide a degree of documentation
//    * Learn the damn thing
//    * Provide a way to catch changes made in Quanah's API
//
//  The actually interesting, i.e. expressive of Quanah's use, code takes place
//  in the describe(...) blocks; everything prior is just helpers.
//
//                                                      ~~ (c) DER, 06 Apr 2012
//                                                      update SRW, 01 Jun 2012

(function () {
    'use strict';

 // Pragmas

    /*global
        beforeEach: false,
        console: false,
        describe: false,
        expect: false,
        it: false,
        jasmine: false,
        Q: false,
        runs: false,
        waitsFor: false,
        xit: false
    */

    /*jshint */

    /*jslint indent: 4, maxlen: 80 */

 // Prerequisites

    if (Object.prototype.hasOwnProperty('Q') === false) {
        throw new Error('Method Q is missing.');
    }

 // Declarations

    var getAvars, toType, onerror;

 // Definitions

    getAvars = function (x) {
     // Returns an avar whose val is an array of avars, with one for each
     // of the arguments (or each element of the first argument if it is
     // an array.
        var arg, args, avars, i, temp;
        avars = [];
        args = (toType(x) === 'array') ? x : arguments;
        for (i in args) {
            if (args.hasOwnProperty(i)) {
                arg = args[i];
                temp = Q.avar({val: arg});
                temp.onerror = onerror;
                avars.push(temp);
            }
        }
        temp = Q.avar({val: avars});
        temp.onerror = onerror;
        return temp;
    };

    toType = function (obj) {
     // This function needs documentation.
        return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
    };

    onerror = function (msg) {
     // This function needs documentation.
        console.error(msg);
        return;
    };

 // Invocations

    beforeEach(function () {
     // This function needs documentation.
        var customMatchers, setMatcherMessage;
        customMatchers = {};
        setMatcherMessage = function (message, matcher_context) {
         // This function needs documentation.
            matcher_context.message = function () {
             // This function needs documentation.
                return message;
            };
            return;
        };
        customMatchers.toBeA = function (expected_type) {
         // This function needs documentation.
            return toType(this.actual) === expected_type;
        };
        customMatchers.toBeAFunction = function () {
         // This function needs documentation.
            return toType(this.actual) === 'function';
        };
        customMatchers.toBeAObject = function () {
         // This function needs documentation.
            return toType(this.actual) === 'object';
        };
        customMatchers.toBeAUuid = function () {
         // This function needs documentation.
            return (this.actual.match(/[0-9abcdef]{32}/)) !== null;
        };
        customMatchers.toContainPrefixes = function (expected) {
         // This function needs documentation.
            var key;
            for (key in expected) {
                if (expected.hasOwnProperty(key) &&
                        (this.actual[key] !== expected[key])) {
                    setMatcherMessage('Expected ' + this.actual[key] +
                            ' to be ' + expected[key] + ', with prefix ' +
                            key + '.', this);
                    return false;
                }
            }
            return true;
        };
        this.addMatchers(customMatchers);
        return;
    });

    describe('Quanah', function () {

     // This is the actual specification :-)

        it('should be awesome', function () {
            expect(true).toBeTruthy();
            return;
        });

        it('should place function Q on the Object prototype', function () {
            expect(Object.prototype.hasOwnProperty('Q')).toBeTruthy();
            return;
        });

        it('should provide the Quanah API', function () {
         // Needs a better "should" string...
            var api, thing;
            api = {
                avar: 'function',
                init: 'function',
                ply:  'function',
                volunteer: 'function',
                when : 'function'
            };
            for (thing in api) {
                if (api.hasOwnProperty(thing)) {
                    expect(typeof Q[thing]).toBe(api[thing]);
                }
            }
            return;
        });

        return;

    });

    describe('Quanah AVars', function () {

        describe('AVar Creation', function () {

            it('should allow creation of AVars with no spec', function () {
                var x = Q.avar();
                expect(x).toBeAObject();
                expect(x.key).toBeAUuid();
                expect(x.val).toBeNull();
            });

            it('should allow creation of AVars with only a key', function () {
                var x = Q.avar({key: 'a'});
                expect(x).toBeAObject();
                expect(x.key).toEqual("a");
                expect(x.val).toBeNull();
            });

            it('should allow creation of AVars with only a val', function () {
                var x = Q.avar({val: 'a'});
                expect(x).toBeAObject();
                expect(x.key).toBeAUuid();
                expect(x.val).toEqual("a");
            });

            it('should allow creation of AVars with key and val', function () {
                var x = Q.avar({key: 'a', val: 12345});
                expect(x).toBeAObject();
                expect(x.key).toEqual("a");
                expect(x.val).toEqual(12345);
            });

            it('should construct AVar from a stringified avar', function () {
                var x, y, z;
                x = Q.avar({key: 'a', val: 12345});
                y = JSON.stringify(x);
                z = Q.avar(y);
                expect(x).toEqual(z);
            });

            return;

        });

        describe('Avar Access', function () {

            var avars, vals, spy;

            beforeEach(function () {
                vals = [
                    1234, '1234', [1, 2, 3, 4], {a: 1, b: 2}, function () {}
                ];
                avars = getAvars(vals);
                spy = jasmine.createSpy();
            });

            xit('should be retrievable as JSON with toJSON()', function () {
             // Disabled until toJSON is better specified,
             // e.g. for functions as vals
                var x, spec;
                spec = {key: 'a', val: '12345'};
                x = Q.avar(spec);
                expect(x.toJSON()).toEqual(spec);
                avars.onready = Q.ply(function (k, v) {
                    expect(v.toJSON().val).toEqual(vals[k]);
                    spy();
                });
                expect(spy.callCount).toEqual(5);
            });

            it('coerces val to string when toString is called', function () {
                avars.onready = Q.ply(function (k, v) {
                    expect(v.toString()).toEqual(vals[k].toString());
                    spy();
                });
                expect(spy.callCount).toEqual(5);
            });

            it('returns raw val when valueOf is called', function () {
                avars.onready = Q.ply(function (k, v) {
                    expect(v.valueOf()).toEqual(vals[k]);
                    spy();
                });
                expect(spy.callCount).toEqual(5);
            });

            return;

        });

        describe('Avar execution', function () {

            var x, spy;

            beforeEach(function () {
                x = Q.avar();
                spy = jasmine.createSpy();
            });

            it('runs computations assigned to onready', function () {
                x = Q.avar({val: 0});
                x.onready = function (evt) {
                    this.val += 1;
                    evt.exit();
                };
                expect(x.val).toEqual(1);
            });

            it("should apply Avar.onready's sequentially", function () {
                x.onready = function (evt) {
                    this.val = "dogs";
                    evt.exit();
                };
                x.onready = function (evt) {
                    expect(this.val).toEqual("dogs");
                    this.val = "cats";
                    evt.exit();
                };
                x.onready = function (evt) {
                    expect(this.val).toEqual("cats");
                    evt.exit();
                };
            });

            it('stays execution when evt.stay is called', function () {
                x.onready = function (evt) {
                    this.val = "before";
                    evt.exit();
                };
                x.onready = function (evt) {
                    evt.stay();
                };
                x.onready = function (evt) {
                    spy();
                    evt.exit();
                };
                expect(spy).not.toHaveBeenCalled();
            });

            it('does not execute next onready w/o evt.exit call', function () {
                /*jslint unparam: true */
                x.onready = function (evt) {
                    this.val = "value";
                };
                x.onready = function (evt) {
                    spy();
                    evt.exit();
                };
                expect(spy).not.toHaveBeenCalled();
            });

            it('executes onerror handler if evt.fail is called', function () {
                x.onerror = function (msg) {
                    expect(msg).toEqual("Oh Noes!!");
                    spy();
                };
                x.onready = function (evt) {
                    evt.fail("Oh Noes!!");
                };
                expect(spy).toHaveBeenCalled();
            });

            xit('allows iteration over "iterables" via Q.ply', function () {
                var vals, avars, afterVals, i, doubleIt, checkIt;
                vals = [[1, 2, 3, 4], {a: 1, b: 2, c: 3, d: 4}];
                afterVals = [[2, 4, 6, 8], {a: 2, b: 4, c: 6, d: 8}];
                avars = getAvars(vals).val;
                doubleIt = function () {
                    this.val *= 2;
                };
                checkIt = function (i) {
                    return function (evt) {
                        expect(this.val).toEqual(afterVals[i]);
                        spy();
                        evt.exit();
                    };
                };
                for (i in vals) {
                 // Could be replaced with ply ... but that would be cheating?
                    if (vals.hasOwnProperty(i)) {
                        avars[i].onready = Q.ply(doubleIt);
                        avars[i].onready = checkIt(i);
                    }
                }
                expect(spy.callCount).toBe(2);
            });

            it('stays execution for long-running onready', function () {
                var done, tic, x;
                tic = Date.now();
                done = false;
                x = Q.avar();
                x.onerror = onerror;
                x.onready = function (evt) {
                    if ((Date.now() - tic) < 2000) {
                        return evt.stay();
                    }
                    done = true;
                    this.val = "finished";
                    return evt.exit();
                };
                x.onready = function (evt) {
                    done = true;
                    return evt.exit();
                };
                waitsFor(function () {
                    x.comm();
                    return done;
                }, 'Never finished.', 3000);
                runs(function () {
                    expect(x.val).toEqual('finished');
                });
            });

        });

    });

    describe('Original Tests', function () {
     // This function needs documentation.
        // ...
        return;
    });

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<commit_msg>Removed global reference to `Q` from Jasmine test spec<commit_after>//- JavaScript source code

//- qspec.js ~~
//
//  Jasmine (http://pivotal.github.com/jasmine/) BDD Specs for Quanah, written
//  in an effort to:
//    * Provide a degree of documentation
//    * Learn the damn thing
//    * Provide a way to catch changes made in Quanah's API
//
//  The actually interesting, i.e. expressive of Quanah's use, code takes place
//  in the describe(...) blocks; everything prior is just helpers.
//
//                                                      ~~ (c) DER, 06 Apr 2012
//                                                      update SRW, 31 Jul 2012

(function () {
    'use strict';

 // Pragmas

    /*global
        beforeEach: false,
        console: false,
        describe: false,
        expect: false,
        it: false,
        jasmine: false,
        runs: false,
        waitsFor: false,
        xit: false
    */

    /*jshint */

    /*jslint indent: 4, maxlen: 80 */

 // Prerequisites

    if (Object.prototype.hasOwnProperty('Q') === false) {
        throw new Error('Method Q is missing.');
    }

 // Declarations

    var Q, getAvars, toType, onerror;

 // Definitions

    Q = Object.prototype.Q;

    getAvars = function (x) {
     // Returns an avar whose val is an array of avars, with one for each
     // of the arguments (or each element of the first argument if it is
     // an array.
        var arg, args, avars, i, temp;
        avars = [];
        args = (toType(x) === 'array') ? x : arguments;
        for (i in args) {
            if (args.hasOwnProperty(i)) {
                arg = args[i];
                temp = Q.avar({val: arg});
                temp.onerror = onerror;
                avars.push(temp);
            }
        }
        temp = Q.avar({val: avars});
        temp.onerror = onerror;
        return temp;
    };

    toType = function (obj) {
     // This function needs documentation.
        return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
    };

    onerror = function (msg) {
     // This function needs documentation.
        console.error(msg);
        return;
    };

 // Invocations

    beforeEach(function () {
     // This function needs documentation.
        var customMatchers, setMatcherMessage;
        customMatchers = {};
        setMatcherMessage = function (message, matcher_context) {
         // This function needs documentation.
            matcher_context.message = function () {
             // This function needs documentation.
                return message;
            };
            return;
        };
        customMatchers.toBeA = function (expected_type) {
         // This function needs documentation.
            return toType(this.actual) === expected_type;
        };
        customMatchers.toBeAFunction = function () {
         // This function needs documentation.
            return toType(this.actual) === 'function';
        };
        customMatchers.toBeAObject = function () {
         // This function needs documentation.
            return toType(this.actual) === 'object';
        };
        customMatchers.toBeAUuid = function () {
         // This function needs documentation.
            return (this.actual.match(/[0-9abcdef]{32}/)) !== null;
        };
        customMatchers.toContainPrefixes = function (expected) {
         // This function needs documentation.
            var key;
            for (key in expected) {
                if (expected.hasOwnProperty(key) &&
                        (this.actual[key] !== expected[key])) {
                    setMatcherMessage('Expected ' + this.actual[key] +
                            ' to be ' + expected[key] + ', with prefix ' +
                            key + '.', this);
                    return false;
                }
            }
            return true;
        };
        this.addMatchers(customMatchers);
        return;
    });

    describe('Quanah', function () {

     // This is the actual specification :-)

        it('should be awesome', function () {
            expect(true).toBeTruthy();
            return;
        });

        it('should place function Q on the Object prototype', function () {
            expect(Object.prototype.hasOwnProperty('Q')).toBeTruthy();
            return;
        });

        it('should provide the Quanah API', function () {
         // Needs a better "should" string...
            var api, thing;
            api = {
                avar: 'function',
                init: 'function',
                ply:  'function',
                volunteer: 'function',
                when : 'function'
            };
            for (thing in api) {
                if (api.hasOwnProperty(thing)) {
                    expect(typeof Q[thing]).toBe(api[thing]);
                }
            }
            return;
        });

        return;

    });

    describe('Quanah AVars', function () {

        describe('AVar Creation', function () {

            it('should allow creation of AVars with no spec', function () {
                var x = Q.avar();
                expect(x).toBeAObject();
                expect(x.key).toBeAUuid();
                expect(x.val).toBeNull();
            });

            it('should allow creation of AVars with only a key', function () {
                var x = Q.avar({key: 'a'});
                expect(x).toBeAObject();
                expect(x.key).toEqual("a");
                expect(x.val).toBeNull();
            });

            it('should allow creation of AVars with only a val', function () {
                var x = Q.avar({val: 'a'});
                expect(x).toBeAObject();
                expect(x.key).toBeAUuid();
                expect(x.val).toEqual("a");
            });

            it('should allow creation of AVars with key and val', function () {
                var x = Q.avar({key: 'a', val: 12345});
                expect(x).toBeAObject();
                expect(x.key).toEqual("a");
                expect(x.val).toEqual(12345);
            });

            it('should construct AVar from a stringified avar', function () {
                var x, y, z;
                x = Q.avar({key: 'a', val: 12345});
                y = JSON.stringify(x);
                z = Q.avar(y);
                expect(x).toEqual(z);
            });

            return;

        });

        describe('Avar Access', function () {

            var avars, vals, spy;

            beforeEach(function () {
                vals = [
                    1234, '1234', [1, 2, 3, 4], {a: 1, b: 2}, function () {}
                ];
                avars = getAvars(vals);
                spy = jasmine.createSpy();
            });

            xit('should be retrievable as JSON with toJSON()', function () {
             // Disabled until toJSON is better specified,
             // e.g. for functions as vals
                var x, spec;
                spec = {key: 'a', val: '12345'};
                x = Q.avar(spec);
                expect(x.toJSON()).toEqual(spec);
                avars.onready = Q.ply(function (k, v) {
                    expect(v.toJSON().val).toEqual(vals[k]);
                    spy();
                });
                expect(spy.callCount).toEqual(5);
            });

            it('coerces val to string when toString is called', function () {
                avars.onready = Q.ply(function (k, v) {
                    expect(v.toString()).toEqual(vals[k].toString());
                    spy();
                });
                expect(spy.callCount).toEqual(5);
            });

            it('returns raw val when valueOf is called', function () {
                avars.onready = Q.ply(function (k, v) {
                    expect(v.valueOf()).toEqual(vals[k]);
                    spy();
                });
                expect(spy.callCount).toEqual(5);
            });

            return;

        });

        describe('Avar execution', function () {

            var x, spy;

            beforeEach(function () {
                x = Q.avar();
                spy = jasmine.createSpy();
            });

            it('runs computations assigned to onready', function () {
                x = Q.avar({val: 0});
                x.onready = function (evt) {
                    this.val += 1;
                    evt.exit();
                };
                expect(x.val).toEqual(1);
            });

            it("should apply Avar.onready's sequentially", function () {
                x.onready = function (evt) {
                    this.val = "dogs";
                    evt.exit();
                };
                x.onready = function (evt) {
                    expect(this.val).toEqual("dogs");
                    this.val = "cats";
                    evt.exit();
                };
                x.onready = function (evt) {
                    expect(this.val).toEqual("cats");
                    evt.exit();
                };
            });

            it('stays execution when evt.stay is called', function () {
                x.onready = function (evt) {
                    this.val = "before";
                    evt.exit();
                };
                x.onready = function (evt) {
                    evt.stay();
                };
                x.onready = function (evt) {
                    spy();
                    evt.exit();
                };
                expect(spy).not.toHaveBeenCalled();
            });

            it('does not execute next onready w/o evt.exit call', function () {
                /*jslint unparam: true */
                x.onready = function (evt) {
                    this.val = "value";
                };
                x.onready = function (evt) {
                    spy();
                    evt.exit();
                };
                expect(spy).not.toHaveBeenCalled();
            });

            it('executes onerror handler if evt.fail is called', function () {
                x.onerror = function (msg) {
                    expect(msg).toEqual("Oh Noes!!");
                    spy();
                };
                x.onready = function (evt) {
                    evt.fail("Oh Noes!!");
                };
                expect(spy).toHaveBeenCalled();
            });

            xit('allows iteration over "iterables" via Q.ply', function () {
                var vals, avars, afterVals, i, doubleIt, checkIt;
                vals = [[1, 2, 3, 4], {a: 1, b: 2, c: 3, d: 4}];
                afterVals = [[2, 4, 6, 8], {a: 2, b: 4, c: 6, d: 8}];
                avars = getAvars(vals).val;
                doubleIt = function () {
                    this.val *= 2;
                };
                checkIt = function (i) {
                    return function (evt) {
                        expect(this.val).toEqual(afterVals[i]);
                        spy();
                        evt.exit();
                    };
                };
                for (i in vals) {
                 // Could be replaced with ply ... but that would be cheating?
                    if (vals.hasOwnProperty(i)) {
                        avars[i].onready = Q.ply(doubleIt);
                        avars[i].onready = checkIt(i);
                    }
                }
                expect(spy.callCount).toBe(2);
            });

            it('stays execution for long-running onready', function () {
                var done, tic, x;
                tic = Date.now();
                done = false;
                x = Q.avar();
                x.onerror = onerror;
                x.onready = function (evt) {
                    if ((Date.now() - tic) < 2000) {
                        return evt.stay();
                    }
                    done = true;
                    this.val = "finished";
                    return evt.exit();
                };
                x.onready = function (evt) {
                    done = true;
                    return evt.exit();
                };
                waitsFor(function () {
                    x.comm();
                    return done;
                }, 'Never finished.', 3000);
                runs(function () {
                    expect(x.val).toEqual('finished');
                });
            });

        });

    });

    describe('Original Tests', function () {
     // This function needs documentation.
        // ...
        return;
    });

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<|endoftext|>


<commit_before>const should = require('should');
const Stage = require('../libs/stage');

const pageInfo = require('../stages/page-info');
const matchRouter = require('../stages/match-router');

describe('Class Stage', () => {
  const filters = [pageInfo, matchRouter];
  const stage = new Stage(filters);

  function beforePageInfo() {}
  function afterPageInfo() {}

  it('should have two filters', () => {
    stage.stageNames.join(',').should.equal('pageInfo,matchRouter');
  });

  it('should can add before filter', () => {
    stage.before('pageInfo', beforePageInfo);

    stage.actions.map(action => action.name)
    .join(',').should.equal('beforePageInfo,pageInfo,matchRouter');
  });

  it('should can add after filter', () => {
    stage.after('pageInfo', afterPageInfo);

    stage.actions.map(action => action.name)
    .join(',').should.equal('beforePageInfo,pageInfo,afterPageInfo,matchRouter');
  });

  it('should throw when add filter to unexist stage', () => {
    const errorAfter = (stageName) => stage.after(stageName, afterPageInfo);
    errorAfter.bind(null, 'wrongStage').should.throw();
    errorAfter.bind(null, 'pageInfo').should.not.throw();
  });

  it('should get and set props correctly', () => {
    stage.set('a', 1);
    stage.get('a').should.equal(1);
  });
});
<commit_msg>add case to test next.to<commit_after>const should = require('should');
const Stage = require('../libs/stage');

const pageInfo = require('../stages/page-info');
const matchRouter = require('../stages/match-router');
let nextToResult = 'to is ok';
let noInvoKeMiddle = 'no-invoke';

function a(req, res, next) {
  req.isTo = true;
  next.to('c');
}
function b(req, res, next) {
  req.isTo = false;
  noInvoKeMiddle = 'yes-invoke';
  next();
}
function c(req, res, next) {
  if (!req.isTo) {
    nextToResult = 'to is bad';
  }
}

describe('Class Stage', () => {
  const filters = [pageInfo, matchRouter];
  const stage = new Stage(filters);
  const stage2 = new Stage([a, b, c]);

  function beforePageInfo() {}
  function afterPageInfo() {}

  it('should have two filters', () => {
    stage.stageNames.join(',').should.equal('pageInfo,matchRouter');
  });

  it('should can add before filter', () => {
    stage.before('pageInfo', beforePageInfo);

    stage.actions.map(action => action.name)
    .join(',').should.equal('beforePageInfo,pageInfo,matchRouter');
  });

  it('should can add after filter', () => {
    stage.after('pageInfo', afterPageInfo);

    stage.actions.map(action => action.name)
    .join(',').should.equal('beforePageInfo,pageInfo,afterPageInfo,matchRouter');
  });

  it('should throw when add filter to unexist stage', () => {
    const errorAfter = (stageName) => stage.after(stageName, afterPageInfo);
    errorAfter.bind(null, 'wrongStage').should.throw();
    errorAfter.bind(null, 'pageInfo').should.not.throw();
  });

  it('should get and set props correctly', () => {
    stage.set('a', 1);
    stage.get('a').should.equal(1);
  });

  it('should get ok when use next.to()', () => {
    stage2.handle({ path: '/demo' }, {}, () => {});

    nextToResult.should.equal('to is ok');
    noInvoKeMiddle.should.equal('no-invoke');
  });
});
<|endoftext|>


<commit_before>App.FundRaiserIsOwner = Em.Mixin.create({
    isOwner: function() {
        var username = this.get('currentUser.username');
        var ownername = this.get('model.owner.username');
        if (username) {
            return (username == ownername);
        }
        return false;
    }.property('model.owner', 'currentUser.username')
});

App.FundRaiserController = Em.ObjectController.extend(App.FundRaiserIsOwner, {
    needs: ['project']
});

App.FundRaiserNewController = Em.ObjectController.extend(App.Editable, App.FundRaiserIsOwner, {
    needs: ['project'],
    actions: {
        updateRecordOnServer: function(){
            var controller = this;
            var model = this.get('model');

            model.one('becameInvalid', function(record){
                model.set('errors', record.get('errors'));
            });

            model.one('didCreate', function(record){
                controller.transitionToRoute('fundRaiser', record);
                if (controller.get('tracker')) {
                    controller.get('tracker').trackEvent("New fundraiser", {project: model.get('project.title'), title: model.get('title')});
                }

            });

            model.one('didUpdate', function(record) {
                if (controller.get('tracker')) {
                    controller.get('tracker').trackEvent("Edit fundraiser", {project: model.get('project.title'), title: model.get('title')});
                }
                controller.transitionToRoute('fundRaiser', record);
            });

            model.save();
        }
    }
});

App.FundRaiserEditController = App.FundRaiserNewController.extend({
});

App.ProjectFundRaiserAllController = Em.ArrayController.extend({
    actions: {
        showFundraiser: function(fundraiser){
            $('.modal-close').click();
            this.transitionToRoute('fundRaiser', fundraiser);
        }
    }
});

App.ProjectFundRaiserListController = Em.ArrayController.extend({
    needs: ['project', 'projectFundRaiserAll'],

    fundraisers: function () {
        return App.FundRaiser.find({project: this.get('controllers.project.id')});
    }.property('controllers.project.id'),

	fundraisersLoaded: function(sender, key) {
		if (this.get(key)) {
			this.set('model', this.get('fundraisers').toArray());
		} else {
			this.set('model', null);
		}
	}.observes('fundraisers.isLoaded'),

    actions: {
        showAllFundraisers: function(project){
            // Get the controller or create one
            var controller = this.get('controllers.projectFundRaiserAll');
            controller.set('model', App.FundRaiser.find({project: project.get('id'), page_size: 200}));

            // Get the view. This should be defined.
            var view = App.ProjectFundRaiserAllView.create();
            view.set('controller', controller);

            var modalPaneTemplate = ['
×{{view view.bodyViewClass}}
'].join("\n");

            Bootstrap.ModalPane.popup({
                classNames: ['modal', 'large'],
                defaultTemplate: Em.Handlebars.compile(modalPaneTemplate),
                bodyViewClass: view,
                secondary: 'Close'
            });

        }
    }

});

App.FundRaiserDonationListController = Em.ObjectController.extend({});

App.FundRaiserSupporterListController = Em.ArrayController.extend({
    needs: ['fundRaiser'],

    supporters: function(){
        //var project_id = this.get('controllers.fundRaiser.project.id')
        var fundraiser_id = this.get('controllers.fundRaiser.id')
        //return App.ProjectSupporter.find({project: project_id});
        return App.ProjectSupporter.find({fundraiser: fundraiser_id});
    }.property('controllers.fundRaiser.id')

});

App.FundRaiserIndexController = Em.ArrayController.extend({
    needs: ['fundRaiser'],
    perPage: 5,
    page: 1,

    isOwner: function(){
        var userName = this.get('currentUser.username');
        var ownerName = this.get('controllers.fundRaiser.owner.username');
        if (userName) {
            return (userName == ownerName);
        }
        return false;
    }.property('controllers.fundRaiser.owner', 'controllers.fundRaiser.owner.username'),

    remainingItemCount: function(){
        if (this.get('meta.total')) {
            return this.get('meta.total') - (this.get('page')  * this.get('perPage'));
        }
        return 0;
    }.property('page', 'perPage', 'meta.total'),

    canLoadMore: function(){
        var totalPages = Math.ceil(this.get('meta.total') / this.get('perPage'));
        return totalPages > this.get('page');
    }.property('perPage', 'page', 'meta.total'),

    actions: {
        showMore: function() {
            var controller = this;
            var page = this.incrementProperty('page');
            var id = this.get('controllers.fundRaiser.model.id');
            App.WallPost.find({'parent_type': 'fund raiser', 'parent_id': id, page: page}).then(function(items){
                controller.get('model').pushObjects(items.toArray());
            });
        }
    }
});

App.MyFundRaiserListController = Em.ArrayController.extend({});
<commit_msg>[feature/CLUB-830] added sorting of fundraisers to controller<commit_after>App.FundRaiserIsOwner = Em.Mixin.create({
    isOwner: function() {
        var username = this.get('currentUser.username');
        var ownername = this.get('model.owner.username');
        if (username) {
            return (username == ownername);
        }
        return false;
    }.property('model.owner', 'currentUser.username')
});

App.FundRaiserController = Em.ObjectController.extend(App.FundRaiserIsOwner, {
    needs: ['project']
});

App.FundRaiserNewController = Em.ObjectController.extend(App.Editable, App.FundRaiserIsOwner, {
    needs: ['project'],
    actions: {
        updateRecordOnServer: function(){
            var controller = this;
            var model = this.get('model');

            model.one('becameInvalid', function(record){
                model.set('errors', record.get('errors'));
            });

            model.one('didCreate', function(record){
                controller.transitionToRoute('fundRaiser', record);
                if (controller.get('tracker')) {
                    controller.get('tracker').trackEvent("New fundraiser", {project: model.get('project.title'), title: model.get('title')});
                }

            });

            model.one('didUpdate', function(record) {
                if (controller.get('tracker')) {
                    controller.get('tracker').trackEvent("Edit fundraiser", {project: model.get('project.title'), title: model.get('title')});
                }
                controller.transitionToRoute('fundRaiser', record);
            });

            model.save();
        }
    }
});

App.FundRaiserEditController = App.FundRaiserNewController.extend({
});

App.ProjectFundRaiserAllController = Em.ArrayController.extend({
    sortProperties: ['amount_donated'],
    sortAscending: false,
    actions: {
        showFundraiser: function(fundraiser){
            $('.modal-close').click();
            this.transitionToRoute('fundRaiser', fundraiser);
        }
    }
});

App.ProjectFundRaiserListController = Em.ArrayController.extend({
    needs: ['project', 'projectFundRaiserAll'],

    fundraisers: function () {
        return App.FundRaiser.find({project: this.get('controllers.project.id')});
    }.property('controllers.project.id'),

	fundraisersLoaded: function(sender, key) {
		if (this.get(key)) {
			this.set('model', this.get('fundraisers').toArray());
		} else {
			this.set('model', null);
		}
	}.observes('fundraisers.isLoaded'),

    actions: {
        showAllFundraisers: function(project){
            // Get the controller or create one
            var controller = this.get('controllers.projectFundRaiserAll');
            controller.set('model', App.FundRaiser.find({project: project.get('id'), page_size: 200}));

            // Get the view. This should be defined.
            var view = App.ProjectFundRaiserAllView.create();
            view.set('controller', controller);

            var modalPaneTemplate = ['
×{{view view.bodyViewClass}}
'].join("\n");

            Bootstrap.ModalPane.popup({
                classNames: ['modal', 'large'],
                defaultTemplate: Em.Handlebars.compile(modalPaneTemplate),
                bodyViewClass: view,
                secondary: 'Close'
            });

        }
    }

});

App.FundRaiserDonationListController = Em.ObjectController.extend({});

App.FundRaiserSupporterListController = Em.ArrayController.extend({
    needs: ['fundRaiser'],

    supporters: function(){
        //var project_id = this.get('controllers.fundRaiser.project.id')
        var fundraiser_id = this.get('controllers.fundRaiser.id')
        //return App.ProjectSupporter.find({project: project_id});
        return App.ProjectSupporter.find({fundraiser: fundraiser_id});
    }.property('controllers.fundRaiser.id')

});

App.FundRaiserIndexController = Em.ArrayController.extend({
    needs: ['fundRaiser'],
    perPage: 5,
    page: 1,

    isOwner: function(){
        var userName = this.get('currentUser.username');
        var ownerName = this.get('controllers.fundRaiser.owner.username');
        if (userName) {
            return (userName == ownerName);
        }
        return false;
    }.property('controllers.fundRaiser.owner', 'controllers.fundRaiser.owner.username'),

    remainingItemCount: function(){
        if (this.get('meta.total')) {
            return this.get('meta.total') - (this.get('page')  * this.get('perPage'));
        }
        return 0;
    }.property('page', 'perPage', 'meta.total'),

    canLoadMore: function(){
        var totalPages = Math.ceil(this.get('meta.total') / this.get('perPage'));
        return totalPages > this.get('page');
    }.property('perPage', 'page', 'meta.total'),

    actions: {
        showMore: function() {
            var controller = this;
            var page = this.incrementProperty('page');
            var id = this.get('controllers.fundRaiser.model.id');
            App.WallPost.find({'parent_type': 'fund raiser', 'parent_id': id, page: page}).then(function(items){
                controller.get('model').pushObjects(items.toArray());
            });
        }
    }
});

App.MyFundRaiserListController = Em.ArrayController.extend({});
<|endoftext|>


<commit_before>
var routes = function ($stateProvider, $urlRouterProvider) {

  $urlRouterProvider.otherwise(function($injector, $location){
    var state = $injector.get('$state');
    Rollbar.warning("404 Error: " + $location.path());
    state.go('notFound');
    return $location.path();
  });

  // handle old single-post links
  $urlRouterProvider.when('/c/:community/s/:seedId/comments', '/c/:community/s/:seedId');

  // handle alternate name of starting route
  $urlRouterProvider.when('/', '/app');

  $stateProvider
    .state('notFound', {
      templateUrl: '/ui/app/404.tpl.html'
    })
    .state('main', /*@ngInject*/ {
      abstract: true,
      templateUrl: '/ui/shared/main.tpl.html',
      resolve: {
        currentUser: function(User) {
          return User.current().$promise.then(function(user) {
            return (user.id ? user : null);
          });
        },
        onboarding: function(currentUser, Onboarding) {
          var onboardingData = (currentUser && currentUser.onboarding);
          if (!_.any(onboardingData)) return null;
          return new Onboarding(currentUser);
        }
      },
      onEnter: function(currentUser) {
        window.hyloEnv.provideUser(currentUser);
      },
      controller: function($scope, $rootScope, currentUser, onboarding) {
        $rootScope.currentUser = currentUser;
      }
    })
    .state('appEntry', /*@ngInject*/ {
      parent: 'main',
      url: '/app',
      onEnter: function(currentUser, $state, $timeout, onboarding) {
        var membership = (currentUser && currentUser.memberships[0]);
        if (membership) {
          $timeout(function() {
            $state.go('community.seeds', {community: membership.community.slug});
          });
        } else if (currentUser) {
          $timeout(function() {
            $state.go('home');
          });
        } else {
          $timeout(function() {
            $state.go('login');
          })
        }
      }
    })
    .state('loginSignup', {
      abstract: true,
      resolve: {
        loggedIn: function(User, $timeout, $state) {
          return User.status().$promise.then(function(res) {
            return res.signedIn;
          });
        }
      },
      onEnter: function(loggedIn, $timeout, $state) {
        if (loggedIn) {
          $timeout(function() {
            $state.go('appEntry');
          });
        } else {
          window.hyloEnv.provideUser(null);
        }
      },
      template: '

'
    })
    .state('login', {
      url: '/h/login',
      parent: 'loginSignup',
      views: {
        loginSignup: {
          templateUrl: '/ui/user/login.tpl.html',
          controller: 'LoginCtrl'
        }
      }
    })
    .state('signup', {
      url: '/h/signup',
      parent: 'loginSignup',
      views: {
        loginSignup: {
          templateUrl: 'ui/user/signup.tpl.html',
          controller: 'SignupCtrl'
        }
      }
    })
    .state('userSettings', {
      url: '/settings',
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/user/settings.tpl.html',
          controller: 'UserSettingsCtrl'
        }
      }
    })
    .state('network', {
      url: "/n/:network",
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/app/network.tpl.html',
          controller: 'NetworkCtrl'
        }
      }
    })
    .state('support', {
      url: '/h/support',
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/support/base.tpl.html',
          controller: function($anchorScroll) {
            $anchorScroll();
          }
        }
      }
    })
    .state('notifications', {
      url: '/h/notifications',
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/user/notifications.tpl.html',
          controller: 'NotificationsCtrl'
        }
      },
      resolve: {
        activity: function(Activity) {
          return Activity.query({limit: 50}).$promise;
        }
      }
    })
    .state('search', {
      url: "/h/search?q&c",
      parent: 'main',
      resolve: /*@ngInject*/ {
        initialQuery: function($stateParams) {
          return $stateParams.q;
        },
        searchCommunity: function($stateParams, Community) {
          if ($stateParams.c)
            return Community.get({id: $stateParams.c}).$promise;
        }
      },
      views: {
        main: {
          templateUrl: '/ui/app/search.tpl.html',
          controller: 'SearchCtrl'
        }
      }
    });

    require('./routes/community')($stateProvider);
    require('./routes/profile')($stateProvider);
    require('./routes/onboarding')($stateProvider);
    require('./routes/home')($stateProvider);

};

module.exports = function (angularModule) {
  angularModule.config(routes);
};<commit_msg>damned leading slashes<commit_after>
var routes = function ($stateProvider, $urlRouterProvider) {

  $urlRouterProvider.otherwise(function($injector, $location){
    var state = $injector.get('$state');
    Rollbar.warning("404 Error: " + $location.path());
    state.go('notFound');
    return $location.path();
  });

  // handle old single-post links
  $urlRouterProvider.when('/c/:community/s/:seedId/comments', '/c/:community/s/:seedId');

  // handle alternate name of starting route
  $urlRouterProvider.when('/', '/app');

  $stateProvider
    .state('notFound', {
      templateUrl: '/ui/app/404.tpl.html'
    })
    .state('main', /*@ngInject*/ {
      abstract: true,
      templateUrl: '/ui/shared/main.tpl.html',
      resolve: {
        currentUser: function(User) {
          return User.current().$promise.then(function(user) {
            return (user.id ? user : null);
          });
        },
        onboarding: function(currentUser, Onboarding) {
          var onboardingData = (currentUser && currentUser.onboarding);
          if (!_.any(onboardingData)) return null;
          return new Onboarding(currentUser);
        }
      },
      onEnter: function(currentUser) {
        window.hyloEnv.provideUser(currentUser);
      },
      controller: function($scope, $rootScope, currentUser, onboarding) {
        $rootScope.currentUser = currentUser;
      }
    })
    .state('appEntry', /*@ngInject*/ {
      parent: 'main',
      url: '/app',
      onEnter: function(currentUser, $state, $timeout, onboarding) {
        var membership = (currentUser && currentUser.memberships[0]);
        if (membership) {
          $timeout(function() {
            $state.go('community.seeds', {community: membership.community.slug});
          });
        } else if (currentUser) {
          $timeout(function() {
            $state.go('home');
          });
        } else {
          $timeout(function() {
            $state.go('login');
          })
        }
      }
    })
    .state('loginSignup', {
      abstract: true,
      resolve: {
        loggedIn: function(User, $timeout, $state) {
          return User.status().$promise.then(function(res) {
            return res.signedIn;
          });
        }
      },
      onEnter: function(loggedIn, $timeout, $state) {
        if (loggedIn) {
          $timeout(function() {
            $state.go('appEntry');
          });
        } else {
          window.hyloEnv.provideUser(null);
        }
      },
      template: '

'
    })
    .state('login', {
      url: '/h/login',
      parent: 'loginSignup',
      views: {
        loginSignup: {
          templateUrl: '/ui/user/login.tpl.html',
          controller: 'LoginCtrl'
        }
      }
    })
    .state('signup', {
      url: '/h/signup',
      parent: 'loginSignup',
      views: {
        loginSignup: {
          templateUrl: '/ui/user/signup.tpl.html',
          controller: 'SignupCtrl'
        }
      }
    })
    .state('userSettings', {
      url: '/settings',
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/user/settings.tpl.html',
          controller: 'UserSettingsCtrl'
        }
      }
    })
    .state('network', {
      url: "/n/:network",
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/app/network.tpl.html',
          controller: 'NetworkCtrl'
        }
      }
    })
    .state('support', {
      url: '/h/support',
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/support/base.tpl.html',
          controller: function($anchorScroll) {
            $anchorScroll();
          }
        }
      }
    })
    .state('notifications', {
      url: '/h/notifications',
      parent: 'main',
      views: {
        main: {
          templateUrl: '/ui/user/notifications.tpl.html',
          controller: 'NotificationsCtrl'
        }
      },
      resolve: {
        activity: function(Activity) {
          return Activity.query({limit: 50}).$promise;
        }
      }
    })
    .state('search', {
      url: "/h/search?q&c",
      parent: 'main',
      resolve: /*@ngInject*/ {
        initialQuery: function($stateParams) {
          return $stateParams.q;
        },
        searchCommunity: function($stateParams, Community) {
          if ($stateParams.c)
            return Community.get({id: $stateParams.c}).$promise;
        }
      },
      views: {
        main: {
          templateUrl: '/ui/app/search.tpl.html',
          controller: 'SearchCtrl'
        }
      }
    });

    require('./routes/community')($stateProvider);
    require('./routes/profile')($stateProvider);
    require('./routes/onboarding')($stateProvider);
    require('./routes/home')($stateProvider);

};

module.exports = function (angularModule) {
  angularModule.config(routes);
};<|endoftext|>