<commit_before>"use strict";

var DBRow = require('./DBRow').DBRow;
var log = require('./log');
var generator = require('./IDGenerator');

const allowedUserKeys = ['id', 'username'];

exports.validateSession = function(cookie) {
	return new Promise(function(resolve, reject){
		if (cookie){ //first of all you need to have a cookie for us to expend resources
			var row = new DBRow("session");
			row.getRow(cookie.sessionID).then(function(row){
				resolve(); //allow user to continue

			}, function(err) {
				resolve(); //no session found, redirect user to login

			});
		}
		else
			reject();
	});
}

//TODO: check if previous session exists and use this session instead
// also TODO: figure out how the hell the SSL works with this because this first query will have to change
exports.loginAndCreateSession = function(postResult) {
	return new Promise(function(resolve, reject) {
		if (postResult) {
			var row = new DBRow("user");
			row.addQuery("netid", postResult.username)
			// row.addQuery("secret", postResult.secret) // BUT WE DON'T KNOW THE PASSWORD _/(O.O)\_

			row.query().then(function(result) {
				if (row.count() == 0){
					reject(false);
					return;
				}
				var date = new Date();

				row.next()
				var newSession = new DBRow("session");
				var sessionInfo = {sessionStart: date.toISOString().slice(0, date.toISOString().indexOf('T')),
									userID: row.getValue("id")};

				newSession.setValue('sessionStart', sessionInfo.sessionStart);
				newSession.setValue('userID', sessionInfo.userID);
				newSession.insert().then(function(res) {
					sessionInfo.sessionID = newSession.getValue('id')
					resolve(sessionInfo);
				}, function(res) {
					reject(false);
				});

			}, function(err){
				reject(false); // no matching user found - indicate failure
			});
		}
		else
			reject(false);
	})
}

exports.logout = function(cookie) {
	return new Promise(function(resolve, reject) {
		if(!cookie)
			reject(false);

		var row = new DBRow('session');
		row.delete(cookie.sessionID).then(function(res) {
			resolve(true);

		}, function(res) {
			reject(false);

		});
	});
}

exports.hasRole = function(userID, role) {
	return new Promise(function(resolve, reject) {
		if (!userID) {
			reject(false);
			return;
		}

		var user = new DBRow('user');
		user.getRow(userID).then(function(res) {
			if (user.count() == 0)
				reject(false);

			if(user.getValue('privilege').includes(role))
				resolve(true);
			else
				reject(false)

		}, function(res) {
			reject(false);
		});
	});
}

exports.validateUser = function(request) {
	return new Promise(function(resolve, reject) {

		var user = new DBRow('user');
		for (var key in request.query) {
			if (allowedUserKeys.includes(key)) // we do not allow searches for users by netid
				user.addQuery(key, request.query[key]);
		}

		user.query().then(function(res) {
			if (user.count() == 0)
				reject(false);
			else
				resolve(true);

		}, function(res) {
			reject(false);
		});
	});
}
<commit_msg>FIX: Validator bug<commit_after>"use strict";

var DBRow = require('./DBRow').DBRow;
var log = require('./log');
var generator = require('./IDGenerator');

const allowedUserKeys = ['id', 'username'];

exports.validateSession = function(cookie) {
	return new Promise(function(resolve, reject){
		if (cookie){ //first of all you need to have a cookie for us to expend resources
			var row = new DBRow("session");
			row.getRow(cookie.sessionID).then(function(row){
				resolve(); //allow user to continue

			}, function(err) {
				resolve(); //no session found, redirect user to login

			});
		}
		else
			reject();
	});
}

// TODO: figure out how the hell the SSO works with this because this first query will have to change
exports.loginAndCreateSession = function(postResult) {
	return new Promise(function(resolve, reject) {
		if (postResult) {
			var row = new DBRow("user");
			row.addQuery("netid", postResult.username)
			// row.addQuery("secret", postResult.secret) // BUT WE DON'T KNOW THE PASSWORD _/(O.O)\_

			row.query().then(function(result) {
				if (!row.next())
					return reject(false);

				var date = new Date();
				var newSession = new DBRow("session");
				var sessionInfo = {sessionStart: date.toISOString().slice(0, date.toISOString().indexOf('T')),
									userID: row.getValue("id")};

				newSession.setValue('userID', sessionInfo.userID);
				newSession.insert().then(function(res) {
					sessionInfo.sessionID = newSession.getValue('id');
					resolve(sessionInfo);
				}, function(res) {
					reject(false);
				});

			}, function(err){
				reject(false); // no matching user found - indicate failure
			});
		}
		else
			reject(false);
	})
}

exports.logout = function(cookie) {
	return new Promise(function(resolve, reject) {
		if(!cookie)
			reject(false);

		var row = new DBRow('session');
		row.delete(cookie.sessionID).then(function(res) {
			resolve(true);

		}, function(res) {
			reject(false);

		});
	});
}

exports.hasRole = function(userID, role) {
	return new Promise(function(resolve, reject) {
		if (!userID) {
			reject(false);
			return;
		}

		var user = new DBRow('user');
		user.getRow(userID).then(function(res) {
			if (user.count() == 0)
				reject(false);

			if(user.getValue('privilege').includes(role))
				resolve(true);
			else
				reject(false)

		}, function(res) {
			reject(false);
		});
	});
}

exports.validateUser = function(request) {
	return new Promise(function(resolve, reject) {

		var user = new DBRow('user');
		for (var key in request.query) {
			if (allowedUserKeys.includes(key)) // we do not allow searches for users by netid
				user.addQuery(key, request.query[key]);
		}

		user.query().then(function(res) {
			if (user.count() == 0)
				reject(false);
			else
				resolve(true);

		}, function(res) {
			reject(false);
		});
	});
}
<|endoftext|>


