<commit_before>var fs = require('fs'),
	util = require('util'),
	EventEmitter = require('events').EventEmitter,
	// RegExp for stripping "ed" from "joined", "parted", "kicked"
	edRx = /ed$/,
	// Default regular expressions for log parsing
	defaultRegexps = {
		// Separator: $1 = Day changed / Log opened/closed; $2 = date
		separator: /^--- (\w+ \w+) (.*)$/,
		// Join/part/etc.: $1 = time, $2 = nick, $3 = mask, $4 = joined/parted/etc., $5 = quit/part message
		populate: /^(\d\d:\d\d:\d\d)-!- (\S+) \[([^\]]+)\] has (\w+)(?:[^\[]*\[([^\]]*))?/,
		// Kick: $1 = time, $2 = nick, $3 = kicker, $4 = message
		kick: /^(\d\d:\d\d:\d\d)-!- (\S+) was kicked from \S by (\S) \[([^\]]+)\]$/,
		// Nick change: $1 = time, $2 = old nick, $3 = new nick
		nick: /^(\d\d:\d\d:\d\d)-!- (\S+) is now known as (\S+)$/,
		// Own nick change: $1 = time, $2 = new nick
		ownNick: /^(\d\d:\d\d:\d\d)-!- You're now known as (\S+)$/,
		// Total nicks in channel upon join: $1 = time, $2 = total, $3 = ops, $4 = halfops, $5 = voices, $6 = normal
		nicks: /^(\d\d:\d\d:\d\d)-!- Irssi: \S+ Total of (\d+) nicks \[(\d+) ops, (\d+) halfops, (\d+) voices, (\d+) normal\]$/,
		// Modes: $1 = time, $2 = modes, $3 = moder
		mode: /^(\d\d:\d\d:\d\d)-!- (?:ServerM|m)ode\/\S+ \[([^\]]+)\] by (\S*)$/,
		// Regular messages: $1 = time, $2 = mode, $3 = nick, $4 = message
		message: /^(\d\d:\d\d:\d\d)<(.)([^>]+)> (.*)$/,
		// Actions: $1 = time, $2 = nick, $3 = message
		action: /^(\d\d:\d\d:\d\d) \* (\S+) (.*)$/
	},
	// Actions to be taken for each line type above
	mappings = {
		separator: function (match) {
			var type = match[1];
			this.currentDate = new Date(match[2]);
			if (type === 'Day changed') {
				// Just update currentDate; don't emit
				return;
			}
			type = type === 'Log opened' ? 'logopen' : 'logclose';
			if (type === 'logopen') {
				// Update own nick on next join
				this._setNick = true;
			}

			return {
				type: type,
				time: this.currentDate
			};
		},
		populate: function (match) {
			var type = match[4].replace(edRx, '');
			if (this._setNick && type === 'join') {
				// Logging client just joined the channel, so update nick
				// (since own nick changes don't indicate previous nick)
				this._nick = match[2];
				this._setNick = false;
			}
			return {
				type: type,
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				mask: match[3],
				message: match[5]
			};
		},
		kick: function (match) {
			return {
				type: 'kick',
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				by: match[3],
				message: match[4]
			};
		},
		nick: function (match) {
			return {
				type: 'nick',
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				newNick: match[3]
			};
		},
		ownNick: function (match) {
			return {
				type: 'nick',
				time: combineDateTime(this.currentDate, match[1]),
				nick: this._nick,
				newNick: (this._nick = match[2])
			};
		},
		nicks: function (match) {
			return {
				type: 'nicks',
				time: combineDateTime(this.currentDate, match[1]),
				total: match[2],
				ops: match[3],
				halfops: match[4],
				voices: match[5],
				normal: match[6]
			};
		},
		mode: function (match) {
			return {
				type: 'mode',
				time: combineDateTime(this.currentDate, match[1]),
				mode: match[2],
				by: match[3]
			};
		},
		message: function (match) {
			return {
				type: 'message',
				time: combineDateTime(this.currentDate, match[1]),
				mode: match[2],
				nick: match[3],
				message: match[4]
			};
		},
		action: function (match) {
			return {
				type: 'action',
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				message: match[3]
			};
		}
	},
	// Order to test RegExps in, from least to most common (will iterate backwards)
	testOrder = ['nicks', 'separator', 'ownNick', 'kick', 'mode', 'nick', 'action', 'populate', 'message'];

function mixin(dest, src) {
	Object.keys(src).forEach(function (k) {
		dest[k] = src[k];
	});
}

function combineDateTime(date, time) {
	// Yields a new Date object combining the given Date object and
	// a "hh:mm:ss" time string.
	var dateTime = new Date(date),
		timeParts = time.split(':');
	dateTime.setHours(parseInt(timeParts[0], 10));
	dateTime.setMinutes(parseInt(timeParts[1], 10));
	dateTime.setSeconds(parseInt(timeParts[2], 10));
	return dateTime;
}

var Parser = module.exports = function (options) {
	EventEmitter.call(this);
	if (options) {
		mixin(this, options);
	}
	this._onAllHandlers = [];
};
util.inherits(Parser, EventEmitter);

mixin(Parser.prototype, {
	_parseLine: function (line) {
		var i = testOrder.length,
			key,
			match;

		while (i--) {
			key = testOrder[i];
			if ((match = defaultRegexps[key].exec(line))) {
				return mappings[key].call(this, match);
			}
		}
		if (this.debug) {
			console.warn('Unhandled line: ' + line);
		}
	},

	_parseLines: function (str) {
		// Parses any full lines in str and adds their info to the `parsed` object.
		// Returns any remainder of str (i.e. from a final line with no newline).

		var lines = str.split('\n'),
			i = 0,
			remainder = lines.pop(),
			len = lines.length,
			parsedObj;

		do {
			parsedObj = this._parseLine(lines[i]);
			if (parsedObj) {
				this.emit(parsedObj.type, parsedObj);
			}
		}
		while (++i < len);

		return remainder;
	},

	parse: function (filename) {
		var
			resume = filename === true, // should only ever be set by resume calls
			fd = this._fd = resume ? this._fd : fs.openSync(filename, 'r'),
			buffer = new Buffer(4096),
			bytesRead,
			current = '',
			remainder = resume ? this._remainder : '';

		while (!this._paused && (bytesRead = fs.readSync(fd, buffer, 0, buffer.length))) {
			current = buffer.toString('utf-8');
			if (current.length > bytesRead) { current = current.slice(0, bytesRead); }
			remainder = this._remainder = this._parseLines(remainder + current);
		}

		// The loop will end either when EOF is reached, or pause was called.
		// In the former case, close the file; in the latter case, leave it
		// open with the expectation that we'll pick up where we left off.
		if (!this._paused) {
			fs.closeSync(fd);
		}
	},

	pause: function () {
		// Pauses after the currently-read chunk is processed.
		// This means that it might not pause right after the current line, but
		// it will before the file is read any further.
		// Consecutive calls to this function when already paused are harmless.
		this._paused = true;
	},

	resume: function () {
		// Causes the previous parse to continue where it left off.
		if (this._paused) {
			this._paused = false;
			this.parse(true);
		}
	},

	emit: function () {
		var i,
			handlers = this._onAllHandlers,
			len = handlers.length;

		// Emit as usual
		EventEmitter.prototype.emit.apply(this, arguments);

		// Also invoke any handlers registered for all events
		for (i = 0; i < len; i++) {
			if (handlers[i]) {
				handlers[i].apply(this, handlers.slice.call(arguments, 1));
			}
		}
	},

	onAll: function (handler) {
		// Binds a function to all emitted events.
		// Rather than impose an obtuse separate removal method,
		// this method returns an object with a remove function.

		var i = this._onAllHandlers.push(handler) - 1;
		return {
			remove: function () {
				this._onAllHandlers[i] = null;
			}
		};
	}
});<commit_msg>Make default regexps a bit more flexible<commit_after>var fs = require('fs'),
	util = require('util'),
	EventEmitter = require('events').EventEmitter,
	// RegExp for stripping "ed" from "joined", "parted", "kicked"
	edRx = /ed$/,
	// Default regular expressions for log parsing
	defaultRegexps = {
		// Log open / log close / day change: $1 = date+time
		logopen: /^--- Log opened (.*)$/,
		logclose: /^--- Log closed (.*)$/,
		daychange: /^--- Day changed (.*)$/,
		// Join/part/etc.: $1 = time, $2 = nick, $3 = mask, $4 = joined/parted/etc., $5 = quit/part message
		populate: /^(\d\d:\d\d(?::\d\d)?)-!- (\S+) \[([^\]]+)\] has (\w+)(?:[^\[]*\[([^\]]*))?/,
		// Kick: $1 = time, $2 = nick, $3 = kicker, $4 = message
		kick: /^(\d\d:\d\d(?::\d\d)?)-!- (\S+) was kicked from \S by (\S) \[([^\]]+)\]$/,
		// Nick change: $1 = time, $2 = old nick, $3 = new nick
		nick: /^(\d\d:\d\d(?::\d\d)?)-!- (\S+) is now known as (\S+)$/,
		// Own nick change: $1 = time, $2 = new nick
		ownNick: /^(\d\d:\d\d(?::\d\d)?)\W+You're now known as (\S+)$/,
		// Total nicks in channel upon join: $1 = time, $2 = total, $3 = ops, $4 = halfops, $5 = voices, $6 = normal
		nicks: /^(\d\d:\d\d(?::\d\d)?)\W+Irssi: \S+ Total of (\d+) nicks \[(\d+) ops, (\d+) halfops, (\d+) voices, (\d+) normal\]$/,
		// Modes: $1 = time, $2 = modes, $3 = moder
		mode: /^(\d\d:\d\d(?::\d\d)?)-!- (?:ServerM|m)ode\/\S+ \[([^\]]+)\] by (\S*)$/,
		// Regular messages: $1 = time, $2 = mode, $3 = nick, $4 = message
		message: /^(\d\d:\d\d(?::\d\d)?)<(.)([^>]+)> (.*)$/,
		// Actions: $1 = time, $2 = nick, $3 = message
		action: /^(\d\d:\d\d(?::\d\d)?) \* (\S+) (.*)$/
	},
	// Actions to be taken for each line type above
	mappings = {
		logopen: function (match) {
			return {
				type: 'logopen',
				time: (this.currentDate = this._openTime = new Date(match[1]))
			};
		},
		logclose: function (match) {
			return {
				type: 'logclose',
				time: (this.currentDate = new Date(match[1]))
			};
		},
		daychange: function (match) {
			// Update currentDate but don't bother emitting an event
			this.currentDate = new Date(match[1]);
		},
		populate: function (match) {
			var type = match[4].replace(edRx, '');
			if (this._setNick && type === 'join') {
				// Logging client just joined the channel, so update nick
				// (since own nick changes don't indicate previous nick)
				this._nick = match[2];
				this._setNick = false;
			}
			return {
				type: type,
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				mask: match[3],
				message: match[5]
			};
		},
		kick: function (match) {
			return {
				type: 'kick',
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				by: match[3],
				message: match[4]
			};
		},
		nick: function (match) {
			return {
				type: 'nick',
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				newNick: match[3]
			};
		},
		ownNick: function (match) {
			return {
				type: 'nick',
				time: combineDateTime(this.currentDate, match[1]),
				nick: this._nick,
				newNick: (this._nick = match[2])
			};
		},
		nicks: function (match) {
			return {
				type: 'nicks',
				time: combineDateTime(this.currentDate, match[1]),
				total: match[2],
				ops: match[3],
				halfops: match[4],
				voices: match[5],
				normal: match[6]
			};
		},
		mode: function (match) {
			return {
				type: 'mode',
				time: combineDateTime(this.currentDate, match[1]),
				mode: match[2],
				by: match[3]
			};
		},
		message: function (match) {
			return {
				type: 'message',
				time: combineDateTime(this.currentDate, match[1]),
				mode: match[2],
				nick: match[3],
				message: match[4]
			};
		},
		action: function (match) {
			return {
				type: 'action',
				time: combineDateTime(this.currentDate, match[1]),
				nick: match[2],
				message: match[3]
			};
		}
	},
	// Order to test RegExps in, from least to most common (will iterate backwards)
	testOrder = ['nicks', 'daychange', 'logclose', 'logopen', 'ownNick', 'kick', 'mode', 'nick', 'action', 'populate', 'message'];

function mixin(dest, src) {
	Object.keys(src).forEach(function (k) {
		dest[k] = src[k];
	});
}

function combineDateTime(date, time) {
	// Yields a new Date object combining the given Date object and
	// a "hh:mm:ss" time string.
	var dateTime = new Date(date),
		timeParts = time.split(':');
	dateTime.setHours(parseInt(timeParts[0], 10));
	dateTime.setMinutes(parseInt(timeParts[1], 10));
	dateTime.setSeconds(parseInt(timeParts[2] || 0, 10));
	return dateTime;
}

var Parser = module.exports = function (options) {
	EventEmitter.call(this);
	if (options) {
		mixin(this, options);
	}
	this._onAllHandlers = [];
};
util.inherits(Parser, EventEmitter);

mixin(Parser.prototype, {
	_parseLine: function (line) {
		var i = testOrder.length,
			key,
			match;

		while (i--) {
			key = testOrder[i];
			if ((match = defaultRegexps[key].exec(line))) {
				return mappings[key].call(this, match);
			}
		}
		if (this.debug) {
			console.warn('Unhandled line: ' + line);
		}
	},

	_parseLines: function (str) {
		// Parses any full lines in str and adds their info to the `parsed` object.
		// Returns any remainder of str (i.e. from a final line with no newline).

		var lines = str.split('\n'),
			i = 0,
			remainder = lines.pop(),
			len = lines.length,
			parsedObj;

		do {
			parsedObj = this._parseLine(lines[i]);
			if (parsedObj) {
				this.emit(parsedObj.type, parsedObj);
			}
		}
		while (++i < len);

		return remainder;
	},

	parse: function (filename) {
		var
			resume = filename === true, // should only ever be set by resume calls
			fd = this._fd = resume ? this._fd : fs.openSync(filename, 'r'),
			buffer = new Buffer(4096),
			bytesRead,
			current = '',
			remainder = resume ? this._remainder : '';

		while (!this._paused && (bytesRead = fs.readSync(fd, buffer, 0, buffer.length))) {
			current = buffer.toString('utf-8');
			if (current.length > bytesRead) { current = current.slice(0, bytesRead); }
			remainder = this._remainder = this._parseLines(remainder + current);
		}

		// The loop will end either when EOF is reached, or pause was called.
		// In the former case, close the file; in the latter case, leave it
		// open with the expectation that we'll pick up where we left off.
		if (!this._paused) {
			fs.closeSync(fd);
		}
	},

	pause: function () {
		// Pauses after the currently-read chunk is processed.
		// This means that it might not pause right after the current line, but
		// it will before the file is read any further.
		// Consecutive calls to this function when already paused are harmless.
		this._paused = true;
	},

	resume: function () {
		// Causes the previous parse to continue where it left off.
		if (this._paused) {
			this._paused = false;
			this.parse(true);
		}
	},

	emit: function () {
		var i,
			handlers = this._onAllHandlers,
			len = handlers.length;

		// Emit as usual
		EventEmitter.prototype.emit.apply(this, arguments);

		// Also invoke any handlers registered for all events
		for (i = 0; i < len; i++) {
			if (handlers[i]) {
				handlers[i].apply(this, handlers.slice.call(arguments, 1));
			}
		}
	},

	onAll: function (handler) {
		// Binds a function to all emitted events.
		// Rather than impose an obtuse separate removal method,
		// this method returns an object with a remove function.

		var i = this._onAllHandlers.push(handler) - 1;
		return {
			remove: function () {
				this._onAllHandlers[i] = null;
			}
		};
	}
});<|endoftext|>


<commit_before>import Item from '../../main/js/Item';
import {equality} from '../../main/js/Item';

describe('An item', () => {

  beforeEach(() => {
    jasmine.addCustomEqualityTester(equality);
  });

  it('should have a working equality method', () => {
    let item1 = new Item('something');
    let item2 = new Item('something');

    expect(item1).toEqual(item2);
  });

  it('should have custom click handlers', () => {
    let myItem = new Item('something');
    let clickText = 'click something';
    myItem.on('click', () => {
      return clickText;
    });
    let ret = myItem.click();

    expect(ret).toEqual(clickText);
  });

  it('may be used with other items in both directions', () => {
    let paper = new Item('paper');
    let pen = new Item('pen');
    let text = new Item('text');
    paper.on('use', {
      pen : {
        returns : text
      }
    });

    expect(paper.use(pen)).toEqual(text);
    expect(pen.use(paper)).toEqual(text);
  });

  it('should not be possible to have different usages with the same items', () => {
    let paper = new Item('paper');
    let pen = new Item('pen');
    let text = new Item('text');
    paper.on('use', {
      pen : {
        returns : text
      }
    });

    expect(() => {
      pen.on('use', {
        paper : {
          returns : pen
        }
      });
    }).toThrow();
  });

  it('should be possible to return multiple items on usage', () => {
    let map = new Item('map');
    let scissors = new Item('scissors');
    let mapPart = new Item('mapPart');
    let mapPartWithX = new Item('mapPartWithX');
    map.on('use', {
      scissors : {
        returns : [mapPart, mapPartWithX]
      }
    });

    expect(map.use(scissors)).toEqual([mapPart, mapPartWithX]);
  });

  it('should be okay to reuse items', () => {
    let coin = new Item('coin');
    let arcade = new Item('arcade');
    let money = new Item('money');
    coin.on('use', {
      arcade : {
        returns : money
      }
    });

    expect(coin.use(arcade)).toEqual(money);
    expect(coin.use(arcade)).toEqual(money);
    expect(coin.use(arcade)).toEqual(money);
  });

  it('should be possible to register a use only once', () => {
    let coin = new Item('coin');
    let arcade = new Item('arcade');
    let plushie = new Item('plushie');
    coin.on('use', {
      arcade : {
        once : true,
        returns : plushie
      }
    });

    expect(coin.use(arcade)).toEqual(plushie);
    expect(coin.use(arcade)).toBeUndefined();
  });

  it('should be possible to have a function that returns things and it gets executed', () => {
    let coin = new Item('coin');
    let arcade = new Item('arcade');
    let plushie = new Item('plushie');
    let changedSomething = false;

    coin.on('use', {
      arcade : () => {
        changedSomething = true;
        return {
          returns : plushie
        };
      }
    });

    expect(coin.use(arcade)).toEqual(plushie);
    expect(changedSomething).toBe(true);
  });

  it('should be possible to highlight items', () => {
    let $element = document.createElement('div');
    let something = new Item('something', $element);

    something.highlight();

    expect($element.classList.contains('highlight')).toBe(true);
  });

  it('should be possible to stop highlighting items', () => {
    let $element = document.createElement('div');
    let something = new Item('something', $element);

    something.highlight();
    something.stopHighlight();

    expect($element.classList.contains('highlight')).toBe(false);
  });

  it('has no current item in use if none was set', () => {
    fail('test missing');
  });

  it('may have a current item in use', () => {
    fail('test missing');
  });

  it('can unset an item in use', () => {
    fail('test missing');
  });
});
<commit_msg>Add test for setting/unsetting item in use<commit_after>import {default as Item, equality, getItemInUse, setItemInUse, unsetItemInUse} from '../../main/js/Item';