<commit_before>
  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,2,2,0,0,0,0],
          [0,0,0,0,0,2,2,0,0,0,0],
          [0,0,0,0,0,1,1,0,0,0,0]],
     2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0]] };

  var spriteData = {
    'alien1': { sx: 0,  sy: 0,  w: 23, h: 18, cls: Alien, frames: 2 },
    'alien2': { sx: 0,  sy: 18, w: 23, h: 18, cls: Alien, frames: 2 },
    'player': { sx: 59,  sy: 0, w: 20, h: 26, cls: Player },
    'missile': { sx: 65,  sy: 47, w: 5,  h: 5, cls: Missile }
  }

  function startGame() {
    var screen = new GameScreen("Alien Invaders","press space to start",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
    Game.loop();
  }

  function endGame() {
    var screen = new GameScreen("Game Over","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }

  function winGame() {
    var screen = new GameScreen("You Win!","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }

  $(function() {
    GameAudio.load({ 'fire' : 'media/laser.ogg', 'die' : 'media/explosion.ogg' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<commit_msg>New Level<commit_after>
  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,2,2,0,0,0,0],
          [0,0,0,0,0,2,2,0,0,0,0],
          [0,0,0,0,0,1,1,0,0,0,0]],
      2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,1,1,1,0,0,0,0],
          [0,0,0,2,2,2,2,2,0,0,0],
          [0,0,0,2,2,2,2,2,0,0,0],
          [0,0,0,0,1,1,1,0,0,0,0]],
     3:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0]] };

  var spriteData = {
    'alien1': { sx: 0,  sy: 0,  w: 23, h: 18, cls: Alien, frames: 2 },
    'alien2': { sx: 0,  sy: 18, w: 23, h: 18, cls: Alien, frames: 2 },
    'player': { sx: 59,  sy: 0, w: 20, h: 26, cls: Player },
    'missile': { sx: 65,  sy: 47, w: 5,  h: 5, cls: Missile }
  }

  function startGame() {
    var screen = new GameScreen("Alien Invaders","press space to start",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
    Game.loop();
  }

  function endGame() {
    var screen = new GameScreen("Game Over","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }

  function winGame() {
    var screen = new GameScreen("You Win!","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }

  $(function() {
    GameAudio.load({ 'fire' : 'media/laser.ogg', 'die' : 'media/explosion.ogg' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign, no-console */
import test from 'ava';
import path from 'path';
import fs from 'fs';
import shell from 'shelljs';
import { constructPlugin, fireEventsBusEvent } from 'meteor-desktop-test-suite';
import { before, beforeEach, always, getApp, waitForSplashWindow, wait, isImageSimilar }
    from './helpers/helpers';

const appDir = path.join(__dirname, '.testApp');

test.before(before.bind(null, appDir));
test.beforeEach(beforeEach.bind(null, appDir, undefined));
test.afterEach.always(always.bind(null, appDir));
test.after(
    () => shell.rm('-rf', appDir)
);

test('the test app', async t => getApp(t));

test('if splash screen is displayed', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    t.true(await app.client.getWindowCount() === 2);
});

test('if splash screen is closed', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    t.is(await app.client.getWindowCount(), 2);
    await fireEventsBusEvent(app, 'beforeLoadFinish');
    t.is(await app.client.getWindowCount(), 1);
});

test('if splash window title is set properly', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowTitle: 'SplashTest',
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    t.is(await app.client.getTitle(), 'SplashTest');
});

test('if splash screen can be disabled', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        enabled: false
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await wait(200);
    t.true(await app.client.getWindowCount() === 1);
});

test('if image is displayed', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    await wait(200);
    const imageBuffer = await app.browserWindow.capturePage();
    const pagePngPath = path.join(__dirname, 'page.png');
    fs.writeFileSync(pagePngPath, imageBuffer);

    t.true(await isImageSimilar(
        pagePngPath,
        path.join(__dirname, 'refs', 'splash.png')));

    fs.unlinkSync(pagePngPath);
});

test('if styles can be injected', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        style: { 'background-color': 'red' },
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);

    await wait(200);
    const imageBuffer = await app.browserWindow.capturePage();
    const page2PngPath = path.join(__dirname, 'page_2.png');
    fs.writeFileSync(page2PngPath, imageBuffer);

    t.true(await isImageSimilar(
        page2PngPath,
        path.join(__dirname, 'refs', 'splash_modified_style.png')));

    fs.unlinkSync(page2PngPath);
});

test('if window settings can be injected', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: {
            width: 200,
            height: 200,
            webPreferences: { nodeIntegration: true }
        }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);

    t.deepEqual(await app.browserWindow.getSize(), [200, 200]);
});

// TODO: implement unit test instead of this incomplete functional one.
test('if splash screen is displayed with proper window icon [incomplete test]', async (t) => {
    const app = await getApp(t);
    await constructPlugin(
        app,
        undefined,
        undefined,
        {
            window: {
                icon: path.join(appDir, 'assets', 'meteor.png')
            }
        },
        undefined,
        undefined, {
            windowSettings: { webPreferences: { nodeIntegration: true } }
        }
    );
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);

    // TODO: how to check if windows is displayed with proper icon? is this possible in spectron?

    // For now you can test it manually here, uncomment line below and you will have 20 secs to
    // verify it :)

    // await wait(20000);
});
<commit_msg>Add window size test<commit_after>/* eslint-disable no-param-reassign, no-console */
import test from 'ava';
import path from 'path';
import fs from 'fs';
import shell from 'shelljs';
import { constructPlugin, fireEventsBusEvent } from 'meteor-desktop-test-suite';
import { before, beforeEach, always, getApp, waitForSplashWindow, wait, isImageSimilar }
    from './helpers/helpers';

const appDir = path.join(__dirname, '.testApp');

test.before(before.bind(null, appDir));
test.beforeEach(beforeEach.bind(null, appDir, undefined));
test.afterEach.always(always.bind(null, appDir));
test.after(
    () => shell.rm('-rf', appDir)
);

test('the test app', async t => getApp(t));

test('if splash screen is displayed', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    t.true(await app.client.getWindowCount() === 2);
});

test('if splash screen is closed', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    t.is(await app.client.getWindowCount(), 2);
    await fireEventsBusEvent(app, 'beforeLoadFinish');
    t.is(await app.client.getWindowCount(), 1);
});