describe('An item', () => {

  beforeEach(() => {
    jasmine.addCustomEqualityTester(equality);
  });

  it('should have a working equality method', () => {
    let item1 = new Item('something');
    let item2 = new Item('something');

    expect(item1).toEqual(item2);
  });

  it('should have custom click handlers', () => {
    let myItem = new Item('something');
    let clickText = 'click something';
    myItem.on('click', () => {
      return clickText;
    });
    let ret = myItem.click();

    expect(ret).toEqual(clickText);
  });

  it('may be used with other items in both directions', () => {
    let paper = new Item('paper');
    let pen = new Item('pen');
    let text = new Item('text');
    paper.on('use', {
      pen : {
        returns : text
      }
    });

    expect(paper.use(pen)).toEqual(text);
    expect(pen.use(paper)).toEqual(text);
  });

  it('should not be possible to have different usages with the same items', () => {
    let paper = new Item('paper');
    let pen = new Item('pen');
    let text = new Item('text');
    paper.on('use', {
      pen : {
        returns : text
      }
    });

    expect(() => {
      pen.on('use', {
        paper : {
          returns : pen
        }
      });
    }).toThrow();
  });

  it('should be possible to return multiple items on usage', () => {
    let map = new Item('map');
    let scissors = new Item('scissors');
    let mapPart = new Item('mapPart');
    let mapPartWithX = new Item('mapPartWithX');
    map.on('use', {
      scissors : {
        returns : [mapPart, mapPartWithX]
      }
    });

    expect(map.use(scissors)).toEqual([mapPart, mapPartWithX]);
  });

  it('should be okay to reuse items', () => {
    let coin = new Item('coin');
    let arcade = new Item('arcade');
    let money = new Item('money');
    coin.on('use', {
      arcade : {
        returns : money
      }
    });

    expect(coin.use(arcade)).toEqual(money);
    expect(coin.use(arcade)).toEqual(money);
    expect(coin.use(arcade)).toEqual(money);
  });

  it('should be possible to register a use only once', () => {
    let coin = new Item('coin');
    let arcade = new Item('arcade');
    let plushie = new Item('plushie');
    coin.on('use', {
      arcade : {
        once : true,
        returns : plushie
      }
    });

    expect(coin.use(arcade)).toEqual(plushie);
    expect(coin.use(arcade)).toBeUndefined();
  });

  it('should be possible to have a function that returns things and it gets executed', () => {
    let coin = new Item('coin');
    let arcade = new Item('arcade');
    let plushie = new Item('plushie');
    let changedSomething = false;

    coin.on('use', {
      arcade : () => {
        changedSomething = true;
        return {
          returns : plushie
        };
      }
    });

    expect(coin.use(arcade)).toEqual(plushie);
    expect(changedSomething).toBe(true);
  });

  it('should be possible to highlight items', () => {
    let $element = document.createElement('div');
    let something = new Item('something', $element);

    something.highlight();

    expect($element.classList.contains('highlight')).toBe(true);
  });

  it('should be possible to stop highlighting items', () => {
    let $element = document.createElement('div');
    let something = new Item('something', $element);

    something.highlight();
    something.stopHighlight();

    expect($element.classList.contains('highlight')).toBe(false);
  });

  it('has no current item in use if none was set', () => {
    expect(getItemInUse()).toBe(null);
  });

  it('may have a current item in use', () => {
    let $element = document.createElement('div');
    let something = new Item('something', $element);
    expect(() => {
      setItemInUse(something);
    }).not.toThrow();
    expect(getItemInUse()).toBe(something);
    unsetItemInUse();
  });

  it('can unset an item in use', () => {
    let $element = document.createElement('div');
    let something = new Item('something', $element);
    expect(getItemInUse()).toBe(null);
    setItemInUse(something);
    expect(getItemInUse()).toBe(something);
    unsetItemInUse();
    expect(getItemInUse()).toBe(null);
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { createStore } from 'redux';
import { mount } from 'enzyme';
import toJSON from 'enzyme-to-json';

import { renderFakeForm, wrap } from '../../../utils/createTestForm';
import Tumbler from '../../../components/Tumbler/Tumbler';

const initialValues = {
    'mock-name': '',
};

const store = createStore(() => ({
    form: {
        mockForm: {
            values: initialValues,
        }
    }
}));

describe('Tumbler component', () => {
    const requiredProps = {
        name: 'mock-name',
    };

    it('renders correctly', () => {
        const tree = wrap(store)(initialValues)(
            <Tumbler
                {...requiredProps}
            />
        ).toJSON();

        expect(tree).toMatchSnapshot();
    });
});
<commit_msg>remove redundant stuff<commit_after>import React from 'react';
import { createStore } from 'redux';

import { wrap } from '../../../utils/createTestForm';
import Tumbler from '../../../components/Tumbler/Tumbler';

const initialValues = {
    'mock-name': '',
};

const store = createStore(() => ({
    form: {
        mockForm: {
            values: initialValues,
        }
    }
}));

describe('Tumbler component', () => {
    const requiredProps = {
        name: 'mock-name',
    };

    it('renders correctly', () => {
        const tree = wrap(store)(initialValues)(
            <Tumbler
                {...requiredProps}
            />
        ).toJSON();

        expect(tree).toMatchSnapshot();
    });
});
<|endoftext|>


<commit_before>class Player {
  static get VERSION() {
    return '0.1';
  }

  static betRequest(gameState) {
    for (var player in gameState.players) {
      if(player.name === "M und M") {
        for (var card in player.hole_cards) {
            if(card.rank === "A" || card.rank === "K" || card.rank === "Q" || card.rank === "J") {
              return 10;
            }
        }
      }
    }

    return 0;
  }

  static showdown(gameState) {
  }
}

module.exports = Player;
<commit_msg>Third move<commit_after>class Player {
  static get VERSION() {
    return '0.1';
  }

  static betRequest(gameState) {
    for (var player in gameState.players) {
      if(player.name === "M und M") {
        for (var card in player.hole_cards) {
            if(card.rank === "A" || card.rank === "K" || card.rank === "Q" || card.rank === "J" || card.rank === "10") {
              return 10;
            }
        }
      }
    }

    return 0;
  }

  static showdown(gameState) {
  }
}

module.exports = Player;
<|endoftext|>


<commit_before>$module('basic', function () {
  var $static = this;
  this.$class('SomeClass', false, function () {
    var $static = this;
    var $instance = this.prototype;
    $static.new = function () {
      var instance = new $static();
      var init = [];
      return $promise.all(init).then(function () {
        return instance;
      });
    };
    $instance.DoSomething = function () {
      var $this = this;
      var $state = $t.sm(function ($callback) {
        while (true) {
          switch ($state.current) {
            case 0:
              $state.resolve(true);
              return;

            default:
              $state.current = -1;
              return;
          }
        }
      });
      return $promise.build($state);
    };
  });

  this.$type('MyType', function () {
    var $instance = this;
    $instance.AnotherThing = function ($this) {
      var $state = $t.sm(function ($callback) {
        while (true) {
          switch ($state.current) {
            case 0:
              $this.DoSomething().then(function ($result0) {
                $result = $result0;
                $state.current = 1;
                $callback($state);
              }).catch(function (err) {
                $state.reject(err);
              });
              return;

            case 1:
              $state.resolve($result);
              return;

            default:
              $state.current = -1;
              return;
          }
        }
      });
      return $promise.build($state);
    };
    $instance.SomeProp = $t.property(true, function ($this) {
      var $state = $t.sm(function ($callback) {
        while (true) {
          switch ($state.current) {
            case 0:
              $state.resolve(true);
              return;

            default:
              $state.current = -1;
              return;
          }
        }
      });
      return $promise.build($state);
    });
  });

  $static.TEST = function () {
    var m;
    var sc;
    var $state = $t.sm(function ($callback) {
      while (true) {
        switch ($state.current) {
          case 0:
            $g.basic.SomeClass.new().then(function ($result0) {
              $result = $result0;
              $state.current = 1;
              $callback($state);
            }).catch(function (err) {
              $state.reject(err);
            });
            return;

          case 1:
            sc = $result;
            m = sc;
            $g.basic.MyType.SomeProp(m).then(function ($result0) {
              return $g.basic.MyType.AnotherThing(m).then(function ($result1) {
                $result = $result0 && $result1;
                $state.current = 2;
                $callback($state);
              });
            }).catch(function (err) {
              $state.reject(err);
            });
            return;

          case 2:
            $state.resolve($result);
            return;

          default:
            $state.current = -1;
            return;
        }
      }
    });
    return $promise.build($state);
  };
});
<commit_msg>Regenerate ES5 golden file for the nominal fix<commit_after>$module('basic', function () {
  var $static = this;
  this.$class('SomeClass', false, function () {
    var $static = this;
    var $instance = this.prototype;
    $static.new = function () {
      var instance = new $static();
      var init = [];
      return $promise.all(init).then(function () {
        return instance;
      });
    };
    $instance.DoSomething = function () {
      var $this = this;
      var $state = $t.sm(function ($callback) {
        while (true) {
          switch ($state.current) {
            case 0:
              $state.resolve(true);
              return;

            default:
              $state.current = -1;
              return;
          }
        }
      });
      return $promise.build($state);
    };
  });

  this.$type('MyType', function () {
    var $instance = this;
    var $static = this;
    $instance.AnotherThing = function ($this) {
      var $state = $t.sm(function ($callback) {
        while (true) {
          switch ($state.current) {
            case 0:
              $this.DoSomething().then(function ($result0) {
                $result = $result0;
                $state.current = 1;
                $callback($state);
              }).catch(function (err) {
                $state.reject(err);
              });
              return;

            case 1:
              $state.resolve($result);
              return;

            default:
              $state.current = -1;
              return;
          }
        }
      });
      return $promise.build($state);
    };
    $instance.SomeProp = $t.property(true, function ($this) {
      var $state = $t.sm(function ($callback) {
        while (true) {
          switch ($state.current) {
            case 0:
              $state.resolve(true);
              return;

            default:
              $state.current = -1;
              return;
          }
        }
      });
      return $promise.build($state);
    });
  });

  $static.TEST = function () {
    var m;
    var sc;
    var $state = $t.sm(function ($callback) {
      while (true) {
        switch ($state.current) {
          case 0:
            $g.basic.SomeClass.new().then(function ($result0) {
              $result = $result0;
              $state.current = 1;
              $callback($state);
            }).catch(function (err) {
              $state.reject(err);
            });
            return;

          case 1:
            sc = $result;
            m = sc;
            $g.basic.MyType.SomeProp(m).then(function ($result0) {
              return $g.basic.MyType.AnotherThing(m).then(function ($result1) {
                $result = $result0 && $result1;
                $state.current = 2;
                $callback($state);
              });
            }).catch(function (err) {
              $state.reject(err);
            });
            return;

          case 2:
            $state.resolve($result);
            return;

          default:
            $state.current = -1;
            return;
        }
      }
    });
    return $promise.build($state);
  };
});
<|endoftext|>


<commit_before>var Player = function(x, y, reverse)
{
    this.x             = x || 0;
    this.y             = y || 0;
	this.velY          = 0;
	this.velX          = 0;
	this.floorY        = y;
	this.jumpMagnitude = -0.7;//negative because the y axis is inverted
	this.gravity       = 0.005;
    this.reverse       = reverse;

	this.gunCD		   = 0;//The number of milliseconds before the gun can be reloaded.
	this.gunMaxCD      = 1200;//The number of milliseconds between one shot and the reload.
	this.reloadCD      = 0;//The number of milliseconds before the gun can be fired
	this.reloadMaxCD   = 500;//The number of milliseconds between the end of the fire sound and the reload

    this.gunShotSound  = new Audio('./GameGunshot.wav');
    this.reloadSound   = new Audio('./ReloadSound.wav');

	this.waitingForDraw = true;
	this.drawTimer      = 0;
	this.maxDrawTimer   = 0;

    this.enemyA        = 0;
    this.angle         = -1;
    this.da            = 0;
    this.maxDa         = 0.2;

	this.score 		   = 0;//The player's score that they have earned by shooting the opponent
	this.enemy 		   = null;//A reference to the opposing player. this.enemy.enemy = this
    this.hit           = false;

    this.gunSprite     = null;
    this.bloodSprite   = null;
    this.charSprite    = null;

    this.h = 0;//The actual height of the player

	this.characterSelection = 0; //which character the player's sprite is
}

Player.prototype =
{
    update: function(dt)
    {
		if(this.waitingForDraw){ //players can't shoot until ref says draw
			this.drawTimer += dt;
			if(this.drawTimer / 1000.0 >= this.maxDrawTimer){
				this.drawTimer = 0;
				this.waitingForDraw = false;
				console.log("Draw!");
				this.maxDrawTimer = Math.random() * 10 + 2;
			}
		} else {
            var e = 0.005;
            var aDiff = this.angle - this.enemyA;

            if (aDiff < 0) {
                if (this.da < 0 || aDiff < -e) {
                    this.da += 0.01;
                }
            } else if (aDiff > 0) {
                if (this.da > 0 || aDiff > e) {
                    this.da -= 0.01;
                }
            }
        }

        this.da += this.velY / 40;

        this.da *= 0.9;
        this.angle += this.da;

		this.reloadCD -= dt;//tick the reload timer down

		if(this.gunCD > 0){//Setting it from 0 to -delta would cause the reload sound to play constantly - would be game breaking.

			this.gunCD -= dt;//tick the cooldown timer down

			//This is where you play the reload sound (there would be a bug if gunCD happened to reach exactly 0 then the reload sound wouldn't play
			//But it is unlikely
			if(this.gunCD == 0){
				this.gunCD = -1;//This way you won't get a 1/delta bug where the reload sound won't play
			}

			if(this.reloadCD < 0){
				this.reloadCD = 0;//Just set it to 0 for simplicity's sake.
			}

			if(this.gunCD < 0){
				//Play the reload sound here!!
				this.reloadSound.play();
				this.reloadCD = this.reloadMaxCD;//Put it on reload cooldown
				this.gunCD = 0;//Set it to 0 so the game knows not to play the reload sound again.

			}
		}

        if (this.y != this.floorY) {//If the player is not on the floor, gravity accelerates them downward
            this.velY += this.gravity * dt;
        }

        this.y += this.velY * dt;//Move based on the current x and y velocities
        this.x += this.velX * dt;

        if (this.y > this.floorY) {
            if (!this.hit) {
                this.charSprite.changeAnim(0);
            }
            this.y = this.floorY;
            this.velY = 0;
        }

        this.charSprite.update(dt);
        this.gunSprite.update(dt);

        if (!this.bloodSprite.anims[0].complete) {
            this.bloodSprite.update(dt);
        }

        if(!this.gunSprite.anims[0].complete) {
            this.gunSprite.update(dt);
        } else {
            this.gunSprite.anims[0].frame = 0;
        }
    },

    setTimer: function(time)
    {
        this.maxDrawTimer = time;
        this.waitingForDraw = true;
    },

    jump: function()
    {
        if(!this.hit && this.y===this.floorY){//If you're on the ground
            this.velY = this.jumpMagnitude;//
            this.charSprite.changeAnim(2);
        }

    },

    duck: function()
    {
    },

    shoot: function(enemy)
    {
		this.gunShotSound.play();
		var shot = new Shot(this.x, this.y + (this.h / 2), this.angle, enemy);
		this.gunCD = this.gunMaxCD;

        this.gunSprite.anims[0].complete = false;
        this.gunSprite.anims[0].frame = 0;

		return shot;
    },

	reset: function(){
        this.waitingForDraw = true;
        this.drawTimer      = 0;
        this.maxDrawTimer   = 0;

        this.angle         = -1;
        this.da            = 0;

        this.hit           = false;

        this.charSprite.anims[3].complete = false;
        this.charSprite.anims[3].frame = 0;
        this.charSprite.changeAnim(0);
	},

    setFloor: function(y)
    {
        this.y      = y - (this.h);
        this.floorY = this.y;
    },

    giveResources: function(resources)
    {
        this.bloodSprite = resources.sprBlood.clone();
    },

    setChar: function(c)
    {
        this.charSprite = c;

        this.w = 2 * this.charSprite.w;
        this.h = 2 * this.charSprite.h;

        //adjust the y position so that sprites of all dimensions are properly aligned to the floor
        this.y -= this.h;
        this.floorY = this.y;
    },

    setGun: function(g)
    {
        this.gunSprite = g;
    },

    kill: function(colY)
    {
        this.colY = colY;
        this.bloodSprite.anims[0].complete = false;
        this.bloodSprite.anims[0].frame = 0;
        this.hit = true;

        this.charSprite.changeAnim(3);
    },

    draw: function(canvas)
    {
        if (this.reverse) {
            canvas.scale(-1,1);
            this.x = -this.x;
        }

        if (!this.hit) {
            canvas.translate(this.x + this.w - 12, this.y + (this.h / 2) - 8);
            canvas.rotate(-this.angle);
            this.gunSprite.draw(canvas, 0, 0);
            canvas.rotate(this.angle);
            canvas.translate(-(this.x + this.w - 12), -(this.y + (this.h / 2) - 8));
        }

        this.charSprite.draw(canvas, this.x, this.y);

        if (!this.bloodSprite.anims[0].complete) {
            this.bloodSprite.draw(canvas, this.x + (0.7 * this.w), this.y + (this.h - this.colY) - 6);
        }

        if (this.reverse) {
            canvas.scale(-1,1);
            this.x = -this.x;
        }
    },

	setEnemy: function(enemy){
		this.enemy = enemy;
	},

	canShoot: function(){
		if(this.waitingForDraw || this.hit){
			return false;
		}

		if(this.gunCD <= 0 && this.reloadCD <= 0){
			return true;
		}

		//otherwise
		return false;

	}
}
<commit_msg>WILHELM SCREAM<commit_after>var Player = function(x, y, reverse)
{
    this.x             = x || 0;
    this.y             = y || 0;
	this.velY          = 0;
	this.velX          = 0;
	this.floorY        = y;
	this.jumpMagnitude = -0.7;//negative because the y axis is inverted
	this.gravity       = 0.005;
    this.reverse       = reverse;

	this.gunCD		   = 0;//The number of milliseconds before the gun can be reloaded.
	this.gunMaxCD      = 1200;//The number of milliseconds between one shot and the reload.
	this.reloadCD      = 0;//The number of milliseconds before the gun can be fired
	this.reloadMaxCD   = 500;//The number of milliseconds between the end of the fire sound and the reload

    this.gunShotSound  = new Audio('./GameGunshot.wav');
    this.reloadSound   = new Audio('./ReloadSound.wav');
	this.wilhelmScream = new Audio('./WilhelmScream.wav');

	this.waitingForDraw = true;
	this.drawTimer      = 0;
	this.maxDrawTimer   = 0;

    this.enemyA        = 0;
    this.angle         = -1;
    this.da            = 0;
    this.maxDa         = 0.2;

	this.score 		   = 0;//The player's score that they have earned by shooting the opponent
	this.enemy 		   = null;//A reference to the opposing player. this.enemy.enemy = this
    this.hit           = false;

    this.gunSprite     = null;
    this.bloodSprite   = null;
    this.charSprite    = null;

    this.h = 0;//The actual height of the player

	this.characterSelection = 0; //which character the player's sprite is
}

Player.prototype =
{
    update: function(dt)
    {
		if(this.waitingForDraw){ //players can't shoot until ref says draw
			this.drawTimer += dt;
			if(this.drawTimer / 1000.0 >= this.maxDrawTimer){
				this.drawTimer = 0;
				this.waitingForDraw = false;
				console.log("Draw!");
				this.maxDrawTimer = Math.random() * 10 + 2;
			}
		} else {
            var e = 0.005;
            var aDiff = this.angle - this.enemyA;

            if (aDiff < 0) {
                if (this.da < 0 || aDiff < -e) {
                    this.da += 0.01;
                }
            } else if (aDiff > 0) {
                if (this.da > 0 || aDiff > e) {
                    this.da -= 0.01;
                }
            }
        }

        this.da += this.velY / 40;

        this.da *= 0.9;
        this.angle += this.da;

		this.reloadCD -= dt;//tick the reload timer down

		if(this.gunCD > 0){//Setting it from 0 to -delta would cause the reload sound to play constantly - would be game breaking.

			this.gunCD -= dt;//tick the cooldown timer down

			//This is where you play the reload sound (there would be a bug if gunCD happened to reach exactly 0 then the reload sound wouldn't play
			//But it is unlikely
			if(this.gunCD == 0){
				this.gunCD = -1;//This way you won't get a 1/delta bug where the reload sound won't play
			}

			if(this.reloadCD < 0){
				this.reloadCD = 0;//Just set it to 0 for simplicity's sake.
			}

			if(this.gunCD < 0){
				//Play the reload sound here!!
				this.reloadSound.play();
				this.reloadCD = this.reloadMaxCD;//Put it on reload cooldown
				this.gunCD = 0;//Set it to 0 so the game knows not to play the reload sound again.

			}
		}

        if (this.y != this.floorY) {//If the player is not on the floor, gravity accelerates them downward
            this.velY += this.gravity * dt;
        }

        this.y += this.velY * dt;//Move based on the current x and y velocities
        this.x += this.velX * dt;

        if (this.y > this.floorY) {
            if (!this.hit) {
                this.charSprite.changeAnim(0);
            }
            this.y = this.floorY;
            this.velY = 0;
        }

        this.charSprite.update(dt);
        this.gunSprite.update(dt);

        if (!this.bloodSprite.anims[0].complete) {
            this.bloodSprite.update(dt);
        }

        if(!this.gunSprite.anims[0].complete) {
            this.gunSprite.update(dt);
        } else {
            this.gunSprite.anims[0].frame = 0;
        }
    },

    setTimer: function(time)
    {
        this.maxDrawTimer = time;
        this.waitingForDraw = true;
    },

    jump: function()
    {
        if(!this.hit && this.y===this.floorY){//If you're on the ground
            this.velY = this.jumpMagnitude;//
            this.charSprite.changeAnim(2);
        }

    },

    duck: function()
    {
    },

    shoot: function(enemy)
    {
		this.gunShotSound.play();
		var shot = new Shot(this.x, this.y + (this.h / 2), this.angle, enemy);
		this.gunCD = this.gunMaxCD;

        this.gunSprite.anims[0].complete = false;
        this.gunSprite.anims[0].frame = 0;

		return shot;
    },

	reset: function(){
        this.waitingForDraw = true;
        this.drawTimer      = 0;
        this.maxDrawTimer   = 0;

        this.angle         = -1;
        this.da            = 0;

        this.hit           = false;

        this.charSprite.anims[3].complete = false;
        this.charSprite.anims[3].frame = 0;
        this.charSprite.changeAnim(0);
	},

    setFloor: function(y)
    {
        this.y      = y - (this.h);
        this.floorY = this.y;
    },

    giveResources: function(resources)
    {
        this.bloodSprite = resources.sprBlood.clone();
    },

    setChar: function(c)
    {
        this.charSprite = c;

        this.w = 2 * this.charSprite.w;
        this.h = 2 * this.charSprite.h;

        //adjust the y position so that sprites of all dimensions are properly aligned to the floor
        this.y -= this.h;
        this.floorY = this.y;
    },

    setGun: function(g)
    {
        this.gunSprite = g;
    },

    kill: function(colY)
    {
		this.wilhelmScream.play();
        this.colY = colY;
        this.bloodSprite.anims[0].complete = false;
        this.bloodSprite.anims[0].frame = 0;
        this.hit = true;

        this.charSprite.changeAnim(3);
    },

    draw: function(canvas)
    {
        if (this.reverse) {
            canvas.scale(-1,1);
            this.x = -this.x;
        }

        if (!this.hit) {
            canvas.translate(this.x + this.w - 12, this.y + (this.h / 2) - 8);
            canvas.rotate(-this.angle);
            this.gunSprite.draw(canvas, 0, 0);
            canvas.rotate(this.angle);
            canvas.translate(-(this.x + this.w - 12), -(this.y + (this.h / 2) - 8));
        }

        this.charSprite.draw(canvas, this.x, this.y);

        if (!this.bloodSprite.anims[0].complete) {
            this.bloodSprite.draw(canvas, this.x + (0.7 * this.w), this.y + (this.h - this.colY) - 6);
        }

        if (this.reverse) {
            canvas.scale(-1,1);
            this.x = -this.x;
        }
    },

	setEnemy: function(enemy){
		this.enemy = enemy;
	},

	canShoot: function(){
		if(this.waitingForDraw || this.hit){
			return false;
		}

		if(this.gunCD <= 0 && this.reloadCD <= 0){
			return true;
		}

		//otherwise
		return false;

	}
}
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import TestRenderer from 'react-test-renderer';

import * as nonce from '../utils/nonce';
import { resetStyled, expectCSSMatches } from './utils';
import StyleSheet from '../models/StyleSheet';

jest.mock('../utils/nonce');
jest.spyOn(nonce, 'default').mockImplementation(() => 'foo');

let styled;

describe('with styles', () => {
  /**
   * Make sure the setup is the same for every test
   */
  beforeEach(() => {
    // $FlowFixMe
    document.head.innerHTML = '';
    styled = resetStyled();
  });

  it('should append a style', () => {
    const rule = 'color: blue;';
    const Comp = styled.div`
      ${rule};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { color:blue; }');
  });

  it('should append multiple styles', () => {
    const rule1 = 'color: blue;';
    const rule2 = 'background: red;';
    const Comp = styled.div`
      ${rule1} ${rule2};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { color:blue; background:red; }');
  });

  it('amperstand should refer to the static class when making a self-referential combo selector', () => {
    const Comp = styled.div`
      background: red;
      color: ${p => p.color};

      &[disabled] {
        color: red;
      }

      & + & {
        margin-left: 4px;
      }

      & ~ & {
        margin-right: 4px;
      }

      & > & {
        margin-top: 4px;
      }

      .foo & {
        color: silver;
      }
    `;
    TestRenderer.create(
      <React.Fragment>
        <Comp color="white" />
        <Comp color="red" />
      </React.Fragment>
    );
    expectCSSMatches(
      '.sc-a{ } .b{ background:red; color:white; } .b[disabled]{ color:red; } .b + .sc-a{ margin-left:4px; } .b ~ .sc-a{ margin-right:4px; } .b > .sc-a{ margin-top:4px; } .foo .b{ color:silver; } .c{ background:red; color:red; } .c[disabled]{ color:red; } .c + .sc-a{ margin-left:4px; } .c ~ .sc-a{ margin-right:4px; } .c > .sc-a{ margin-top:4px; } .foo .c{ color:silver; }'
    );
  });

  it('should handle inline style objects', () => {
    const rule1 = {
      backgroundColor: 'blue',
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; }');
  });

  it('should handle inline style objects with media queries', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '@media screen and (min-width: 250px)': {
        backgroundColor: 'red',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches(
      '.sc-a {} .b { background-color:blue; } @media screen and (min-width:250px) { .b { background-color:red; } }'
    );
  });

  it('should handle inline style objects with pseudo selectors', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '&:hover': {
        color: 'green',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } .b:hover { color:green; }');
  });

  it('should handle inline style objects with pseudo selectors', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '&:hover': {
        color: 'green',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } .b:hover { color:green; }');
  });

  it('should handle inline style objects with nesting', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '> h1': {
        color: 'white',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } .b > h1 { color:white; }');
  });

  it('should handle inline style objects with contextual selectors', () => {
    const rule1 = {
      backgroundColor: 'blue',
      'html.something &': {
        color: 'white',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } html.something .b { color:white; }');
  });

  it('should inject styles of multiple components', () => {
    const firstRule = 'background: blue;';
    const secondRule = 'background: red;';
    const FirstComp = styled.div`
      ${firstRule};
    `;
    const SecondComp = styled.div`
      ${secondRule};
    `;

    TestRenderer.create(<FirstComp />);
    TestRenderer.create(<SecondComp />);

    expectCSSMatches('.sc-a {} .c { background:blue; } .sc-b {} .d { background:red; }');
  });

  it('should inject styles of multiple components based on creation, not rendering order', () => {
    const firstRule = 'content: "first rule";';
    const secondRule = 'content: "second rule";';
    const FirstComp = styled.div`
      ${firstRule};
    `;
    const SecondComp = styled.div`
      ${secondRule};
    `;

    // Switch rendering order, shouldn't change injection order
    TestRenderer.create(<SecondComp />);
    TestRenderer.create(<FirstComp />);

    // Classes _do_ get generated in the order of rendering but that's ok
    expectCSSMatches(`
        .sc-a {}
        .d { content:"first rule"; }
        .sc-b {}
        .c { content:"second rule"; }
      `);
  });

  it('should strip a JS-style (invalid) comment in the styles', () => {
    const comment = '// This is an invalid comment';
    const rule = 'color: blue;';
    // prettier-ignore
    const Comp = styled.div`
      ${comment}
      ${rule}
    `
    TestRenderer.create(<Comp />);
    expectCSSMatches(`
        .sc-a {}
        .b {
          color:blue;
        }
      `);
  });

  it('should respect removed rules', () => {
    const Heading = styled.h1`
      color: red;
    `;
    const Text = styled.span`
      color: green;
    `;

    TestRenderer.create(
      <Heading>
        <Text />
      </Heading>
    );
    StyleSheet.master.remove(Text.styledComponentId);

    expectCSSMatches(`
        .sc-a {}
        .c {
          color:red;
        }
      `);
  });

  it('should add a webpack nonce to the style tags if one is available in the global scope', () => {
    const rule = 'color: blue;';
    const Comp = styled.div`
      ${rule};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches(`
        .sc-a {}
        .b {
          color:blue;
        }
      `);

    Array.from(document.querySelectorAll('style')).forEach(el => {
      expect(el.getAttribute('nonce')).toBe('foo');
    });
  });

  it('should handle deferredInject and inject correctly', () => {
    const cloneA = StyleSheet.master.clone();
    const cloneB = StyleSheet.master.clone();
    const rules = ['.testA {}'];

    StyleSheet.master.deferredInject('test', rules);

    expect(StyleSheet.master.deferred.test).toBe(rules);
    expect(cloneA.deferred.test).toBe(rules);
    expect(cloneB.deferred.test).toBe(rules);

    StyleSheet.master.inject('test', ['.testB {}']);

    const inspectTag = sheet => {
      const tag = sheet.getTagForId('test');
      return tag.css();
    };

    const masterCss = inspectTag(StyleSheet.master);

    expect(masterCss).toEqual(inspectTag(cloneA));
    expect(masterCss).toEqual(inspectTag(cloneB));
  });
});
<commit_msg>easier to read<commit_after>// @flow
import React from 'react';
import TestRenderer from 'react-test-renderer';

import * as nonce from '../utils/nonce';
import { resetStyled, expectCSSMatches } from './utils';
import StyleSheet from '../models/StyleSheet';

jest.mock('../utils/nonce');
jest.spyOn(nonce, 'default').mockImplementation(() => 'foo');

let styled;

describe('with styles', () => {
  /**
   * Make sure the setup is the same for every test
   */
  beforeEach(() => {
    // $FlowFixMe
    document.head.innerHTML = '';
    styled = resetStyled();
  });

  it('should append a style', () => {
    const rule = 'color: blue;';
    const Comp = styled.div`
      ${rule};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { color:blue; }');
  });

  it('should append multiple styles', () => {
    const rule1 = 'color: blue;';
    const rule2 = 'background: red;';
    const Comp = styled.div`
      ${rule1} ${rule2};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { color:blue; background:red; }');
  });

  it('amperstand should refer to the static class when making a self-referential combo selector', () => {
    const Comp = styled.div`
      background: red;
      color: ${p => p.color};

      &[disabled] {
        color: red;
      }

      & + & {
        margin-left: 4px;
      }

      & ~ & {
        margin-right: 4px;
      }

      & > & {
        margin-top: 4px;
      }

      .foo & {
        color: silver;
      }
    `;
    TestRenderer.create(
      <React.Fragment>
        <Comp color="white" />
        <Comp color="red" />
      </React.Fragment>
    );
    expectCSSMatches(`
      .sc-a{ }
      .b{ background:red; color:white; }
      .b[disabled]{ color:red; }
      .b + .sc-a{ margin-left:4px; }
      .b ~ .sc-a{ margin-right:4px; }
      .b > .sc-a{ margin-top:4px; }
      .foo .b{ color:silver; }
      .c{ background:red; color:red; }
      .c[disabled]{ color:red; }
      .c + .sc-a{ margin-left:4px; }
      .c ~ .sc-a{ margin-right:4px; }
      .c > .sc-a{ margin-top:4px; }
      .foo .c{ color:silver; }
    `);
  });

  it('should handle inline style objects', () => {
    const rule1 = {
      backgroundColor: 'blue',
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; }');
  });

  it('should handle inline style objects with media queries', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '@media screen and (min-width: 250px)': {
        backgroundColor: 'red',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches(
      '.sc-a {} .b { background-color:blue; } @media screen and (min-width:250px) { .b { background-color:red; } }'
    );
  });

  it('should handle inline style objects with pseudo selectors', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '&:hover': {
        color: 'green',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } .b:hover { color:green; }');
  });

  it('should handle inline style objects with pseudo selectors', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '&:hover': {
        color: 'green',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } .b:hover { color:green; }');
  });

  it('should handle inline style objects with nesting', () => {
    const rule1 = {
      backgroundColor: 'blue',
      '> h1': {
        color: 'white',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } .b > h1 { color:white; }');
  });

  it('should handle inline style objects with contextual selectors', () => {
    const rule1 = {
      backgroundColor: 'blue',
      'html.something &': {
        color: 'white',
      },
    };
    const Comp = styled.div`
      ${rule1};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches('.sc-a {} .b { background-color:blue; } html.something .b { color:white; }');
  });

  it('should inject styles of multiple components', () => {
    const firstRule = 'background: blue;';
    const secondRule = 'background: red;';
    const FirstComp = styled.div`
      ${firstRule};
    `;
    const SecondComp = styled.div`
      ${secondRule};
    `;

    TestRenderer.create(<FirstComp />);
    TestRenderer.create(<SecondComp />);

    expectCSSMatches('.sc-a {} .c { background:blue; } .sc-b {} .d { background:red; }');
  });

  it('should inject styles of multiple components based on creation, not rendering order', () => {
    const firstRule = 'content: "first rule";';
    const secondRule = 'content: "second rule";';
    const FirstComp = styled.div`
      ${firstRule};
    `;
    const SecondComp = styled.div`
      ${secondRule};
    `;

    // Switch rendering order, shouldn't change injection order
    TestRenderer.create(<SecondComp />);
    TestRenderer.create(<FirstComp />);

    // Classes _do_ get generated in the order of rendering but that's ok
    expectCSSMatches(`
        .sc-a {}
        .d { content:"first rule"; }
        .sc-b {}
        .c { content:"second rule"; }
      `);
  });

  it('should strip a JS-style (invalid) comment in the styles', () => {
    const comment = '// This is an invalid comment';
    const rule = 'color: blue;';
    // prettier-ignore
    const Comp = styled.div`
      ${comment}
      ${rule}
    `
    TestRenderer.create(<Comp />);
    expectCSSMatches(`
        .sc-a {}
        .b {
          color:blue;
        }
      `);
  });

  it('should respect removed rules', () => {
    const Heading = styled.h1`
      color: red;
    `;
    const Text = styled.span`
      color: green;
    `;

    TestRenderer.create(
      <Heading>
        <Text />
      </Heading>
    );
    StyleSheet.master.remove(Text.styledComponentId);

    expectCSSMatches(`
        .sc-a {}
        .c {
          color:red;
        }
      `);
  });

  it('should add a webpack nonce to the style tags if one is available in the global scope', () => {
    const rule = 'color: blue;';
    const Comp = styled.div`
      ${rule};
    `;
    TestRenderer.create(<Comp />);
    expectCSSMatches(`
        .sc-a {}
        .b {
          color:blue;
        }
      `);

    Array.from(document.querySelectorAll('style')).forEach(el => {
      expect(el.getAttribute('nonce')).toBe('foo');
    });
  });

  it('should handle deferredInject and inject correctly', () => {
    const cloneA = StyleSheet.master.clone();
    const cloneB = StyleSheet.master.clone();
    const rules = ['.testA {}'];

    StyleSheet.master.deferredInject('test', rules);

    expect(StyleSheet.master.deferred.test).toBe(rules);
    expect(cloneA.deferred.test).toBe(rules);
    expect(cloneB.deferred.test).toBe(rules);

    StyleSheet.master.inject('test', ['.testB {}']);

    const inspectTag = sheet => {
      const tag = sheet.getTagForId('test');
      return tag.css();
    };

    const masterCss = inspectTag(StyleSheet.master);

    expect(masterCss).toEqual(inspectTag(cloneA));
    expect(masterCss).toEqual(inspectTag(cloneB));
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

//Helper Objects
var users = require('./users');

//Storm DRPC
var NodeDRPCClient = require('node-drpc');
var nodeDrpcClient =  new  NodeDRPCClient( process.env.DRPC_SERVER_HOST,  parseInt(process.env.DRPC_SERVER_PORT, 10) );

//Kafka
var kafka = require('kafka-node'),
    Producer = kafka.Producer,
    client = new kafka.Client(process.env.KAFKA_ZK_HOST),
    producer = new Producer(client);

var topic_name_crawler = process.env.KAFKA_TOPIC_CRAWL;
var crawl_depth =  process.env.CRAWL_DEFAULT_DEPTH;

producer.on('ready', function () {
  console.log('Kafka Producer Ready');
});

producer.on('error', function (err) {
  console.log('Error:' + err);
});

//App
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

//API Routes
app.use('/api',function(req, res, next){
  console.log('Authenticating API Request...');
  var userid = req.body.userid;

  // userid isn't present
  if (!userid) return next(error(400, 'api userid required'));

  // key is invalid
  if (!~users[userid]) return next(error(401, 'invalid user'));

  // all good, store req.key for route access
  next();
});

app.post('/api/event', function(req, res, next){
  console.log('/api/event: Looking for POST data...');
  //Get event from post data
  var event = new Object();
  event.userid = req.body.userid;
  event.type = req.body.type;
  event.uri = req.body.uri;
  event.summary = req.body.summary;
  event.task = req.body.task;
  event.timestamp = req.body.timestamp;

  var payload_crawler = [{topic:topic_name_crawler , messages:event.uri+' '+crawl_depth+' '+event.task+' '+event.userid}];

  console.log('Sending to kafka...');
  //Send to Kafka
  if(producer) {
    producer.send(payload_crawler, function (err, data) {
      if (err) {
        res.send(500, err);
      } else {
        res.send(200, 'Message is queued.');
      }
    });
  } else {
    res.send(500, 'Unable to send to Kafka Producer');
  }
});

//DRPC Search Route
app.post('/api/search', function(req, res, next){
  console.log('/api/search: Looking for POST data...');

  var userid = req.body.userid;
  var searchQuery = req.body.searchQuery;
  var taskName =  req.body.taskName;

  nodeDrpcClient.execute("search", searchQuery+' '+taskName, function(err, response) {//DRPC func_name, func_args, callback
    if (err) {
      console.error(err);
    } else {
      console.log("Storm DRPC Success");

      var searchResultArray = [];
      var jsonResponse = JSON.parse(response);
      for(var i = 0; i < jsonResponse.length; i++) {
        var curResponse = jsonResponse[i];
        var curSearchResult = curResponse[curResponse.length -1];
        searchResultArray.push(curSearchResult)

        console.log("curResponse"+ i + " : "+JSON.stringify(curResponse));
      }

      console.log("searchResultArray"+ JSON.stringify(searchResultArray));
      res.render('search_result', {searchResult: searchResultArray}, function(err, html) {
        res.send(200, JSON.stringify(searchResultArray));
      })
    }
  });

});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>Search Result UI<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

//Helper Objects
var users = require('./users');

//Storm DRPC
var NodeDRPCClient = require('node-drpc');
var nodeDrpcClient =  new  NodeDRPCClient( process.env.DRPC_SERVER_HOST,  parseInt(process.env.DRPC_SERVER_PORT, 10) );

//Kafka
var kafka = require('kafka-node'),
    Producer = kafka.Producer,
    client = new kafka.Client(process.env.KAFKA_ZK_HOST),
    producer = new Producer(client);

var topic_name_crawler = process.env.KAFKA_TOPIC_CRAWL;
var crawl_depth =  process.env.CRAWL_DEFAULT_DEPTH;

producer.on('ready', function () {
  console.log('Kafka Producer Ready');
});

producer.on('error', function (err) {
  console.log('Error:' + err);
});

//App
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

//API Routes
app.use('/api',function(req, res, next){
  console.log('Authenticating API Request...');
  var userid = req.body.userid;

  // userid isn't present
  if (!userid) return next(error(400, 'api userid required'));

  // key is invalid
  if (!~users[userid]) return next(error(401, 'invalid user'));

  // all good, store req.key for route access
  next();
});

app.post('/api/event', function(req, res, next){
  console.log('/api/event: Looking for POST data...');
  //Get event from post data
  var event = new Object();
  event.userid = req.body.userid;
  event.type = req.body.type;
  event.uri = req.body.uri;
  event.summary = req.body.summary;
  event.task = req.body.task;
  event.timestamp = req.body.timestamp;

  var payload_crawler = [{topic:topic_name_crawler , messages:event.uri+' '+crawl_depth+' '+event.task+' '+event.userid}];

  console.log('Sending to kafka...');
  //Send to Kafka
  if(producer) {
    producer.send(payload_crawler, function (err, data) {
      if (err) {
        res.send(500, err);
      } else {
        res.send(200, 'Message is queued.');
      }
    });
  } else {
    res.send(500, 'Unable to send to Kafka Producer');
  }
});

//DRPC Search Route
app.post('/api/search', function(req, res, next){
  console.log('/api/search: Looking for POST data...');

  var userid = req.body.userid;
  var searchQuery = req.body.searchQuery;
  var taskName =  req.body.taskName;

  nodeDrpcClient.execute("search", searchQuery+' '+taskName, function(err, response) {//DRPC func_name, func_args, callback
    if (err) {
      console.error(err);
    } else {
      console.log("Storm DRPC Success");

      var searchResultArray = [];
      var jsonResponse = JSON.parse(response);
      for(var i = 0; i < jsonResponse.length; i++) {
        var curResponse = jsonResponse[i];
        var curSearchResult = curResponse[curResponse.length -1];
        searchResultArray.push(curSearchResult)

        console.log("curResponse"+ i + " : "+JSON.stringify(curResponse));
      }

      console.log("searchResultArray"+ JSON.stringify(searchResultArray));
      res.render('search_result', {searchResult: searchResultArray});
      /*res.render('search_result', {searchResult: searchResultArray}, function(err, html) {
        res.send(200, JSON.stringify(searchResultArray));
      })*/
    }
  });

});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before><commit_msg>Replace sys.puts with process.stdout.write<commit_after><|endoftext|>


<commit_before><commit_msg>Extending example.js<commit_after><|endoftext|>


<commit_before>describe('The Module Loader', function () {
   'use strict';
   afterEach(function () {
      moduleSystem.reset();
   });

   it('should load any Module found in dom', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var spyModule = jasmine.createSpy('creator');
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalled();
      expect(spyModule.calls.argsFor(0)[0]).toEqual($('#test-testModule'));
   });

   it('should not load a Module if not found in dom', function () {
      var spyModule = jasmine.createSpy('creator');
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).not.toHaveBeenCalled();
   });

   it('should provide a settings object to the module if specified', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var settings = {
         testSetting: 'test'
      };

      var spyModule = jasmine.createSpy('creator').and.returnValue({});
      moduleSystem.createModule('testModule')
         .settings(settings)
         .creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), settings);

   });

   it('should provide a settings object to the module if settings found in DOM', function () {
      loadFixtures('moduleSystem/oneModuleWithSettings.html');

      var spyModule = jasmine.createSpy('creator').and.returnValue({});
      moduleSystem.createModule('testModule')
         .creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), {
         testOverrideSetting: 12
      });

   });

   it('should override the specified settings with the settings found in DOM', function () {
      loadFixtures('moduleSystem/oneModuleWithSettings.html');
      var settings = {
         testOverrideSetting: 'test',
         otherSetting: 'setting'
      };

      var spyModule = jasmine.createSpy('creator').and.returnValue({});
      moduleSystem.createModule('testModule')
         .settings(settings)
         .creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), {
         testOverrideSetting: 12,
         otherSetting: settings.otherSetting
      });

   });

   it('should set the name of a module to its moduleObj', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var moduleObj = {};
      var spyModule = jasmine.createSpy('creator').and.returnValue(moduleObj);
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(moduleObj.name).toBe('testModule0');
   });

   it('should create a module for every module in dom', function () {
      loadFixtures('moduleSystem/twoIdenticalModules.html');
      var spyModule = jasmine.createSpy('creator');
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule.calls.count()).toBe(2);
      expect(spyModule.calls.argsFor(0)[0]).toEqual($('#test-testModule1'));
      expect(spyModule.calls.argsFor(1)[0]).toEqual($('#test-testModule2'));
   });

   it('should set incrementing name of a module to its moduleObj', function () {
      loadFixtures('moduleSystem/twoIdenticalModules.html');
      var moduleObj = {};
      var spyModule = jasmine.createSpy('creator').and.returnValue(moduleObj);
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(moduleObj.name).toBe('testModule1');
   });

   it('should Throw if a Module in the dom is not registered', function () {
      loadFixtures('moduleSystem/oneModule.html');

      expect(moduleSystem.initModulePage).toThrow();
   });

   describe('with parts', function () {
      var spyModule;

      it('should get a part', function () {
         var spyPart = jasmine.createSpy('creator');
         moduleSystem.createPart('testPart').creator(function () {
            return spyPart;
         });

         expect(moduleSystem.getPart('testPart')).toEqual(spyPart);
      });

      it('should provide a settings object to the part if specified', function () {
         var settings = {
            testSetting: 'test'
         };

         var spyPart = jasmine.createSpy('creator').and.returnValue({});
         moduleSystem.createPart('testPart')
            .settings(settings)
            .creator(spyPart);

         moduleSystem.getPart('testPart');

         expect(spyPart).toHaveBeenCalledWith(settings);
      });

      it('should add missing Parts to Parts', function () {
         var testPart = jasmine.createSpy('test part');
         var publicMethodObject = {
            testProperty: 'test'
         };
         moduleSystem.createPart('dependencyPart').creator(function () {
            return publicMethodObject;
         });
         moduleSystem.createPart('testPart').dependencies(['dependencyPart']).creator(testPart);

         moduleSystem.getPart('testPart');

         expect(testPart).toHaveBeenCalledWith(publicMethodObject);
      });

      it('should throw an exception if a part dependencie couldnt be resolved', function () {
         var spyPart = jasmine.createSpy();
         moduleSystem.createPart('testPart').dependencies(['dependencyPart']).creator(spyPart);

         expect(function () {
            moduleSystem.getPart('testPart')
         }).toThrow();
      });

      it('should throw an exception on circular dependencies', function () {
         var spyPart = jasmine.createSpy();
         moduleSystem.createPart('testPart').dependencies(['dependencyPart']).creator(spyPart);
         moduleSystem.createPart('dependencyPart').dependencies(['testPart']).creator(spyPart);

         expect(function () {
            moduleSystem.getPart('testPart')
         }).toThrow();
      });

      describe('with dependencie from module', function () {
         beforeEach(function () {
            loadFixtures('moduleSystem/oneModule.html');
            spyModule = jasmine.createSpy('module');

            moduleSystem.createModule('testModule').dependencies(['testPart']).creator(spyModule);
         });

         it('should load any needed Part', function () {
            var spyPart = jasmine.createSpy('creator');
            moduleSystem.createPart('testPart').creator(spyPart);

            moduleSystem.initModulePage();

            expect(spyPart).toHaveBeenCalled();
         });

         it('should not load any part which is not needed', function () {
            moduleSystem.createPart('testPart').creator(function () {});
            var spyPart = jasmine.createSpy('creator');
            moduleSystem.createPart('testPart2').creator(spyPart);

            moduleSystem.initModulePage();

            expect(spyPart).not.toHaveBeenCalled();
         });

         it('should add missing parts to the module', function () {
            var publicMethodObject = {
               testProperty: 'test'
            };
            moduleSystem.createPart('testPart').creator(function () {
               return publicMethodObject;
            });

            moduleSystem.initModulePage();

            expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), publicMethodObject);
         });

         it('should call postConstruct from parts when provision is finished', function () {
            var spyPartObject = jasmine.createSpyObj('part object', ['postConstruct']);

            var initWasCalled = false;

            spyPartObject.postConstruct.and.callFake(function () {
               expect(initWasCalled).toEqual(true);
            });

            var spyPart = jasmine.createSpy('spyPart').and.callFake(function () {
               initWasCalled = true;
               return spyPartObject;
            });

            moduleSystem.createPart('testPart').creator(spyPart);

            moduleSystem.initModulePage();

            expect(spyPartObject.postConstruct).toHaveBeenCalled();
         });

      });

   });

   it('should throw an exception if a module dependencie couldnt be resolved', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var spyModule = jasmine.createSpy();
      moduleSystem.createModule('testModule').dependencies(['dependencyPart']).creator(spyModule);

      expect(moduleSystem.initModulePage).toThrow();
   });

   it('should add every module to the event bus', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var eventBus = moduleSystem.getPart('eventBus');

      eventBus.add = jasmine.createSpy('add').and.callThrough();

      var publicMethodObject = {
         testProperty: 'test'
      };
      moduleSystem.createModule('testModule').creator(function () {
         return publicMethodObject;
      });

      moduleSystem.initModulePage();

      expect(eventBus.add).toHaveBeenCalledWith({
         name: 'testModule0',
         testProperty: 'test'
      });
   });

   it('should call postConstruct when provision is finished', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var spyModuleObject = jasmine.createSpyObj('module object', ['postConstruct']);
      var initWasCalled = false;

      spyModuleObject.postConstruct.and.callFake(function () {
         expect(initWasCalled).toEqual(true);
      });

      var spyModule = jasmine.createSpy('spyModule').and.callFake(function () {
         initWasCalled = true;
         return spyModuleObject;
      });

      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModuleObject.postConstruct).toHaveBeenCalled();
   });

});<commit_msg>add test for reinitialization<commit_after>describe('The Module Loader', function () {
   'use strict';
   afterEach(function () {
      moduleSystem.reset();
   });

   it('should load any Module found in dom', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var spyModule = jasmine.createSpy('creator');
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalled();
      expect(spyModule.calls.argsFor(0)[0]).toEqual($('#test-testModule'));
   });

   it('should not load a Module if not found in dom', function () {
      var spyModule = jasmine.createSpy('creator');
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).not.toHaveBeenCalled();
   });

   it('should provide a settings object to the module if specified', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var settings = {
         testSetting: 'test'
      };

      var spyModule = jasmine.createSpy('creator').and.returnValue({});
      moduleSystem.createModule('testModule')
         .settings(settings)
         .creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), settings);

   });

   it('should provide a settings object to the module if settings found in DOM', function () {
      loadFixtures('moduleSystem/oneModuleWithSettings.html');

      var spyModule = jasmine.createSpy('creator').and.returnValue({});
      moduleSystem.createModule('testModule')
         .creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), {
         testOverrideSetting: 12
      });

   });

   it('should override the specified settings with the settings found in DOM', function () {
      loadFixtures('moduleSystem/oneModuleWithSettings.html');
      var settings = {
         testOverrideSetting: 'test',
         otherSetting: 'setting'
      };

      var spyModule = jasmine.createSpy('creator').and.returnValue({});
      moduleSystem.createModule('testModule')
         .settings(settings)
         .creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), {
         testOverrideSetting: 12,
         otherSetting: settings.otherSetting
      });

   });

   it('should set the name of a module to its moduleObj', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var moduleObj = {};
      var spyModule = jasmine.createSpy('creator').and.returnValue(moduleObj);
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(moduleObj.name).toBe('testModule0');
   });

   it('should create a module for every module in dom', function () {
      loadFixtures('moduleSystem/twoIdenticalModules.html');
      var spyModule = jasmine.createSpy('creator');
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModule.calls.count()).toBe(2);
      expect(spyModule.calls.argsFor(0)[0]).toEqual($('#test-testModule1'));
      expect(spyModule.calls.argsFor(1)[0]).toEqual($('#test-testModule2'));
   });

   it('should set incrementing name of a module to its moduleObj', function () {
      loadFixtures('moduleSystem/twoIdenticalModules.html');
      var moduleObj = {};
      var spyModule = jasmine.createSpy('creator').and.returnValue(moduleObj);
      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(moduleObj.name).toBe('testModule1');
   });

   it('should Throw if a Module in the dom is not registered', function () {
      loadFixtures('moduleSystem/oneModule.html');

      expect(moduleSystem.initModulePage).toThrow();
   });

   describe('with parts', function () {
      var spyModule;

      it('should get a part', function () {
         var partObj = {
            test: 'test'
         };
         var spyPart = jasmine.createSpy('creator').and.returnValue(partObj);
         moduleSystem.createPart('testPart').creator(spyPart);

         expect(moduleSystem.getPart('testPart')).toEqual(partObj);
      });

      it('should not reinitilize part if allready initialized', function () {
         var partObj = {
            test: 'test'
         };
         var spyPart = jasmine.createSpy('creator').and.returnValue(partObj);
         moduleSystem.createPart('testPart').creator(spyPart);

         moduleSystem.getPart('testPart');
         var partObjActual = moduleSystem.getPart('testPart');

         expect(partObj).toEqual(partObjActual);
         expect(spyPart.calls.count()).toEqual(1);

      });

      it('should provide a settings object to the part if specified', function () {
         var settings = {
            testSetting: 'test'
         };

         var spyPart = jasmine.createSpy('creator').and.returnValue({});
         moduleSystem.createPart('testPart')
            .settings(settings)
            .creator(spyPart);

         moduleSystem.getPart('testPart');

         expect(spyPart).toHaveBeenCalledWith(settings);
      });

      it('should add missing Parts to Parts', function () {
         var testPart = jasmine.createSpy('test part');
         var publicMethodObject = {
            testProperty: 'test'
         };
         moduleSystem.createPart('dependencyPart').creator(function () {
            return publicMethodObject;
         });
         moduleSystem.createPart('testPart').dependencies(['dependencyPart']).creator(testPart);

         moduleSystem.getPart('testPart');

         expect(testPart).toHaveBeenCalledWith(publicMethodObject);
      });

      it('should throw an exception if a part dependencie couldnt be resolved', function () {
         var spyPart = jasmine.createSpy();
         moduleSystem.createPart('testPart').dependencies(['dependencyPart']).creator(spyPart);

         expect(function () {
            moduleSystem.getPart('testPart')
         }).toThrow();
      });

      it('should throw an exception on circular dependencies', function () {
         var spyPart = jasmine.createSpy();
         moduleSystem.createPart('testPart').dependencies(['dependencyPart']).creator(spyPart);
         moduleSystem.createPart('dependencyPart').dependencies(['testPart']).creator(spyPart);

         expect(function () {
            moduleSystem.getPart('testPart')
         }).toThrow();
      });

      describe('with dependencie from module', function () {
         beforeEach(function () {
            loadFixtures('moduleSystem/oneModule.html');
            spyModule = jasmine.createSpy('module');

            moduleSystem.createModule('testModule').dependencies(['testPart']).creator(spyModule);
         });

         it('should load any needed Part', function () {
            var spyPart = jasmine.createSpy('creator');
            moduleSystem.createPart('testPart').creator(spyPart);

            moduleSystem.initModulePage();

            expect(spyPart).toHaveBeenCalled();
         });

         it('should not load any part which is not needed', function () {
            moduleSystem.createPart('testPart').creator(function () {});
            var spyPart = jasmine.createSpy('creator');
            moduleSystem.createPart('testPart2').creator(spyPart);

            moduleSystem.initModulePage();

            expect(spyPart).not.toHaveBeenCalled();
         });

         it('should add missing parts to the module', function () {
            var publicMethodObject = {
               testProperty: 'test'
            };
            moduleSystem.createPart('testPart').creator(function () {
               return publicMethodObject;
            });

            moduleSystem.initModulePage();

            expect(spyModule).toHaveBeenCalledWith(jasmine.any(Object), publicMethodObject);
         });

         it('should call postConstruct from parts when provision is finished', function () {
            var spyPartObject = jasmine.createSpyObj('part object', ['postConstruct']);

            var initWasCalled = false;

            spyPartObject.postConstruct.and.callFake(function () {
               expect(initWasCalled).toEqual(true);
            });

            var spyPart = jasmine.createSpy('spyPart').and.callFake(function () {
               initWasCalled = true;
               return spyPartObject;
            });

            moduleSystem.createPart('testPart').creator(spyPart);

            moduleSystem.initModulePage();

            expect(spyPartObject.postConstruct).toHaveBeenCalled();
         });

      });

   });

   it('should throw an exception if a module dependencie couldnt be resolved', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var spyModule = jasmine.createSpy();
      moduleSystem.createModule('testModule').dependencies(['dependencyPart']).creator(spyModule);

      expect(moduleSystem.initModulePage).toThrow();
   });

   it('should add every module to the event bus', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var eventBus = moduleSystem.getPart('eventBus');

      eventBus.add = jasmine.createSpy('add').and.callThrough();

      var publicMethodObject = {
         testProperty: 'test'
      };
      moduleSystem.createModule('testModule').creator(function () {
         return publicMethodObject;
      });

      moduleSystem.initModulePage();

      expect(eventBus.add).toHaveBeenCalledWith({
         name: 'testModule0',
         testProperty: 'test'
      });
   });

   it('should call postConstruct when provision is finished', function () {
      loadFixtures('moduleSystem/oneModule.html');
      var spyModuleObject = jasmine.createSpyObj('module object', ['postConstruct']);
      var initWasCalled = false;

      spyModuleObject.postConstruct.and.callFake(function () {
         expect(initWasCalled).toEqual(true);
      });

      var spyModule = jasmine.createSpy('spyModule').and.callFake(function () {
         initWasCalled = true;
         return spyModuleObject;
      });

      moduleSystem.createModule('testModule').creator(spyModule);

      moduleSystem.initModulePage();

      expect(spyModuleObject.postConstruct).toHaveBeenCalled();
   });

});<|endoftext|>


<commit_before><commit_msg>emitterable<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';

export default class Dropdown extends Component {
  render() {
    return (

component

    );
  }
}

Dropdown.propTypes = {
  className: React.PropTypes.string,
};
<commit_msg>add jsx markup<commit_after>import React, { Component } from 'react';

export default class Dropdown extends Component {
  render() {
    return (

value

    );
  }
}

Dropdown.propTypes = {
  className: React.PropTypes.string,
};
<|endoftext|>


<commit_before>import React from 'react';
import Tooltip from 'src/Tooltip';

import Icon from 'src/Icon';
import anchored from 'src/mixins/anchored';

function TooltipBox({ children }) {
    return (

            {children}

    );
}

const AnchoredTooltip = anchored({ defaultPlacement: 'top', padding: 0 })(Tooltip);

class FooBox extends React.PureComponent {
    state = {
        show: false
    }

    componentDidMount() {
        setTimeout(() => this.setState({ show: true }), 500);
    }

    render() {
        return (

                 { this.spanRef = r; }}>
                    <Icon type="printer" />

                {this.state.show && <AnchoredTooltip anchor={this.spanRef} />}

        );
    }
}

function TooltipDoc() {
    return (

<Tooltip>

            <TooltipBox>
                <Tooltip>Tooltip</Tooltip>
            </TooltipBox>

            <TooltipBox>
                <Tooltip placement="bottom">Tooltip</Tooltip>
            </TooltipBox>

            <FooBox />

    );
}