test('if splash window title is set properly', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowTitle: 'SplashTest',
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    t.is(await app.client.getTitle(), 'SplashTest');
});

test('if window size is correct', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowTitle: 'SplashTest',
        windowSettings: { width: 200, height: 400, webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    const size = await app.browserWindow.getSize();
    t.true(size[0] === 200);
    t.true(size[1] === 400);
});

test('if splash screen can be disabled', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        enabled: false
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await wait(200);
    t.true(await app.client.getWindowCount() === 1);
});

test('if image is displayed', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);
    await wait(200);
    const imageBuffer = await app.browserWindow.capturePage();
    const pagePngPath = path.join(__dirname, 'page.png');
    fs.writeFileSync(pagePngPath, imageBuffer);

    t.true(await isImageSimilar(
        pagePngPath,
        path.join(__dirname, 'refs', 'splash.png')));

    fs.unlinkSync(pagePngPath);
});

test('if styles can be injected', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        style: { 'background-color': 'red' },
        windowSettings: { webPreferences: { nodeIntegration: true } }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);

    await wait(200);
    const imageBuffer = await app.browserWindow.capturePage();
    const page2PngPath = path.join(__dirname, 'page_2.png');
    fs.writeFileSync(page2PngPath, imageBuffer);

    t.true(await isImageSimilar(
        page2PngPath,
        path.join(__dirname, 'refs', 'splash_modified_style.png')));

    fs.unlinkSync(page2PngPath);
});

test('if window settings can be injected', async (t) => {
    const app = await getApp(t);
    await constructPlugin(app, undefined, undefined, undefined, undefined, undefined, {
        windowSettings: {
            width: 200,
            height: 200,
            webPreferences: { nodeIntegration: true }
        }
    });
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);

    t.deepEqual(await app.browserWindow.getSize(), [200, 200]);
});

// TODO: implement unit test instead of this incomplete functional one.
test('if splash screen is displayed with proper window icon [incomplete test]', async (t) => {
    const app = await getApp(t);
    await constructPlugin(
        app,
        undefined,
        undefined,
        {
            window: {
                icon: path.join(appDir, 'assets', 'meteor.png')
            }
        },
        undefined,
        undefined, {
            windowSettings: { webPreferences: { nodeIntegration: true } }
        }
    );
    await fireEventsBusEvent(app, 'beforeModulesLoad');
    await waitForSplashWindow(app);

    // TODO: how to check if windows is displayed with proper icon? is this possible in spectron?

    // For now you can test it manually here, uncomment line below and you will have 20 secs to
    // verify it :)

    // await wait(20000);
});
<|endoftext|>


<commit_before>// Initialize a jQuery object
import jQuery from "../core.js";
import document from "../var/document.js";
import rsingleTag from "./var/rsingleTag.js";
import isObviousHtml from "./isObviousHtml.js";

import "../traversing/findFilter.js";

// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (trac-9521)
	// Strict HTML recognition (trac-11290: must start with <)
	// Shortcut simple #id case for speed
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,

	init = jQuery.fn.init = function( selector, context, root ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Method init() accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// HANDLE: $(DOMElement)
		if ( selector.nodeType ) {
			this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( typeof selector === "function" ) {
			return root.ready !== undefined ?
				root.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );

		} else {

			// Handle obvious HTML strings
			match = selector + "";
			if ( isObviousHtml( match ) ) {

				// Assume that strings that start and end with <> are HTML and skip
				// the regex check. This also handles browser-supported HTML wrappers
				// like TrustedHTML.
				match = [ null, selector, null ];

			// Handle HTML strings or selectors
			} else if ( typeof selector === "string" ) {
				match = rquickExpr.exec( selector );
			} else {
				return jQuery.makeArray( selector, this );
			}

			// Match html or make sure no context is specified for #id
			// Note: match[1] may be a string or a TrustedHTML wrapper
			if ( match && ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( typeof this[ match ] === "function" ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					if ( elem ) {

						// Inject the element directly into the jQuery object
						this[ 0 ] = elem;
						this.length = 1;
					}
					return this;
				}

			// HANDLE: $(expr) & $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || root ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}
		}

	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );
<commit_msg>Core: Drop the root parameter of jQuery.fn.init<commit_after>// Initialize a jQuery object
import jQuery from "../core.js";
import document from "../var/document.js";
import rsingleTag from "./var/rsingleTag.js";
import isObviousHtml from "./isObviousHtml.js";

import "../traversing/findFilter.js";

// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (trac-9521)
	// Strict HTML recognition (trac-11290: must start with <)
	// Shortcut simple #id case for speed
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,

	init = jQuery.fn.init = function( selector, context ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// HANDLE: $(DOMElement)
		if ( selector.nodeType ) {
			this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( typeof selector === "function" ) {
			return rootjQuery.ready !== undefined ?
				rootjQuery.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );

		} else {

			// Handle obvious HTML strings
			match = selector + "";
			if ( isObviousHtml( match ) ) {

				// Assume that strings that start and end with <> are HTML and skip
				// the regex check. This also handles browser-supported HTML wrappers
				// like TrustedHTML.
				match = [ null, selector, null ];

			// Handle HTML strings or selectors
			} else if ( typeof selector === "string" ) {
				match = rquickExpr.exec( selector );
			} else {
				return jQuery.makeArray( selector, this );
			}

			// Match html or make sure no context is specified for #id
			// Note: match[1] may be a string or a TrustedHTML wrapper
			if ( match && ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( typeof this[ match ] === "function" ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					if ( elem ) {

						// Inject the element directly into the jQuery object
						this[ 0 ] = elem;
						this.length = 1;
					}
					return this;
				}

			// HANDLE: $(expr) & $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || rootjQuery ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}
		}

	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );
<|endoftext|>


<commit_before>/* eslint no-console: 0 */

const mongoose = require('mongoose');
const chalk = require('chalk');
const log = require('debug')('flint');
const registerPlugins = require('./registerPlugins');

const UserGroupSchema = require('../models/UserGroupSchema');
const UserSchema = require('../models/UserSchema');
const SectionSchema = require('../models/SectionSchema');
const EntrySchema = require('../models/EntrySchema');
const FieldSchema = require('../models/FieldSchema');
const AssetSchema = require('../models/AssetSchema');
const PageSchema = require('../models/PageSchema');
const SiteSchema = require('../models/SiteSchema');
const PluginSchema = require('../models/PluginSchema');
const createAdminUserGroup = require('./createAdminUserGroup');
const updateSiteConfig = require('./updateSiteConfig');

mongoose.Promise = global.Promise;

const mongoUri = `mongodb://${process.env.DB_HOST}`;
const mongoOptions = {
  user: process.env.DB_USER,
  pass: process.env.DB_PASS,
  useMongoClient: true,
};

module.exports = function connectToDatabase() {
  mongoose.connect(mongoUri, mongoOptions);
  return new Promise((resolve, reject) => {
    mongoose.connection.on('open', async () => {
      /* eslint-disable global-require */
      mongoose.model('Plugin', PluginSchema, 'plugins');
      await registerPlugins();

      mongoose.model('UserGroup', UserGroupSchema, 'usergroups');
      await createAdminUserGroup();

      mongoose.model('User', UserSchema, 'users');
      mongoose.model('Section', SectionSchema, 'sections');
      mongoose.model('Entry', EntrySchema, 'entries');
      mongoose.model('Field', FieldSchema, 'fields');
      mongoose.model('Asset', AssetSchema, 'assets');
      mongoose.model('Page', PageSchema, 'pages');

      mongoose.model('Site', SiteSchema, 'sites');
      await updateSiteConfig();
      /* eslint-enable global-require */

      resolve(`${chalk.green('[Mongoose]')} connection has been successfully established.`);
    });
    mongoose.connection.on('error', e =>
      reject(`${chalk.red('[Mongoose]')} Connection error: ${e}`));
  });
};

// Close the Mongoose connected on Ctrl+C
/* istanbul ignore next */
process.on('SIGINT', () => {
  mongoose.connection.close(() => {
    log('Mongoose default connection disconnected');
    process.exit(0);
  });
});
<commit_msg>Fix Site model<commit_after>/* eslint no-console: 0 */

const mongoose = require('mongoose');
const chalk = require('chalk');
const log = require('debug')('flint');
const registerPlugins = require('./registerPlugins');

const UserGroupSchema = require('../models/UserGroupSchema');
const UserSchema = require('../models/UserSchema');
const SectionSchema = require('../models/SectionSchema');
const EntrySchema = require('../models/EntrySchema');
const FieldSchema = require('../models/FieldSchema');
const AssetSchema = require('../models/AssetSchema');
const PageSchema = require('../models/PageSchema');
const SiteSchema = require('../models/SiteSchema');
const PluginSchema = require('../models/PluginSchema');
const createAdminUserGroup = require('./createAdminUserGroup');
const updateSiteConfig = require('./updateSiteConfig');

mongoose.Promise = global.Promise;

const mongoUri = `mongodb://${process.env.DB_HOST}`;
const mongoOptions = {
  user: process.env.DB_USER,
  pass: process.env.DB_PASS,
  useMongoClient: true,
};

module.exports = function connectToDatabase() {
  mongoose.connect(mongoUri, mongoOptions);
  return new Promise((resolve, reject) => {
    mongoose.connection.on('open', async () => {
      /* eslint-disable global-require */
      mongoose.model('Plugin', PluginSchema, 'plugins');
      await registerPlugins();

      mongoose.model('UserGroup', UserGroupSchema, 'usergroups');
      await createAdminUserGroup();

      mongoose.model('User', UserSchema, 'users');
      mongoose.model('Section', SectionSchema, 'sections');
      mongoose.model('Entry', EntrySchema, 'entries');
      mongoose.model('Field', FieldSchema, 'fields');
      mongoose.model('Asset', AssetSchema, 'assets');
      mongoose.model('Page', PageSchema, 'pages');

      mongoose.model('Site', SiteSchema, 'site');
      await updateSiteConfig();
      /* eslint-enable global-require */

      resolve(`${chalk.green('[Mongoose]')} connection has been successfully established.`);
    });
    mongoose.connection.on('error', e =>
      reject(`${chalk.red('[Mongoose]')} Connection error: ${e}`));
  });
};

// Close the Mongoose connected on Ctrl+C
/* istanbul ignore next */
process.on('SIGINT', () => {
  mongoose.connection.close(() => {
    log('Mongoose default connection disconnected');
    process.exit(0);
  });
});
<|endoftext|>


<commit_before>
//This is where you can chande the number of aliens in the different levels by using 1 and 2 intergers which correlate to the different alien images.

  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,2,2,2,2,0,0,0],
          [0,0,0,0,2,2,2,2,0,0,0],
          [0,0,0,0,1,1,1,1,0,0,0],
          [0,0,0,0,1,1,1,1,0,0,0]],
     2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0]]
     3:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,1,1,1,1,1,1,1,0,0]] };

		  //This is the co-ordinates of the images the game uses from the sprite page.

  var spriteData = {
    'alien1': { sx: 0,  sy: 0,  w: 23, h: 18, cls: Alien, frames: 2 },
    'alien2': { sx: 0,  sy: 18, w: 23, h: 18, cls: Alien, frames: 2 },
    'player': { sx: 0,  sy: 36, w: 26, h: 17, cls: Player },
    'missile': { sx: 0,  sy: 86, w: 3,  h: 14, cls: Missile }
  }

 		//This is the start page for the game itself.

  function startGame() {
    var screen = new GameScreen("Space Incagers","press space to start",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
    Game.loop();
  }

  //This is the screen that tells you you have been killed and to press space to start again from level 1.

  function endGame() {
    var screen = new GameScreen("Game Over","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }
		//This is the screen that tells you you have won and to press space to start the game from level 1.

  function winGame() {
    var screen = new GameScreen("You Win!","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }

  			//This is where the sounds are located to play when you fire a missile or hit something.

  $(function() {
    GameAudio.load({ 'fire' : 'media/laser.ogg', 'die' : 'media/explosion.ogg' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<commit_msg>Changed the name<commit_after>
//This is where you can chande the number of aliens in the different levels by using 1 and 2 intergers which correlate to the different alien images.

  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,2,2,2,2,0,0,0],
          [0,0,0,0,2,2,2,2,0,0,0],
          [0,0,0,0,1,1,1,1,0,0,0],
          [0,0,0,0,1,1,1,1,0,0,0]],
     2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,2,2,2,2,2,2,2,2,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0]] };

		  //This is the co-ordinates of the images the game uses from the sprite page.

  var spriteData = {
    'alien1': { sx: 0,  sy: 0,  w: 23, h: 18, cls: Alien, frames: 2 },
    'alien2': { sx: 0,  sy: 18, w: 23, h: 18, cls: Alien, frames: 2 },
    'player': { sx: 0,  sy: 36, w: 26, h: 17, cls: Player },
    'missile': { sx: 0,  sy: 86, w: 3,  h: 14, cls: Missile }
  }

 		//This is the start page for the game itself.

  function startGame() {
    var screen = new GameScreen("Space Wars","press space to start",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
    Game.loop();
  }

  //This is the screen that tells you you have been killed and to press space to start again from level 1.

  function endGame() {
    var screen = new GameScreen("Game Over","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }
		//This is the screen that tells you you have won and to press space to start the game from level 1.

  function winGame() {
    var screen = new GameScreen("You Win!","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
  }

  			//This is where the sounds are located to play when you fire a missile or hit something.

  $(function() {
    GameAudio.load({ 'fire' : 'media/laser.ogg', 'die' : 'media/explosion.ogg' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<|endoftext|>


<commit_before>var ragnarok = require('../bootstrap/js/ragnarok-bootstrap.js'),
    express = require('express'),
    app     = require('express')(),
    server  = require('http').createServer(app),
    io      = require('socket.io').listen(server),
    buffer = '',
    complete = false;

server.listen(1337);
console.log("Web server running on port 1337");

// Create routes for static content and the index
app.use(express.static(__dirname + '/static'));

app.get('/', function(req, res)
{
    console.log("Page requested.");
    res.sendfile(__dirname + '/index.html');
});

app.get('/character', function(req, res)
{
    res.end(JSON.stringify({
        character: ragnarok.character,
        storage: ragnarok.storage.items,
        inventory: ragnarok.inventory.items
    }));
});

var net = require('net');

var HOST = '0.0.0.0';
var PORT = 1338;

// Create a server instance
net.createServer(function(socket) {
    console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);

    socket.on('data', function(data) {
        var chunk = data.toString();

        // We use newlines to deliminate the end of our data
        if(chunk.indexOf("\n") == -1)
            complete = false;
        else
            complete = true;

        // Always add the current chunk to our buffer
        buffer += chunk;

        if(complete)
        {
            try
            {
                // Parse our buffer to see what's inside
                var buffered = JSON.parse(buffer);
            }
            catch(error)
            {
                var buffered = {'event': 'error', 'message': error};
            }

            switch(buffered.event)
            {
                case "chat":
                    buffered.data.timestamp = new Date();

                    // Emit chat message
                    io.sockets.emit('chat', buffered.data);
                    break;

                case "character":
                    // Save character data
                    ragnarok.character = buffered.data.character;
                    ragnarok.storage.items = buffered.data.storage;
                    ragnarok.inventory.items = buffered.data.inventory;
                    io.sockets.emit('refresh');
                    break;

                case "move":
                    ragnarok.character.pos = buffered.data.to;
                    io.sockets.emit('move', buffered.data);
                    break;

                case "item":
                    if(buffered.data.action == 'add' || buffered.data.action == 'remove')
                    {
                        ragnarok.inventory[buffered.data.action](buffered.data.item_id, buffered.data.quantity);
                    }

                    io.sockets.emit('item', buffered.data);
                    break;

                case "map":
                    ragnarok.character.map = buffered.data.map;
                    ragnarok.character.pos = buffered.data.pos;
                    io.sockets.emit('map', buffered.data);
                    break;

                default:
                    console.log('Unhandled event recieved: ' + buffered.event);
                    console.log(buffered);
                    console.log("\n");
                    break;
            }

            buffer = '';
        }

        console.log('From ' + socket.remoteAddress + ': ' + data);
    });

    socket.on('close', function(data) {
        console.log('Socket connection closed... ');
    });

    socket.on("error", function(error) {
        console.log("Socket had an error!")
        console.log(error)
    });

}).listen(PORT, HOST);

console.log("Statistics server running on " + PORT);
<commit_msg>Updated buffer handler to support multiple events in a single packet<commit_after>var ragnarok = require('../bootstrap/js/ragnarok-bootstrap.js'),
    express = require('express'),
    app     = require('express')(),
    server  = require('http').createServer(app),
    io      = require('socket.io').listen(server),
    buffer = '',
    complete = false;

server.listen(1337);
console.log("Web server running on port 1337");

// Create routes for static content and the index
app.use(express.static(__dirname + '/static'));

app.get('/', function(req, res)
{
    console.log("Page requested.");
    res.sendfile(__dirname + '/index.html');
});

app.get('/character', function(req, res)
{
    res.end(JSON.stringify({
        character: ragnarok.character,
        storage: ragnarok.storage.items,
        inventory: ragnarok.inventory.items
    }));
});

var net = require('net');

var HOST = '0.0.0.0';
var PORT = 1338;

// Create a server instance
net.createServer(function(socket) {
    console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);

    socket.on('data', function(data) {
        var chunk = data.toString();

        // We use newlines to deliminate the end of our data
        if(chunk.indexOf("\n") == -1)
            complete = false;
        else
            complete = true;

        // Always add the current chunk to our buffer
        buffer += chunk;

        if(complete)
        {
            var buffer_array = buffer.split("\n");
            var length = buffer_array.length;

            for($i = 0; $i < length; $i++)
            {
                // Skip empty buffers
                if(buffer_array[$i] == '')
                    continue;

                try
                {
                    // Parse our buffer to see what's inside
                    var buffered = JSON.parse(buffer_array[$i]);
                }
                catch(error)
                {
                    var buffered = {'event': 'error', 'message': error};
                }

                switch(buffered.event)
                {
                    case "chat":
                        buffered.data.timestamp = new Date();

                        // Emit chat message
                        io.sockets.emit('chat', buffered.data);
                        break;

                    case "character":
                        // Save character data
                        ragnarok.character = buffered.data.character;
                        ragnarok.storage.items = buffered.data.storage;
                        ragnarok.inventory.items = buffered.data.inventory;
                        io.sockets.emit('refresh');
                        break;

                    case "move":
                        ragnarok.character.pos = buffered.data.to;
                        io.sockets.emit('move', buffered.data);
                        break;

                    case "item":
                        if(buffered.data.action == 'add' || buffered.data.action == 'remove')
                        {
                            ragnarok.inventory[buffered.data.action](buffered.data.item_id, buffered.data.quantity);
                        }

                        io.sockets.emit('item', buffered.data);
                        break;

                    case "map":
                        ragnarok.character.map = buffered.data.map;
                        ragnarok.character.pos = buffered.data.pos;
                        io.sockets.emit('map', buffered.data);
                        break;

                    default:
                        console.log('Unhandled event recieved: ' + buffered.event);
                        console.log(buffered);
                        console.log("\n");
                        break;
                }

            }

            buffer = '';
        }

        console.log('From ' + socket.remoteAddress + ': ' + data);
    });

    socket.on('close', function(data) {
        console.log('Socket connection closed... ');
    });

    socket.on("error", function(error) {
        console.log("Socket had an error!")
        console.log(error)
    });

}).listen(PORT, HOST);

console.log("Statistics server running on " + PORT);
<|endoftext|>


<commit_before>function setupLinkHandling() {
    window.history.pushState({"html": document.documentElement.outerHTML}, "", window.location.href);

    var anchors = document.getElementsByTagName("a");

    for (var i = 0; i < anchors.length; i++) {
        if (anchors[i].href.startsWith("http://localhost") || anchors[i].href.startsWith("http://club.atomhacks.org")) {
            anchors[i].onclick = function() {
                var href = this.href;
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        window.history.pushState({"html": this.responseText}, "", href);
                        document.getElementsByTagName("html")[0].innerHTML = this.responseText;
                        setupLinkHandling();
                        setupNavigation();
                        generateShapes();
                    }
                };
                xhttp.open("GET", href, true);
                xhttp.send();

                return false;
            };
        }
    }

    window.onpopstate = function(e) {
        if (e.state) {
            document.getElementsByTagName("html")[0].innerHTML = e.state.html;
        }
    };
}

setupLinkHandling();
<commit_msg>Use the correct URL<commit_after>function setupLinkHandling() {
    window.history.pushState({"html": document.documentElement.outerHTML}, "", window.location.href);

    var anchors = document.getElementsByTagName("a");

    for (var i = 0; i < anchors.length; i++) {
        if (anchors[i].href.startsWith("http://localhost") || anchors[i].href.startsWith("http://atomhacks.github.io")) {
            anchors[i].onclick = function() {
                var href = this.href;
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        window.history.pushState({"html": this.responseText}, "", href);
                        document.getElementsByTagName("html")[0].innerHTML = this.responseText;
                        setupLinkHandling();
                        setupNavigation();
                        generateShapes();
                    }
                };
                xhttp.open("GET", href, true);
                xhttp.send();

                return false;
            };
        }
    }

    window.onpopstate = function(e) {
        if (e.state) {
            document.getElementsByTagName("html")[0].innerHTML = e.state.html;
        }
    };
}

setupLinkHandling();
<|endoftext|>


<commit_before>const chai = require('chai');
const assert = chai.assert;

var Board = require('../lib/board')
var Square = require('../lib/square')
var Piece = require('../lib/piece')

describe('Square', function () {
  beforeEach( function () {
    this.board = new Board ();
  });

  it('should instantiate a new square', function () {
    let square = new Square ();
    assert.isObject(square);
  });

  it('should know its coordinates', function () {
    let square = new Square (this.board, 3, 5);
    assert.equal(square.xCoordinate, 3);
    assert.equal(square.yCoordinate, 5);
  });

  it('should know the board it belongs to', function () {
    let square = new Square (this.board, 3, 5);
    assert.equal(square.board, this.board);
  });

  it('should know a piece can move to it', function () {
    let square = new Square (this.board, 3, 5);
    let squareTwo = new Square (this.board, 3, 6);
    let piece = new Piece (squareTwo, "white");
    squareTwo.piece = piece;
    this.board.squares.push(square);
    this.board.squares.push(squareTwo);
    assert.include(square.legalPieces(), piece);
  });

  it('should remove piece from the board when another piece enters', function () {
    let square = new Square (this.board, 3, 5);
    let piece = new Piece (square, "black");
    square.piece = piece;
    let squareTwo = new Square (this.board, 3, 6);
    let pieceTwo = new Piece (squareTwo, "white");
    squareTwo.piece = pieceTwo;
    this.board.squares.push(square);
    this.board.squares.push(squareTwo);
    var preCount = this.board.pieceCount();

    piece.move(squareTwo);

    assert.equal(this.board.pieceCount(), (preCount - 1));
    assert.equal(squareTwo.piece, piece);
    assert.equal(piece.square, squareTwo);
    assert.equal(pieceTwo.square, null);
  });
});
<commit_msg>Adds require for game.<commit_after>const chai = require('chai');
const assert = chai.assert;

var Game = require('../lib/game')
var Board = require('../lib/board')
var Square = require('../lib/square')
var Piece = require('../lib/piece')

describe('Square', function () {
  beforeEach( function () {
    this.board = new Board ();
    this.game = new Game (this.board);
    this.board.game = this.game;
  });

  it('should instantiate a new square', function () {
    let square = new Square ();
    assert.isObject(square);
  });

  it('should know its coordinates', function () {
    let square = new Square (this.board, 3, 5);
    assert.equal(square.xCoordinate, 3);
    assert.equal(square.yCoordinate, 5);
  });

  it('should know the board it belongs to', function () {
    let square = new Square (this.board, 3, 5);
    assert.equal(square.board, this.board);
  });

  it('should know a piece can move to it', function () {
    let square = new Square (this.board, 3, 5);
    let squareTwo = new Square (this.board, 3, 6);
    let piece = new Piece (squareTwo, "white");
    squareTwo.piece = piece;
    this.board.squares.push(square);
    this.board.squares.push(squareTwo);
    assert.include(square.legalPieces(), piece);
  });

  it('should remove piece from the board when another piece enters', function () {
    let square = new Square (this.board, 3, 5);
    let piece = new Piece (square, "black");
    square.piece = piece;
    let squareTwo = new Square (this.board, 3, 6);
    let pieceTwo = new Piece (squareTwo, "white");
    squareTwo.piece = pieceTwo;
    this.board.squares.push(square);
    this.board.squares.push(squareTwo);
    var preCount = this.board.pieceCount();

    piece.move(squareTwo);

    assert.equal(this.board.pieceCount(), (preCount - 1));
    assert.equal(squareTwo.piece, piece);
    assert.equal(piece.square, squareTwo);
    assert.equal(pieceTwo.square, null);
  });
});
<|endoftext|>


<commit_before>import '@webcomponents/shadycss/entrypoints/apply-shim';

import '@polymer/iron-flex-layout/iron-flex-layout';

import { translatable } from '@neovici/cosmoz-i18next';
import {
	mixin, Template
} from '@neovici/cosmoz-utils';

import { PolymerElement } from '@polymer/polymer/polymer-element';
import { html } from '@polymer/polymer/lib/utils/html-tag';
window.Cosmoz = window.Cosmoz || {};

/**
 * @polymer
 * @customElement
 * @appliesMixin translatable
 */
class OmnitableColumnListData extends translatable(mixin(Template, PolymerElement)) {
	static get template() {
		return html`

				[[ _firstItem(items) ]]

				[[ _('and {0} more', _othersCount, t) ]]

			<template is="dom-repeat" items="[[ _otherItems(items, _expanded) ]]" as="item">

					[[ item ]]

			</template>

				[[ _('See less', t) ]]

`;
	}

	static get is() {
		return 'cosmoz-omnitable-column-list-data';
	}

	static get properties() {
		return {
			items: {
				type: Array
			},

			_expanded: {
				type: Boolean,
				value: false
			},

			_othersCount: {
				type: Number,
				computed: '_computeOthersCount(items)'
			}
		};
	}

	_firstItem(items) {
		if (items !== undefined && items !== null && items.length > 0) {
			return items[0];
		}
	}

	_hideExpand(items, expanded) {
		if (items !== undefined && items.length !== null) {
			return items.length <= 2 || expanded;
		}
		return true;
	}

	_hideCollapse(items, expanded) {
		if (items !== undefined && items.length !== null) {
			return items.length <= 2 || !expanded;
		}
		return true;
	}

	_otherItems(items, expanded) {
		if (items !== undefined && items !== null) {
			if (items.length <= 2 || expanded) {
				return items.slice(1);
			}
		}
	}

	_computeOthersCount(items) {
		if (items !== undefined && items !== null) {
			return items.length - 1;
		}
	}

	_toggleExpand(event) {
		this._expanded = !this._expanded;
		event.stopPropagation();
		event.preventDefault();
		this.dispatchEvent(new CustomEvent('iron-resize', { bubbles: true }));
	}
}

customElements.define(OmnitableColumnListData.is, OmnitableColumnListData);
<commit_msg>fix(column-list-data): add ellipses to overflow<commit_after>import '@webcomponents/shadycss/entrypoints/apply-shim';

import '@polymer/iron-flex-layout/iron-flex-layout';

import { translatable } from '@neovici/cosmoz-i18next';
import {
	mixin, Template
} from '@neovici/cosmoz-utils';

import { PolymerElement } from '@polymer/polymer/polymer-element';
import { html } from '@polymer/polymer/lib/utils/html-tag';
window.Cosmoz = window.Cosmoz || {};

/**
 * @polymer
 * @customElement
 * @appliesMixin translatable
 */
class OmnitableColumnListData extends translatable(mixin(Template, PolymerElement)) {
	static get template() {
		return html`

				[[ _firstItem(items) ]]

				[[ _('and {0} more', _othersCount, t) ]]

			<template is="dom-repeat" items="[[ _otherItems(items, _expanded) ]]" as="item">

					[[ item ]]

			</template>

				[[ _('See less', t) ]]

`;
	}

	static get is() {
		return 'cosmoz-omnitable-column-list-data';
	}

	static get properties() {
		return {
			items: {
				type: Array
			},

			_expanded: {
				type: Boolean,
				value: false
			},

			_othersCount: {
				type: Number,
				computed: '_computeOthersCount(items)'
			}
		};
	}

	_firstItem(items) {
		if (items !== undefined && items !== null && items.length > 0) {
			return items[0];
		}
	}

	_hideExpand(items, expanded) {
		if (items !== undefined && items.length !== null) {
			return items.length <= 2 || expanded;
		}
		return true;
	}

	_hideCollapse(items, expanded) {
		if (items !== undefined && items.length !== null) {
			return items.length <= 2 || !expanded;
		}
		return true;
	}

	_otherItems(items, expanded) {
		if (items !== undefined && items !== null) {
			if (items.length <= 2 || expanded) {
				return items.slice(1);
			}
		}
	}

	_computeOthersCount(items) {
		if (items !== undefined && items !== null) {
			return items.length - 1;
		}
	}

	_toggleExpand(event) {
		this._expanded = !this._expanded;
		event.stopPropagation();
		event.preventDefault();
		this.dispatchEvent(new CustomEvent('iron-resize', { bubbles: true }));
	}
}

customElements.define(OmnitableColumnListData.is, OmnitableColumnListData);
<|endoftext|>


<commit_before>// queue-test
// tests for forerunner queue modules

var vows = require('vows');
var async = require('async');
var _ = require('underscore');
var assert = require('assert');

var sampleData = [];

// take in a queue object just like forerunner would
// this way the queue object can be initialized properly w/o the tests being concerned
function testModule(storeObject, testCallbacks) {
  var tests = vows.describe('Store')
  .addBatch({
    'Creating a few jobs': {
      topic: function() {
        var self = this;
        var jobs = [1, 2, 3, 4];

        async.mapSeries(jobs, function(item, cb) {
          storeObject.create('testObject', {foo: 'bar' + item}, function(err, id, obj) {
            if (err) {
              cb(err);
            } else {
              cb(null, {
                id: id,
                obj: obj
              });
            }
          });
        }, function(err, results) {
          self.callback(err, results);
        });
      },

      'returns an id and an object': function(err, storedObjects) {
        assert.isNull(err);
        var ids = [];
        _.each(storedObjects, function(obj) {
          assert.equal(ids.indexOf(obj.id), -1);
          assert.isObject(obj.obj);
          // store the data for reference later
          sampleData.push(obj);
        });
      }
    }
  })
  .addBatch({
    'Marking progress': {
      topic: function() {
        storeObject.progress(sampleData[0].id, 'wharrgarbl', this.callback);
      },

      'works': function(err) {
        assert.isUndefined(err);
      }
    }
  })
  .addBatch({
    'Counting a failure': {
      topic: function() {
        storeObject.countFailed(sampleData[1].id, 'fail_count', this.callback);
      },

      'returns a failure count of 1': function(err, count) {
        assert.isNull(err);
        assert.equal(count, 1);
      },

      'doing it again': {
        topic: function() {
          storeObject.countFailed(sampleData[1].id, 'fail_count', this.callback);
        },

        'returns a count of 2': function(err, count) {
          assert.isNull(err);
          assert.equal(count, 2);
        }
      }
    }
  })
  .addBatch({
    'Marking a failure': {
      topic: function() {
        storeObject.failed(sampleData[2].id, this.callback);
      },

      'works': function(err) {
        assert.isUndefined(err);
      }
    }
  })
  .addBatch({
    'Marking a completion': {
      topic: function() {
        storeObject.complete(sampleData[3].id, {cat: 'dog'}, this.callback);
      },

      'works': function(err) {
        assert.isUndefined(err);
      }
    }
  })
  .addBatch({
    'Getting queued objects': {
      topic: function() {
        var self = this;
        // empty the queue first
        storeObject.getQueue(this.callback);
      },

      'returns the expected results': function(err, jobs) {
        assert.isNull(err);
        var sourceIds = _.pluck(jobs, 'id');
        // make sure only the two NOT marked as failed or complete are returned
        assert.equal(sourceIds.length, 2);
      }
    }
  })
  .run({reporter: require('vows/lib/vows/reporters/spec')}, testCallbacks);
}
module.exports = testModule;

<commit_msg>few typos<commit_after>// store-test
// tests for forerunner store modules

var vows = require('vows');
var async = require('async');
var _ = require('underscore');
var assert = require('assert');

var sampleData = [];

// take in a store object just like forerunner would
// this way the store object can be initialized properly w/o the tests being concerned
function testModule(storeObject, testCallbacks) {
  var tests = vows.describe('Store')
  .addBatch({
    'Creating a few jobs': {
      topic: function() {
        var self = this;
        var jobs = [1, 2, 3, 4];

        async.mapSeries(jobs, function(item, cb) {
          storeObject.create('testObject', {foo: 'bar' + item}, function(err, id, obj) {
            if (err) {
              cb(err);
            } else {
              cb(null, {
                id: id,
                obj: obj
              });
            }
          });
        }, function(err, results) {
          self.callback(err, results);
        });
      },

      'returns an id and an object': function(err, storedObjects) {
        assert.isNull(err);
        var ids = [];
        _.each(storedObjects, function(obj) {
          assert.equal(ids.indexOf(obj.id), -1);
          assert.isObject(obj.obj);
          // store the data for reference later
          sampleData.push(obj);
        });
      }
    }
  })
  .addBatch({
    'Marking progress': {
      topic: function() {
        storeObject.progress(sampleData[0].id, 'wharrgarbl', this.callback);
      },

      'works': function(err) {
        assert.isUndefined(err);
      }
    }
  })
  .addBatch({
    'Counting a failure': {
      topic: function() {
        storeObject.countFailed(sampleData[1].id, 'fail_count', this.callback);
      },

      'returns a failure count of 1': function(err, count) {
        assert.isNull(err);
        assert.equal(count, 1);
      },

      'doing it again': {
        topic: function() {
          storeObject.countFailed(sampleData[1].id, 'fail_count', this.callback);
        },

        'returns a count of 2': function(err, count) {
          assert.isNull(err);
          assert.equal(count, 2);
        }
      }
    }
  })
  .addBatch({
    'Marking a failure': {
      topic: function() {
        storeObject.failed(sampleData[2].id, this.callback);
      },

      'works': function(err) {
        assert.isUndefined(err);
      }
    }
  })
  .addBatch({
    'Marking a completion': {
      topic: function() {
        storeObject.complete(sampleData[3].id, {cat: 'dog'}, this.callback);
      },

      'works': function(err) {
        assert.isUndefined(err);
      }
    }
  })
  .addBatch({
    'Getting queued objects': {
      topic: function() {
        var self = this;
        // empty the queue first
        storeObject.getQueue(this.callback);
      },

      'returns the expected results': function(err, jobs) {
        assert.isNull(err);
        var sourceIds = _.pluck(jobs, 'id');
        // make sure only the two NOT marked as failed or complete are returned
        assert.equal(sourceIds.length, 2);
      }
    }
  })
  .run({reporter: require('vows/lib/vows/reporters/spec')}, testCallbacks);
}
module.exports = testModule;

<|endoftext|>