export default TooltipDoc;
<commit_msg>Remove bad example of anchored tooltip, in favor of the on in <IconButton>.<commit_after>import React from 'react';
import Tooltip from 'src/Tooltip';

function TooltipBox({ children }) {
    return (

            {children}

    );
}

function TooltipDoc() {
    return (

<Tooltip>

            <TooltipBox>
                <Tooltip>Tooltip</Tooltip>
            </TooltipBox>

            <TooltipBox>
                <Tooltip placement="bottom">Tooltip</Tooltip>
            </TooltipBox>

    );
}

export default TooltipDoc;
<|endoftext|>


<commit_before>exports.module = {
    utils:require('../../../utils.js').utils,
    callback:null,
    query:null,
    postData:null,
    cookies:null,
    excute:function on(callback) {
        //可能存在另外一种写法是在外面对callback赋值，这里可以不传入，做判断的目的是为了兼容闭包样式的写法
        if (callback) { this.callback = callback; }

        if (!this.query['userid']) {
            exports.module.callback([],1004,'缺少必要参数');
            return;
        }

        var query_sql = 'SELECT * FROM nodejs_users WHERE user_id = "' + this.query['userid'] + '"';

        this.utils.excuteMySqlQuery(query_sql,function on(err,result){
            if (err) {
                console.log('[Mysql Error]please check querystring!');
                exports.module.callback([], 1010, '[Mysql Error]please check querystring!');
                return;
            }
            var responseModal = require('../../modals/responseModal.js').modal;
            responseModal.code = 0;
            responseModal.data = result;
            responseModal.errMsg = null;
            exports.module.callback(JSON.stringify(responseModal));
        });
    },
    //分割线，以上成员为module的必要成员，每个module都必须存在
};<commit_msg>demo bug fixed<commit_after>exports.module = {
    utils:require('../../../utils.js').utils,
    callback:null,
    query:null,
    postData:null,
    cookies:null,
    excute:function on(callback) {
        //可能存在另外一种写法是在外面对callback赋值，这里可以不传入，做判断的目的是为了兼容闭包样式的写法
        if (callback) { this.callback = callback; }

        if (!this.query['userid']) {
            exports.module.callback('',1004,'缺少必要参数');
            return;
        }

        var query_sql = 'SELECT * FROM nodejs_users WHERE user_id = "' + this.query['userid'] + '"';

        this.utils.excuteMySqlQuery(query_sql,function on(err,result){
            if (err) {
                console.log('[Mysql Error]please check querystring!');
                exports.module.callback([], 1010, '[Mysql Error]please check querystring!');
                return;
            }
            var responseModal = require('../../modals/responseModal.js').modal;
            responseModal.code = 0;
            responseModal.data = result;
            responseModal.errMsg = null;
            exports.module.callback(JSON.stringify(responseModal));
        });
    },
    //分割线，以上成员为module的必要成员，每个module都必须存在
};<|endoftext|>