<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */
goog.require('devtools.InspectorController');

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  devtools.InspectorController.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('setTextNodeValue');

  this.installInjectedScriptDelegate_('getStyles');
  this.installInjectedScriptDelegate_('getComputedStyle');
  this.installInjectedScriptDelegate_('getInlineStyle');
  this.installInjectedScriptDelegate_('applyStyleText');
  this.installInjectedScriptDelegate_('setStyleText');
  this.installInjectedScriptDelegate_('toggleStyleEnabled');
  this.installInjectedScriptDelegate_('applyStyleRuleText');
  this.installInjectedScriptDelegate_('addStyleSelector');
  this.installInjectedScriptDelegate_('setStyleProperty');
  this.installInjectedScriptDelegate_('getPrototypes');
  this.installInjectedScriptDelegate_('getProperties');
  this.installInjectedScriptDelegate_('setPropertyValue');

  this.installInjectedScriptDelegate_('evaluate');
  this.installInjectedScriptDelegate_('addInspectedNode');
  this.installInjectedScriptDelegate_('performSearch');
  this.installInjectedScriptDelegate_('searchCanceled');
};
goog.inherits(devtools.InspectorControllerImpl,
    devtools.InspectorController);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return 'databases';
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  devtools.InspectorController.prototype.toggleNodeSearch.call(this);
  DevToolsHost.toggleInspectElementMode(this.searchingForNode());
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }
  DevToolsHost.addResourceSourceToFrame(identifier, resource.mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.enableResourceTracking =
    function(always) {
  devtools.tools.setResourceTrackingEnabled(true, always);
}

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.disableResourceTracking =
    function(always) {
  devtools.tools.setResourceTrackingEnabled(false, always);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.currentCallFrame = function() {
  return devtools.tools.getDebuggerAgent().getCurrentCallFrame();
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

devtools.InspectorControllerImpl.prototype.storeLastActivePanel =
    function(panel) {
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(undefined),
      'InspectorController', JSON.stringify(['storeLastActivePanel', panel]));
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInjectedScriptDelegate_ =
    function(methodName) {
  this[methodName] = goog.bind(this.callInjectedScript_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInjectedScript_ =
    function(methodName, var_arg) {
  var allArgs = Array.prototype.slice.call(arguments);
  var callback = allArgs[allArgs.length - 1];
  var args = Array.prototype.slice.call(allArgs, 0, allArgs.length - 1);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.InspectorControllerImpl.parseWrap_(callback),
      'InjectedScript', JSON.stringify(args));
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(function(){}),
      'InspectorController', JSON.stringify(args));
};

devtools.InspectorControllerImpl.parseWrap_ = function(callback) {
  return devtools.Callback.wrap(
      function(data) {
        callback.call(this, JSON.parse(data));
      });
};

InspectorController = new devtools.InspectorControllerImpl();
<commit_msg>DevTools: Add delegate for method added upstream.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */
goog.require('devtools.InspectorController');

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  devtools.InspectorController.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('setTextNodeValue');

  this.installInjectedScriptDelegate_('getStyles');
  this.installInjectedScriptDelegate_('getComputedStyle');
  this.installInjectedScriptDelegate_('getInlineStyle');
  this.installInjectedScriptDelegate_('applyStyleText');
  this.installInjectedScriptDelegate_('setStyleText');
  this.installInjectedScriptDelegate_('toggleStyleEnabled');
  this.installInjectedScriptDelegate_('applyStyleRuleText');
  this.installInjectedScriptDelegate_('addStyleSelector');
  this.installInjectedScriptDelegate_('setStyleProperty');
  this.installInjectedScriptDelegate_('getPrototypes');
  this.installInjectedScriptDelegate_('getProperties');
  this.installInjectedScriptDelegate_('setPropertyValue');
  this.installInjectedScriptDelegate_('evaluate');
  this.installInjectedScriptDelegate_('addInspectedNode');
  this.installInjectedScriptDelegate_('pushNodeToFrontend');
  this.installInjectedScriptDelegate_('performSearch');
  this.installInjectedScriptDelegate_('searchCanceled');
};
goog.inherits(devtools.InspectorControllerImpl,
    devtools.InspectorController);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return 'databases';
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  devtools.InspectorController.prototype.toggleNodeSearch.call(this);
  DevToolsHost.toggleInspectElementMode(this.searchingForNode());
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }
  DevToolsHost.addResourceSourceToFrame(identifier, resource.mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.enableResourceTracking =
    function(always) {
  devtools.tools.setResourceTrackingEnabled(true, always);
}

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.disableResourceTracking =
    function(always) {
  devtools.tools.setResourceTrackingEnabled(false, always);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.currentCallFrame = function() {
  return devtools.tools.getDebuggerAgent().getCurrentCallFrame();
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

devtools.InspectorControllerImpl.prototype.storeLastActivePanel =
    function(panel) {
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(undefined),
      'InspectorController', JSON.stringify(['storeLastActivePanel', panel]));
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInjectedScriptDelegate_ =
    function(methodName) {
  this[methodName] = goog.bind(this.callInjectedScript_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInjectedScript_ =
    function(methodName, var_arg) {
  var allArgs = Array.prototype.slice.call(arguments);
  var callback = allArgs[allArgs.length - 1];
  var args = Array.prototype.slice.call(allArgs, 0, allArgs.length - 1);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.InspectorControllerImpl.parseWrap_(callback),
      'InjectedScript', JSON.stringify(args));
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments);
  RemoteToolsAgent.ExecuteUtilityFunction(
      devtools.Callback.wrap(function(){}),
      'InspectorController', JSON.stringify(args));
};

devtools.InspectorControllerImpl.parseWrap_ = function(callback) {
  return devtools.Callback.wrap(
      function(data) {
        callback.call(this, JSON.parse(data));
      });
};

InspectorController = new devtools.InspectorControllerImpl();
<|endoftext|>


<commit_before>"use strict";

class TableController {
  constructor(table, fixtures) {
    this.table = table;
    this.fixtures = fixtures;
    this.tableCopy = [];
    this.output = [];
    this.outcomes = [
      [3, 0],  // home win
      [1, 1],  // draw
      [0, 3]  // home loss
    ];
  }

  /*
  * Tie break criteria:
  * 1. Points
  * 2. Name
  *
  * TODO: Add more realistic criteria like GD / Head-to-Head, GF, GA, etc.
  * This is also league specific
  */
  tieBreaker(a, b) {
    if (a.points === b.points) {
      return a.team.localeCompare(b.team);  // alphabetical order (asc)
    }
    return b.points - a.points;  // points order (desc)
  }

  validate() {
    // TODO make sure the table and fixtures are consistent
    return true;
  }

  validateTable(table) {
    if (!Array.isArray(table)) {
      return false;
    }
    for (let i=0; i<table.length; i++) {
      let elem = table[i];
      if (!elem.team || (typeof elem.team !== 'string')) {
        return false;
      }
      if (!elem.points || (typeof elem.points !== 'number')) {
        return false;
      }
    }
    return true;
  }

  validateFixtures(fixtures) {
    if (!Array.isArray(fixtures)) {
      return false;
    }
    for (let i=0; i<fixtures.length; i++) {
      let fixture = fixtures[i];
      if (!fixture.homeTeam || typeof fixture.homeTeam != 'string') {
        return false;
      }
      if (!fixture.awayTeam || typeof fixture.awayTeam != 'string') {
        return false;
      }
    }
    return true;
  }

  initOutput() {
    this.table.sort(this.tieBreaker);
    this.tableCopy = JSON.parse(JSON.stringify(this.table));
    this.output = [];
    let output = this.output;
    this.table.forEach(function(elem, index) {
      let outputElem = JSON.parse(JSON.stringify(elem));
      outputElem.currPos = index + 1;
      outputElem.highestPos = index + 1;
      outputElem.lowestPos = index + 1;
      output.push(outputElem);
    });
  }

  // Main routine
  project(index) {
    if (index >= this.fixtures.length) {
      return;
    }

    let currFixture = this.fixtures[index];
    for (let points of this.outcomes) {
      // TODO trim search tree if this result doesn't affect the table
      this.recordResult(currFixture, points);
      this.updatePositions();
      this.project(index + 1);
      this.undoResult(currFixture, points);
    }
  }

  updatePositions() {
    let output = this.output;
    this.tableCopy.forEach(function(elem, index) {
      let outputTeam = output.find(function(outputElem) {
        return outputElem.team === elem.team;
      });
      let currPos = index + 1;
      outputTeam.highestPos = Math.min(currPos, outputTeam.highestPos);
      outputTeam.lowestPos = Math.max(currPos, outputTeam.lowestPos);
    });
  }

  recordResult(fixture, points) {
    let homeTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.homeTeam;
    });
    let awayTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.awayTeam;
    });
    homeTeam.points += points[0];
    awayTeam.points += points[1];
    this.tableCopy.sort(this.tieBreaker);
  };

  undoResult(fixture, points) {
    let homeTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.homeTeam;
    });
    let awayTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.awayTeam;
    });
    homeTeam.points -= points[0];
    awayTeam.points -= points[1];
    this.tableCopy.sort(this.tieBreaker);
  };
}

module.exports = TableController;<commit_msg>Fix comment<commit_after>"use strict";

class TableController {
  constructor(table, fixtures) {
    this.table = table;
    this.fixtures = fixtures;
    this.tableCopy = [];
    this.output = [];
    this.outcomes = [
      [3, 0],  // home win
      [1, 1],  // draw
      [0, 3]  // home loss
    ];
  }

  /*
  * Tie break criteria:
  * 1. Name
  *
  * TODO: Add more realistic criteria like GD / Head-to-Head, GF, GA, etc.
  * This is also league specific
  */
  tieBreaker(a, b) {
    if (a.points === b.points) {
      return a.team.localeCompare(b.team);  // alphabetical order (asc)
    }
    return b.points - a.points;  // points order (desc)
  }

  validate() {
    // TODO make sure the table and fixtures are consistent
    return true;
  }

  validateTable(table) {
    if (!Array.isArray(table)) {
      return false;
    }
    for (let i=0; i<table.length; i++) {
      let elem = table[i];
      if (!elem.team || (typeof elem.team !== 'string')) {
        return false;
      }
      if (!elem.points || (typeof elem.points !== 'number')) {
        return false;
      }
    }
    return true;
  }

  validateFixtures(fixtures) {
    if (!Array.isArray(fixtures)) {
      return false;
    }
    for (let i=0; i<fixtures.length; i++) {
      let fixture = fixtures[i];
      if (!fixture.homeTeam || typeof fixture.homeTeam != 'string') {
        return false;
      }
      if (!fixture.awayTeam || typeof fixture.awayTeam != 'string') {
        return false;
      }
    }
    return true;
  }

  initOutput() {
    this.table.sort(this.tieBreaker);
    this.tableCopy = JSON.parse(JSON.stringify(this.table));
    this.output = [];
    let output = this.output;
    this.table.forEach(function(elem, index) {
      let outputElem = JSON.parse(JSON.stringify(elem));
      outputElem.currPos = index + 1;
      outputElem.highestPos = index + 1;
      outputElem.lowestPos = index + 1;
      output.push(outputElem);
    });
  }

  // Main routine
  project(index) {
    if (index >= this.fixtures.length) {
      return;
    }

    let currFixture = this.fixtures[index];
    for (let points of this.outcomes) {
      // TODO trim search tree if this result doesn't affect the table
      this.recordResult(currFixture, points);
      this.updatePositions();
      this.project(index + 1);
      this.undoResult(currFixture, points);
    }
  }

  updatePositions() {
    let output = this.output;
    this.tableCopy.forEach(function(elem, index) {
      let outputTeam = output.find(function(outputElem) {
        return outputElem.team === elem.team;
      });
      let currPos = index + 1;
      outputTeam.highestPos = Math.min(currPos, outputTeam.highestPos);
      outputTeam.lowestPos = Math.max(currPos, outputTeam.lowestPos);
    });
  }

  recordResult(fixture, points) {
    let homeTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.homeTeam;
    });
    let awayTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.awayTeam;
    });
    homeTeam.points += points[0];
    awayTeam.points += points[1];
    this.tableCopy.sort(this.tieBreaker);
  };

  undoResult(fixture, points) {
    let homeTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.homeTeam;
    });
    let awayTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.awayTeam;
    });
    homeTeam.points -= points[0];
    awayTeam.points -= points[1];
    this.tableCopy.sort(this.tieBreaker);
  };
}

module.exports = TableController;<|endoftext|>


<commit_before>'use strict';

//Menu service used for managing  menus
angular.module('core').service('Menus', [
	function() {
		// Define a set of default roles
		this.defaultRoles = ['user'];

		// Define the menus object
		this.menus = {};

		// A private function for rendering decision
		var shouldRender = function(user) {
			if(user) {
				for (var userRoleIndex in user.roles) {
					for (var roleIndex in this.roles) {
						if(this.roles[roleIndex] === user.roles[userRoleIndex]) {
							return true;
						}
					}
				}
			} else {
				return this.isPublic;
			}

			return false;
		};

		// Validate menu existance
		this.validateMenuExistance = function(menuId) {
			if (menuId && menuId.length) {
				if (this.menus[menuId]) {
					return true;
				} else {
					throw new Error('Menu does not exists');
				}
			} else {
				throw new Error('MenuId was not provided');
			}

			return false;
		};

		// Get the menu object by menu id
		this.getMenu = function(menuId) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Return the menu object
			return this.menus[menuId];
		};

		// Add new menu object by menu id
		this.addMenu = function(menuId, isPublic, roles) {
			// Create the new menu
			this.menus[menuId] = {
				isPublic: isPublic || false,
				roles: roles || this.defaultRoles,
				items: [],
				shouldRender: shouldRender
			};

			// Return the menu object
			return this.menus[menuId];
		};

		// Remove existing menu object by menu id
		this.removeMenu = function(menuId) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Return the menu object
			delete this.menus[menuId];
		};

		// Add menu item object
		this.addMenuItem = function(menuId, menuItemTitle, menuItemURL, menuClass, menuItemUIRoute, isPublic, roles) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Push new menu item
			this.menus[menuId].items.push({
				class: (menuClass === 'dropdown') ? menuClass : '',
				title: menuItemTitle,
				link: menuItemURL,
				uiRoute: menuItemUIRoute || ('/' + menuItemURL),
				isPublic: isPublic || this.menus[menuId].isPublic,
				roles: roles || this.defaultRoles,
                		subitems: [],
				shouldRender: shouldRender
			});

			// Return the menu object
			return this.menus[menuId];
		};

		// Add submenu item object
	        this.addSubMenuItem = function(menuId, rootMenuItemURL, menuItemTitle, menuItemURL, menuItemUIRoute, isPublic, roles) {
	            // Validate that the menu exists
	            this.validateMenuExistance(menuId);

	            // Search for menu item
	            for (var itemIndex in this.menus[menuId].items) {
	                if (this.menus[menuId].items[itemIndex].link === rootMenuItemURL) {
	                    // Push new submenu item
	                    this.menus[menuId].items[itemIndex].subitems.push({
	                        title: menuItemTitle,
	                        link: menuItemURL,
	                        uiRoute: menuItemUIRoute || ('/' + menuItemURL),
	                        isPublic: isPublic || this.menus[menuId].isPublic,
	                        roles: roles || this.defaultRoles,
	                        shouldRender: shouldRender
	                    });
	                }
	            }

	            // Return the menu object
	            return this.menus[menuId];
	        };

		// Remove existing menu object by menu id
		this.removeMenuItem = function(menuId, menuItemURL) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Search for menu item to remove
			for (var itemIndex in this.menus[menuId].items) {
				if (this.menus[menuId].items[itemIndex].link === menuItemURL) {
					this.menus[menuId].items.splice(itemIndex, 1);
				}
			}

			// Return the menu object
			return this.menus[menuId];
		};

		// Remove existing menu object by menu id
	        this.removeSubMenuItem = function(menuId, submenuItemURL) {
	            // Validate that the menu exists
	            this.validateMenuExistance(menuId);

	            // Search for menu item to remove
	            for (var itemIndex in this.menus[menuId].items) {
	                for (var subitemIndex in this.menus[menuId].items[itemIndex].subitems) {
	                    if (this.menus[menuId].items[itemIndex].subitems[subitemIndex].link === submenuItemURL) {
	                        this.menus[menuId].items[itemIndex].subitems.splice(subitemIndex, 1);
	                    }
	                }
	            }

	            // Return the menu object
	            return this.menus[menuId];
	        };

		//Adding the topbar menu
		this.addMenu('topbar');
	}
]);
<commit_msg>minor change on addMenuItem<commit_after>'use strict';

//Menu service used for managing  menus
angular.module('core').service('Menus', [
	function() {
		// Define a set of default roles
		this.defaultRoles = ['user'];

		// Define the menus object
		this.menus = {};

		// A private function for rendering decision
		var shouldRender = function(user) {
			if(user) {
				for (var userRoleIndex in user.roles) {
					for (var roleIndex in this.roles) {
						if(this.roles[roleIndex] === user.roles[userRoleIndex]) {
							return true;
						}
					}
				}
			} else {
				return this.isPublic;
			}

			return false;
		};

		// Validate menu existance
		this.validateMenuExistance = function(menuId) {
			if (menuId && menuId.length) {
				if (this.menus[menuId]) {
					return true;
				} else {
					throw new Error('Menu does not exists');
				}
			} else {
				throw new Error('MenuId was not provided');
			}

			return false;
		};

		// Get the menu object by menu id
		this.getMenu = function(menuId) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Return the menu object
			return this.menus[menuId];
		};

		// Add new menu object by menu id
		this.addMenu = function(menuId, isPublic, roles) {
			// Create the new menu
			this.menus[menuId] = {
				isPublic: isPublic || false,
				roles: roles || this.defaultRoles,
				items: [],
				shouldRender: shouldRender
			};

			// Return the menu object
			return this.menus[menuId];
		};

		// Remove existing menu object by menu id
		this.removeMenu = function(menuId) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Return the menu object
			delete this.menus[menuId];
		};

		// Add menu item object
		this.addMenuItem = function(menuId, menuItemTitle, menuItemURL, menuClass, menuItemUIRoute, isPublic, roles) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Push new menu item
			this.menus[menuId].items.push({
				title: menuItemTitle,
				link: menuItemURL,
				class: menuClass || '',
				uiRoute: menuItemUIRoute || ('/' + menuItemURL),
				isPublic: isPublic || this.menus[menuId].isPublic,
				roles: roles || this.defaultRoles,
                		subitems: [],
				shouldRender: shouldRender
			});

			// Return the menu object
			return this.menus[menuId];
		};

		// Add submenu item object
	        this.addSubMenuItem = function(menuId, rootMenuItemURL, menuItemTitle, menuItemURL, menuItemUIRoute, isPublic, roles) {
	            // Validate that the menu exists
	            this.validateMenuExistance(menuId);

	            // Search for menu item
	            for (var itemIndex in this.menus[menuId].items) {
	                if (this.menus[menuId].items[itemIndex].link === rootMenuItemURL) {
	                    // Push new submenu item
	                    this.menus[menuId].items[itemIndex].subitems.push({
	                        title: menuItemTitle,
	                        link: menuItemURL,
	                        uiRoute: menuItemUIRoute || ('/' + menuItemURL),
	                        isPublic: isPublic || this.menus[menuId].isPublic,
	                        roles: roles || this.defaultRoles,
	                        shouldRender: shouldRender
	                    });
	                }
	            }

	            // Return the menu object
	            return this.menus[menuId];
	        };

		// Remove existing menu object by menu id
		this.removeMenuItem = function(menuId, menuItemURL) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Search for menu item to remove
			for (var itemIndex in this.menus[menuId].items) {
				if (this.menus[menuId].items[itemIndex].link === menuItemURL) {
					this.menus[menuId].items.splice(itemIndex, 1);
				}
			}

			// Return the menu object
			return this.menus[menuId];
		};

		// Remove existing menu object by menu id
	        this.removeSubMenuItem = function(menuId, submenuItemURL) {
	            // Validate that the menu exists
	            this.validateMenuExistance(menuId);

	            // Search for menu item to remove
	            for (var itemIndex in this.menus[menuId].items) {
	                for (var subitemIndex in this.menus[menuId].items[itemIndex].subitems) {
	                    if (this.menus[menuId].items[itemIndex].subitems[subitemIndex].link === submenuItemURL) {
	                        this.menus[menuId].items[itemIndex].subitems.splice(subitemIndex, 1);
	                    }
	                }
	            }

	            // Return the menu object
	            return this.menus[menuId];
	        };

		//Adding the topbar menu
		this.addMenu('topbar');
	}
]);
<|endoftext|>


<commit_before>/*
 *  error.js
 *
 *  David Janes
 *  IOTDB.org
 *  2014-05-18
 *
 *  Copyright [2013-2016] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const _ = require("../helpers");

const message = function(error, otherwise) {
    if (error && (error.package === "seneca")) {
        return message({
            message: error.code,
        }, otherwise)
    }

    if (error && error.message) {
        return error.message;
    } else if (_.is.String(error)) {
        return error;
    } else if (error && error.name) {
        return error.name;
    } else if (otherwise) {
        return otherwise;
    } else {
        return null;
    }
};

const status = function(error, otherwise) {
    if (error && (error.package === "seneca")) {
        return code({
            message: error.code,
        }, otherwise)
    }

    if (error && error.statusCode && _.is.Number(error.statusCode)) {
        return error.statusCode;
    } else if (error && error.status && _.is.Number(error.status)) {
        return error.status;
    } else if (otherwise) {
        return otherwise;
    } else {
        return 500;
    }
};

/**
 *  This is a unique String identitier telling what an error is.
 */
const code_id = function(error, otherwise) {
    if (error && error.code_id) {
        return error.code_id;
    } else {
        return null;
    }
};

/**
 *  Which group does a the Status Code fall into, e.g. 2, 3, 4 or 5
 */
const group = function(error, otherwise) {
    return Math.floor(status(error, otherwise) / 100);
};

exports.error = {
    message: message,
    code: status,       // obsolete
    code_id: code_id,
    status: status,
    group: group
};
<commit_msg>generic error logger<commit_after>/*
 *  error.js
 *
 *  David Janes
 *  IOTDB.org
 *  2014-05-18
 *
 *  Copyright [2013-2016] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const _ = require("../helpers");

const message = function(error, otherwise) {
    if (error && (error.package === "seneca")) {
        return message({
            message: error.code,
        }, otherwise)
    }

    if (error && error.message) {
        return error.message;
    } else if (_.is.String(error)) {
        return error;
    } else if (error && error.name) {
        return error.name;
    } else if (otherwise) {
        return otherwise;
    } else {
        return null;
    }
};

const status = function(error, otherwise) {
    if (error && (error.package === "seneca")) {
        return code({
            message: error.code,
        }, otherwise)
    }

    if (error && error.statusCode && _.is.Number(error.statusCode)) {
        return error.statusCode;
    } else if (error && error.status && _.is.Number(error.status)) {
        return error.status;
    } else if (otherwise) {
        return otherwise;
    } else {
        return 500;
    }
};

/**
 *  This is a unique String identitier telling what an error is.
 */
const code_id = function(error, otherwise) {
    if (error && error.code_id) {
        return error.code_id;
    } else {
        return null;
    }
};

/**
 *  Which group does a the Status Code fall into, e.g. 2, 3, 4 or 5
 */
const group = function(error, otherwise) {
    return Math.floor(status(error, otherwise) / 100);
};

/**
 */
const log = error => {
    console.log("#", message(error))

    if (error.self && error.self.verbose) {
        console.trace()
    }
}

exports.error = {
    message: message,
    code: status,       // obsolete
    code_id: code_id,
    status: status,
    group: group,
    log: log,
};
<|endoftext|>


<commit_before>var React = require('react/addons');
var blacklist = require('blacklist');
var classNames = require('classnames');

var FormField = require('./FormField');
var Spinner = require('./Spinner');
var icons = require('../Octicons').map;

var COLOR_VARIANTS = ['danger', 'default', 'primary', 'success', 'warning'];

module.exports = React.createClass({
	displayName: 'FormIconField',
	propTypes: {
		className: React.PropTypes.string,
		iconColor: React.PropTypes.oneOf(COLOR_VARIANTS),
		iconFill: React.PropTypes.oneOf(COLOR_VARIANTS),
		iconIsLoading: React.PropTypes.bool,
		iconKey: React.PropTypes.string.isRequired,
		iconPosition: React.PropTypes.oneOf(['left', 'right'])
	},
	getDefaultProps() {
		return {
			iconPosition: 'left'
		};
	},
	render() {
		// props
		var props = blacklist(this.props, 'className', 'iconPosition', 'iconKey', 'iconFill', 'iconColor', 'iconIsLoading');

		// classes
		var fieldClass = classNames('IconField', {
				'has-fill-icon': this.props.iconFill,
				'is-loading-icon': this.props.iconIsLoading
			},
			(this.props.iconFill ? ('field-context-' + this.props.iconFill) : null),
			(this.props.iconColor ? ('field-context-' + this.props.iconColor) : null),
			this.props.iconPosition);

		var iconClass = classNames(
			'IconField__icon',
			(this.props.iconFill ? 'IconField__icon-fill--' + this.props.iconFill : null),
			(this.props.iconColor ? 'IconField__icon-color--' + this.props.iconColor : null),
			icons[this.props.iconKey].className,
			this.props.className
		);

		var icon = this.props.iconIsLoading ? (
			<Spinner size="sm" />
		) : (

		);

		return (
			<FormField {...props}>

					{this.props.children}
					{icon}

			</FormField>
		);
	}
});
<commit_msg>FormIconField: pass className through to the FormField<commit_after>var React = require('react/addons');
var blacklist = require('blacklist');
var classNames = require('classnames');

var FormField = require('./FormField');
var Spinner = require('./Spinner');
var icons = require('../Octicons').map;

var COLOR_VARIANTS = ['danger', 'default', 'primary', 'success', 'warning'];

module.exports = React.createClass({
	displayName: 'FormIconField',
	propTypes: {
		className: React.PropTypes.string,
		iconColor: React.PropTypes.oneOf(COLOR_VARIANTS),
		iconFill: React.PropTypes.oneOf(COLOR_VARIANTS),
		iconIsLoading: React.PropTypes.bool,
		iconKey: React.PropTypes.string.isRequired,
		iconPosition: React.PropTypes.oneOf(['left', 'right'])
	},
	getDefaultProps() {
		return {
			iconPosition: 'left'
		};
	},
	render() {
		// props
		var props = blacklist(this.props, 'children', 'iconPosition', 'iconKey', 'iconFill', 'iconColor', 'iconIsLoading');

		// classes
		var fieldClass = classNames('IconField', {
				'has-fill-icon': this.props.iconFill,
				'is-loading-icon': this.props.iconIsLoading
			},
			(this.props.iconFill ? ('field-context-' + this.props.iconFill) : null),
			(this.props.iconColor ? ('field-context-' + this.props.iconColor) : null),
			this.props.iconPosition);

		var iconClass = classNames(
			'IconField__icon',
			(this.props.iconFill ? 'IconField__icon-fill--' + this.props.iconFill : null),
			(this.props.iconColor ? 'IconField__icon-color--' + this.props.iconColor : null),
			icons[this.props.iconKey].className
		);

		var icon = this.props.iconIsLoading ? (
			<Spinner size="sm" />
		) : (

		);

		return (
			<FormField {...props}>

					{this.props.children}
					{icon}

			</FormField>
		);
	}
});
<|endoftext|>


<commit_before>/*
    Created by: Casey Cabrales
    8/13/16

    In reference to tutorial at http://blog.alexanderdickson.com/javascript-chip-8-emulator
    by Alexander Dickson.
 */

class Chip8 {

    constructor() {
        this.displayHeight = DISPLAY_HEIGHT;
        this.displayWidth = DISPLAY_WIDTH;
        this.display = new Array(displayHeight * displayWidth);

        this.step = null;
        this.running = null;

        let mem = new ArrayBuffer(MEM_SIZE);
        this.memory = new Uint8Array(mem);

        this.stack = new Array(16);
        this.sp = null;
        this.v = new Uint8Array(16);
        this.i = null;
        this.delayTimer = null;
        this.delayTimer = null;

        this.renderer = null;
        this.keys = {};

        this.reset();
    }

    // Load the program into memory
    loadProgram(program) {
        for (let i = 0; i < program.length; i++) {
            this.memory[i + DEFAULT_PC] = program[i];
        }
    }

    setRenderer(renderer) {
        this.renderer = renderer;
    }

    setKey(key) {
        this.keys[key] = true;
    }

    unsetKey(key) {
        this.keys[key] = false;
    }

    //TODO
    setPixel(x, y) {

    }

    // Main loop that emulates the device cycles
    requestAnimFrame() {
        for (let i = 0; i < NUM_CYCLES; i++) {
            if (this.running) {
                this.cycle();
            }
        }

        if (this.shouldDraw) {
            this.renderer.render(this.display);
            this.shouldDraw = false;
        }

        if (this.step % 2 === 0) {
            this.step++;
            if (this.delayTimer > 0) {
                this.delayTimer--;
            }
            if (this.soundTimer > 0) {
                this.soundTimer--;
                if (this.soundTimer === 0) {
                    this.renderer.beep();
                }
            }
        }

        window.requestAnimationFrame(this.requestAnimFrame);
    }

    start() {
        this.running = true;

        window.requestAnimationFrame(this.requestAnimFrame);
    }

    stop() {
        this.running = false;
    }

    cycle() {
        // Able to read as a single number when joining them
        let opCode = this.memory[this.pc] << 8 | this.memory[this.pc + 1];
        let x = (opCode & 0x0F00) >> 8;
        let y = (opCode & 0x00F0) >> 4;

        // Increment pc by 2 and decrement sound and delay
        this.pc += 2;

        // Read the first portion to classify the code, then can nest further for more classification
        switch (opCode & 0xF000) {
            case 0x0000:

                switch (opCode) {
                    // CLS - Clear Screen
                        // clear renderer and reset display
                    case 0x00E0:
                        this.renderer.clear();
                        for (let i = 0; i < this.display.length; i++) {
                            this.display[i] = 0;
                        }
                        break;

                    // RET - Return from subroutine
                    case 0x00EE:
                        this.pc = stack[--this.sp];
                        break;

                }
                break;

            // JP address
                // jump to address 1NNN
            case 0x1000:
                this.pc = opCode & 0xFFF;
                break;

            // CALL subroutine
                // call at 2NNN
            case 0x2000:
                this.stack[this.sp] = this.pc;
                this.sp++;
                this.pc = opCode & 0xFFF;
                break;

            // SE 3XNN
                // skip next instruction if Vx == NN
            case 0x3000:
                if (this.v[x] === (opCode & 0xFF)) {
                    this.pc += 2;
                }
                break;

            // SNE 4XNN
                // skip next instruction if Vx != NN
            case 0x4000:
                if (this.v[x] !== (opCode & 0x00FF)) {
                    this.pc += 2;
                }
                break;

            // SE 5XY0
                // skips next instruction if Vx === Vy
            case 0x5000:
                if (this.v[x] === this.v[y]) {
                    this.pc += 2;
                }
                break;

            // LD 6XNN
                // sets Vx to NN
            case 0x6000:
                this.v[x] = (opCode & 0xFF);
                break;

            // ADD 7XNN
                // add NN to Vx
            case 0x7000:
                let calc = this.v[x] + (opCode & 0xFF);
                // Prevent overflow
                if (calc > 255) {
                    calc -= 256;
                }
                this.v[x] = calc;
                break;

            case 0x8000:
                switch (opCode & 0x000F) {
                    // LD 8XY0
                        // set Vx to Vy
                    case 0x0000:
                        this.v[x] = this.v[y];
                        break;

                    // OR 8XY1
                        // set Vx to Vx OR Vy
                    case 0x0001:
                        this.v[x] |= this.v[y];
                        break;

                    // AND 8XY2
                        // set Vx to Vx AND Vy
                    case 0x0002:
                        this.v[x] &= this.v[y];
                        break;

                    // XOR 8XY3
                        // set Vx to Vx XOR Vy
                    case 0x0003:
                        this.v[x] ^= this.v[y];
                        break;

                    // ADD 8XY4
                        // adds Vy to Vx. VF is set to 1 when there's a carry, 0 otherwise
                    case 0x0004:
                        this.v[x] += this.v[y];
                        this.v[0xF] = +(this.v[x] > 255);

                        if (this.v[x] > 255) {
                            this.v[x] -= 256;
                        }
                        break;

                    // SUB 8XY5
                        // subtract Vy from Vx. VF is set to 0 when there's a borrow, 0 otherwise
                    case 0x0005:
                        this.v[0xF] = +(this.v[x] > this.v[y]);
                        this.v[x] -= this.v[y];
                        if (this.v[x] < 0) {
                            this.v[x] += 256;
                        }
                        break;

                    // SHR 8XY6
                        // shift Vx right by one. VF is set to least significant bit of Vx before the shift
                    case 0x0006:
                        this.v[0xF] = this.v[x] & 0x1;
                        this.v[x] >>= 1;
                        break;

                    // SUBN 8XY7
                        // set Vx to Vy - Vx. VF is set to 0 when there's a borrow, 1 otherwise
                    case 0x0007:
                        this.v[0xF] = +(this.v[x] > this.v[y]);
                        this.v[x] = this.v[y] = this.v[x];
                        if (this.v[x] < 0) {
                            this.v[x] += 256;
                        }
                        break;

                    // SHL 8XYE
                        // shift Vx left by one. VF set to most significant bit of Vx before shift
                    case 0x000E:
                        this.v[0xF] = this.v[x] & 0x8;
                        this.v[x] <<= 1;
                        break;
                }
                break;

            // SNE 9XY0
                // skips next instruction if Vx != Vy
            case 0x9000:
                if (this.v[x] !== this.v[y]) {
                    this.pc += 2;
                }
                break;

            // LD I ANNN
                // sets I to address NNN
            case 0xA000:
                this.i = opCode & 0xFFF;
                break;

            // JP V0 BNNN
                // jumps to address NNN + V0
            case 0xB000:
                this.pc = (opCode & 0xFFF) + this.v[0];
                break;

            // RND CXNN
                // set Vx to result of AND on a random number and NN
            case 0xC000:
                this.v[x] = Math.floor(Math.random() * 0xFF) & (opCode & 0xFF);
                break;

            // DRW DXYN
                // draws a sprite at coordinate (Vx, Vy) with a width of 8 pixels and height of N pixels
                // each row of 8 pixels is read as a bit-coded starting from memory location I
                // VF is set to 1 if any screen pixels are flipped from set to unset when the sprite is drawn, 0 otherwise
            // TODO
            case 0xD000:
                let width = 8;
                let height = opCode & 0x000F;
                this.v[0xF] = 0;

                // for (let )
                // this.shouldDraw = true;
                break;

            case 0xE000:
                switch(opCode & 0x00FF) {

                    // SKP EX9E
                        // skips next instruction if the key stored in Vx is pressed
                    case 0x009E:
                        if (this.keys[this.v[x]]) {
                            this.pc += 2;
                        }
                        break;

                    // SKNP EXA1
                        // skips next instruction if the key stored in Vx is not pressed
                    case 0x00A1:
                        if (!this.keys[this.v[x]]) {
                            this.pc += 2;
                        }
                        break;
                }
                break;

            case 0xF000:
                switch(opCode & 0x00FF) {

                    // LD FX07
                        // set Vx to value of delay timer
                    case 0x0007:
                        this.v[x] =  this.delayTimer;
                        break;

                    // LD FX0A
                        // wait for key press, then store in Vx
                        //TODO
                    case 0x000A:
                        let oldKey = this.setKey;
                        this.setKey = (key) => {
                            this.v[x] = key;
                        }
                        break;

                    // LD FX15
                        // sets delay timer to Vx
                    case 0x0015:
                        this.delayTimer = this.v[x];
                        break;

                    // LD FX18
                        // sets sound timer to Vx
                    case 0x0018:
                        this.soundTimer = this.v[x];
                        break;

                    // ADD I FX1E
                        // adds Vx to I
                    case 0x001E:
                        this.i += this.v[x];
                        break;

                    // LD F FX29
                        // sets I to the location of the sprite for the character in Vx
                        // characters 0-F are represented by a 4x5 font
                    case 0x0029:
                        this.i = this.v[x] * 5;
                        break;

                    // LD B FX33
                        // stores binary representation of Vx in memory, with the most significant of three digits
                        // at addr in I, middle digit at I+1, LSB at I+2
                    case 0x0033:
                        var dec = this.v[x];

                        for (let i = this.i + 2; i >= this.i - 2; i--) {
                            this.memory[i] = parseInt(dec % 10);
                            dec /= 10;
                        }
                        break;

                    // LD [I] FX55
                        // stores V0 to Vx (inclusive) in memory address starting at address I
                    case 0x0055:
                        for (let i = 0; i <= x; i++) {
                            this.memory[this.i + i] = this.v[i];
                        }
                        break;

                    // LD Vx FX65
                        // fills V0 to Vx (inclusive) with values from memory starting at address I
                    case 0x0065:
                        for (let i = 0; i <= x; i++) {
                            this.v[i] = this.memory[this.i + i];
                        }
                        break;
                }
                break;
            default:
                throw new Error("Invalid opcode " + opCode.toString(16) + " received. Quitting now.");
        }
    }

    reset() {
        //Program Counter
        this.pc = DEFAULT_PC;

        // Memory
        for (let i = 0; i < MEM_SIZE; i++) {
            this.memory[i] = 0;
        }

        //Display
        for (let i = 0; i < display.length; i++) {
            this.display[i] = 0;
        }

        // Stack Pointer
        this.sp = 0;

        // "V" Registers
        for (let i = 0; i < this.v.length; i++) {
            v[i] = 0;
        }

        // "I" Register
        this.i = 0;

        // Delay Timer
        this.delayTimer = 0;

        // Sound Timer
        this.soundTimer = 0;

        this.step = 0;
        this.running = false;

        this.setupKeys();
    }

    setupKeys() {

    }
}<commit_msg>Pretty sure I got case 0xD000 correct (at least implemented for now)<commit_after>/*
    Created by: Casey Cabrales
    8/13/16

    In reference to tutorial at http://blog.alexanderdickson.com/javascript-chip-8-emulator
    by Alexander Dickson.
 */

class Chip8 {

    constructor() {
        this.displayHeight = DISPLAY_HEIGHT;
        this.displayWidth = DISPLAY_WIDTH;
        this.display = new Array(displayHeight * displayWidth);

        this.step = null;
        this.running = null;

        let mem = new ArrayBuffer(MEM_SIZE);
        this.memory = new Uint8Array(mem);

        this.stack = new Array(16);
        this.sp = null;
        this.v = new Uint8Array(16);
        this.i = null;
        this.delayTimer = null;
        this.delayTimer = null;

        this.renderer = null;
        this.keys = {};

        this.reset();
    }

    // Load the program into memory
    loadProgram(program) {
        for (let i = 0; i < program.length; i++) {
            this.memory[i + DEFAULT_PC] = program[i];
        }
    }

    setRenderer(renderer) {
        this.renderer = renderer;
    }

    setKey(key) {
        this.keys[key] = true;
    }

    unsetKey(key) {
        this.keys[key] = false;
    }

    //TODO
    setPixel(x, y) {

    }

    // Main loop that emulates the device cycles
    requestAnimFrame() {
        for (let i = 0; i < NUM_CYCLES; i++) {
            if (this.running) {
                this.cycle();
            }
        }

        if (this.shouldDraw) {
            this.renderer.render(this.display);
            this.shouldDraw = false;
        }

        if (this.step % 2 === 0) {
            this.step++;
            if (this.delayTimer > 0) {
                this.delayTimer--;
            }
            if (this.soundTimer > 0) {
                this.soundTimer--;
                if (this.soundTimer === 0) {
                    this.renderer.beep();
                }
            }
        }

        window.requestAnimationFrame(this.requestAnimFrame);
    }

    start() {
        this.running = true;

        window.requestAnimationFrame(this.requestAnimFrame);
    }

    stop() {
        this.running = false;
    }

    cycle() {
        // Able to read as a single number when joining them
        let opCode = this.memory[this.pc] << 8 | this.memory[this.pc + 1];
        let x = (opCode & 0x0F00) >> 8;
        let y = (opCode & 0x00F0) >> 4;

        // Increment pc by 2 and decrement sound and delay
        this.pc += 2;

        // Read the first portion to classify the code, then can nest further for more classification
        switch (opCode & 0xF000) {
            case 0x0000:

                switch (opCode) {
                    // CLS - Clear Screen
                        // clear renderer and reset display
                    case 0x00E0:
                        this.renderer.clear();
                        for (let i = 0; i < this.display.length; i++) {
                            this.display[i] = 0;
                        }
                        break;

                    // RET - Return from subroutine
                    case 0x00EE:
                        this.pc = stack[--this.sp];
                        break;

                }
                break;

            // JP address
                // jump to address 1NNN
            case 0x1000:
                this.pc = opCode & 0xFFF;
                break;

            // CALL subroutine
                // call at 2NNN
            case 0x2000:
                this.stack[this.sp] = this.pc;
                this.sp++;
                this.pc = opCode & 0xFFF;
                break;

            // SE 3XNN
                // skip next instruction if Vx == NN
            case 0x3000:
                if (this.v[x] === (opCode & 0xFF)) {
                    this.pc += 2;
                }
                break;

            // SNE 4XNN
                // skip next instruction if Vx != NN
            case 0x4000:
                if (this.v[x] !== (opCode & 0x00FF)) {
                    this.pc += 2;
                }
                break;

            // SE 5XY0
                // skips next instruction if Vx === Vy
            case 0x5000:
                if (this.v[x] === this.v[y]) {
                    this.pc += 2;
                }
                break;

            // LD 6XNN
                // sets Vx to NN
            case 0x6000:
                this.v[x] = (opCode & 0xFF);
                break;

            // ADD 7XNN
                // add NN to Vx
            case 0x7000:
                let calc = this.v[x] + (opCode & 0xFF);
                // Prevent overflow
                if (calc > 255) {
                    calc -= 256;
                }
                this.v[x] = calc;
                break;

            case 0x8000:
                switch (opCode & 0x000F) {
                    // LD 8XY0
                        // set Vx to Vy
                    case 0x0000:
                        this.v[x] = this.v[y];
                        break;

                    // OR 8XY1
                        // set Vx to Vx OR Vy
                    case 0x0001:
                        this.v[x] |= this.v[y];
                        break;

                    // AND 8XY2
                        // set Vx to Vx AND Vy
                    case 0x0002:
                        this.v[x] &= this.v[y];
                        break;

                    // XOR 8XY3
                        // set Vx to Vx XOR Vy
                    case 0x0003:
                        this.v[x] ^= this.v[y];
                        break;

                    // ADD 8XY4
                        // adds Vy to Vx. VF is set to 1 when there's a carry, 0 otherwise
                    case 0x0004:
                        this.v[x] += this.v[y];
                        this.v[0xF] = +(this.v[x] > 255);

                        if (this.v[x] > 255) {
                            this.v[x] -= 256;
                        }
                        break;

                    // SUB 8XY5
                        // subtract Vy from Vx. VF is set to 0 when there's a borrow, 0 otherwise
                    case 0x0005:
                        this.v[0xF] = +(this.v[x] > this.v[y]);
                        this.v[x] -= this.v[y];
                        if (this.v[x] < 0) {
                            this.v[x] += 256;
                        }
                        break;

                    // SHR 8XY6
                        // shift Vx right by one. VF is set to least significant bit of Vx before the shift
                    case 0x0006:
                        this.v[0xF] = this.v[x] & 0x1;
                        this.v[x] >>= 1;
                        break;

                    // SUBN 8XY7
                        // set Vx to Vy - Vx. VF is set to 0 when there's a borrow, 1 otherwise
                    case 0x0007:
                        this.v[0xF] = +(this.v[x] > this.v[y]);
                        this.v[x] = this.v[y] = this.v[x];
                        if (this.v[x] < 0) {
                            this.v[x] += 256;
                        }
                        break;

                    // SHL 8XYE
                        // shift Vx left by one. VF set to most significant bit of Vx before shift
                    case 0x000E:
                        this.v[0xF] = this.v[x] & 0x8;
                        this.v[x] <<= 1;
                        break;
                }
                break;

            // SNE 9XY0
                // skips next instruction if Vx != Vy
            case 0x9000:
                if (this.v[x] !== this.v[y]) {
                    this.pc += 2;
                }
                break;

            // LD I ANNN
                // sets I to address NNN
            case 0xA000:
                this.i = opCode & 0xFFF;
                break;

            // JP V0 BNNN
                // jumps to address NNN + V0
            case 0xB000:
                this.pc = (opCode & 0xFFF) + this.v[0];
                break;

            // RND CXNN
                // set Vx to result of AND on a random number and NN
            case 0xC000:
                this.v[x] = Math.floor(Math.random() * 0xFF) & (opCode & 0xFF);
                break;

            // DRW DXYN
                // draws a sprite at coordinate (Vx, Vy) with a width of 8 pixels and height of N pixels
                // each row of 8 pixels is read as a bit-coded starting from memory location I
                // VF is set to 1 if any screen pixels are flipped from set to unset when the sprite is drawn, 0 otherwise
            case 0xD000:
                let width = 8;
                let height = opCode & 0x000F;
                this.v[0xF] = 0;

                // Go row by row for outer loop, and inner loop go column by column
                for (let i = 0; i < height; i++) {
                    let sprite = this.memory[this.i + i];
                    for (let j = 0; j < width; j++) {
                        // check for whether highest bit is 1 and there is an overlap/flipping pixels b/c of it
                        if ((sprite & 0x80) > 0 && this.setPixel(this.v[x] + j, this.v[y] + i)) {
                            this.v[0xF] = 1;
                        }
                        sprite <<= 1; // shift left by one every iteration to get every bit as highest to test
                    }
                    this.shouldDraw = true;
                }
                break;

            case 0xE000:
                switch(opCode & 0x00FF) {

                    // SKP EX9E
                        // skips next instruction if the key stored in Vx is pressed
                    case 0x009E:
                        if (this.keys[this.v[x]]) {
                            this.pc += 2;
                        }
                        break;

                    // SKNP EXA1
                        // skips next instruction if the key stored in Vx is not pressed
                    case 0x00A1:
                        if (!this.keys[this.v[x]]) {
                            this.pc += 2;
                        }
                        break;
                }
                break;

            case 0xF000:
                switch(opCode & 0x00FF) {

                    // LD FX07
                        // set Vx to value of delay timer
                    case 0x0007:
                        this.v[x] =  this.delayTimer;
                        break;

                    // LD FX0A
                        // wait for key press, then store in Vx
                        //TODO
                    case 0x000A:
                        let oldKey = this.setKey;
                        this.setKey = (key) => {
                            this.v[x] = key;
                        }
                        break;

                    // LD FX15
                        // sets delay timer to Vx
                    case 0x0015:
                        this.delayTimer = this.v[x];
                        break;

                    // LD FX18
                        // sets sound timer to Vx
                    case 0x0018:
                        this.soundTimer = this.v[x];
                        break;

                    // ADD I FX1E
                        // adds Vx to I
                    case 0x001E:
                        this.i += this.v[x];
                        break;

                    // LD F FX29
                        // sets I to the location of the sprite for the character in Vx
                        // characters 0-F are represented by a 4x5 font
                    case 0x0029:
                        this.i = this.v[x] * 5;
                        break;

                    // LD B FX33
                        // stores binary representation of Vx in memory, with the most significant of three digits
                        // at addr in I, middle digit at I+1, LSB at I+2
                    case 0x0033:
                        var dec = this.v[x];

                        for (let i = this.i + 2; i >= this.i - 2; i--) {
                            this.memory[i] = parseInt(dec % 10);
                            dec /= 10;
                        }
                        break;

                    // LD [I] FX55
                        // stores V0 to Vx (inclusive) in memory address starting at address I
                    case 0x0055:
                        for (let i = 0; i <= x; i++) {
                            this.memory[this.i + i] = this.v[i];
                        }
                        break;

                    // LD Vx FX65
                        // fills V0 to Vx (inclusive) with values from memory starting at address I
                    case 0x0065:
                        for (let i = 0; i <= x; i++) {
                            this.v[i] = this.memory[this.i + i];
                        }
                        break;
                }
                break;
            default:
                throw new Error("Invalid opcode " + opCode.toString(16) + " received. Quitting now.");
        }
    }

    reset() {
        //Program Counter
        this.pc = DEFAULT_PC;

        // Memory
        for (let i = 0; i < MEM_SIZE; i++) {
            this.memory[i] = 0;
        }

        //Display
        for (let i = 0; i < display.length; i++) {
            this.display[i] = 0;
        }

        // Stack Pointer
        this.sp = 0;

        // "V" Registers
        for (let i = 0; i < this.v.length; i++) {
            v[i] = 0;
        }

        // "I" Register
        this.i = 0;

        // Delay Timer
        this.delayTimer = 0;

        // Sound Timer
        this.soundTimer = 0;

        this.step = 0;
        this.running = false;

        this.setupKeys();
    }

    setupKeys() {

    }
}<|endoftext|>


<commit_before>function (doc) {
    // !code util/mvp.js
    if(isChildVisitForm(doc)) {
        var indicators = get_indicators(doc);

        if (indicators.child_dob && indicators.child_dob.value) {
            var meta = doc.form.meta,
                indicator_entries = {},
                age = get_age_from_dob(indicators.child_dob.value, meta.timeEnd),
                visit_date = new Date(meta.timeEnd),
                case_id = get_case_id(doc);

            if (age >= 180*MS_IN_DAY && age < 1770*MS_IN_DAY && indicators.muac.value) {
                // MUAC reading taken during visit
                indicator_entries["muac_reading"] = 1;
                try {
                    var muac_value = parseFloat(indicators.muac.value);
                    if (muac_value < 125.0) {
                        indicator_entries["muac_wasting"] = 1;
                    }
                } catch (err) {
                    log("MUAC value could not be obtained");
                }

                if (doc.form.last_muac) {
                    var last_muac = new Date(doc.form.last_muac);
                    if (last_muac <= visit_date) {
                        var difference = visit_date.getTime() - last_muac.getTime();
                        if (difference <= 90*MS_IN_DAY){
                            indicator_entries["routine_muac"] = case_id;
                        }
                    }
                }
            }
            emit_special(doc, visit_date, indicator_entries, [doc._id]);
        }

    }
}
<commit_msg>greater than 180, not eq to<commit_after>function (doc) {
    // !code util/mvp.js
    if(isChildVisitForm(doc)) {
        var indicators = get_indicators(doc);

        if (indicators.child_dob && indicators.child_dob.value) {
            var meta = doc.form.meta,
                indicator_entries = {},
                age = get_age_from_dob(indicators.child_dob.value, meta.timeEnd),
                visit_date = new Date(meta.timeEnd),
                case_id = get_case_id(doc);

            if (age > 180*MS_IN_DAY && age < 1770*MS_IN_DAY && indicators.muac.value) {
                // MUAC reading taken during visit
                indicator_entries["muac_reading"] = 1;
                try {
                    var muac_value = parseFloat(indicators.muac.value);
                    if (muac_value < 125.0) {
                        indicator_entries["muac_wasting"] = 1;
                    }
                } catch (err) {
                    log("MUAC value could not be obtained");
                }

                if (doc.form.last_muac) {
                    var last_muac = new Date(doc.form.last_muac);
                    if (last_muac <= visit_date) {
                        var difference = visit_date.getTime() - last_muac.getTime();
                        if (difference <= 90*MS_IN_DAY){
                            indicator_entries["routine_muac"] = case_id;
                        }
                    }
                }
            }
            emit_special(doc, visit_date, indicator_entries, [doc._id]);
        }

    }
}
<|endoftext|>


<commit_before>/*! MIT License | github.com/kingalfred/canvas */

/*
 * Replace title
 */
if (document.title === 'Log in to canvas') {
  document.title = 'King Alfred School Canvas';
}

/*
 * Add "Check Homework button"
 */
if (window.location.href.indexOf('courses')) {
  var text = 'Calendar';
  var course = window.location.pathname.split('/')[2];

  $('#section-tabs').append(
    `

        ${text}

`
  );
}

/*
 * Parent's multiple children
 */
function addChooseChild() {

  // Add initial option selector
  $('#calendar_header').append(
    `
    <select id="calendar_children" onchange="location = this.value;">
      <option class="calendar_child">Select Option</option>
    </select>
    `
  );

  // Get user's children
  $.ajax({
    method: 'get',
    url: 'api/v1/users/self/observees?per_page=50',
    dataType: 'json'
  }).then(children => {
    if (children.length < 1) {
      $('#calendar_children').remove();
    }

    var counter = 1;
    // Each child...
    for (var child of children) {
      // Add child option
      $('#calendar_children').append(
        `
        <option class="calendar_child">${child.name}</option>
        `
      );
      // Get courses of that child
      $.ajax({
        method: 'get',
        url: '/api/v1/users/' + child.id + '/courses?per_page=20',
        dataType: 'json'
      }).then(courses => {
        // Create the calendar link
        var courseLinks = '/calendar?include_contexts=';

        // Add every course ID to the link
        for (var course of courses) {
          courseLinks += `course_${course.id},`;
        }

        // Add child option
        $('.calendar_child').eq(counter).attr('value', courseLinks);
        counter++;
      }).fail(err => {
        throw err;
      });
    }
  }).fail(err => {
    throw err;
  });
};

if (window.location.href.indexOf('calendar')) {
  addChooseChild();
}

/*
 * Change favicon of beta environment to green icon
 */
function changeFavicon(img) {
  var favicon = $('link[rel="shortcut icon"]');
  if (!favicon) $('head').append('<link rel="shortcut icon">');
  favicon.attr('type', 'image/png');
  favicon.attr('href', img);
}

if (window.location.hostname.indexOf('beta')) {
  changeFavicon('https://i.imgur.com/DpAI7L4.png');
}
<commit_msg>Fix bug with more than 3 children<commit_after>/*! MIT License | github.com/kingalfred/canvas */

/*
 * Replace title
 */
if (document.title === 'Log in to canvas') {
  document.title = 'King Alfred School Canvas';
}

/*
 * Add "Check Homework button"
 */
if (window.location.href.indexOf('courses')) {
  var text = 'Calendar';
  var course = window.location.pathname.split('/')[2];

  $('#section-tabs').append(
    `

        ${text}

`
  );
}

/*
 * Parent's multiple children
 */
function addChooseChild() {

  $.ajax({
    method: 'get',
    url: '/api/v1/users/self/observees?per_page=50',
    dataType: 'json'
  }).then(children => {
    var p = [];
    for (let child of children) {
      p.push(new Promise(function(resolve, reject) {
        $.ajax({
          method: 'get',
          url: '/api/v1/users/' + child.id + '/courses?per_page=20',
          dataType: 'json'
        }).then(courses => {
          var listCourses = [];
          for (var course of courses) {
            listCourses.push(course.id)
          }
          resolve({
            name: child.name,
            courses: listCourses
          });
        }).fail(err => {
          reject(err);
        });
      }));
    }
    Promise.all(p).then(res => {
      $('#calendar_header').append(`
        <select id="calendar_children" onchange="location = this.value;">
          <option class="calendar_child">Select Child</option>
          ${
            res.map(
              x => `<option class="calendar_child" value=${x.id}>${x.name}</option>`
            )
          }
        </select>
      `)
    })
  }).fail(err => {
    throw err;
  })

};

if (window.location.href.indexOf('calendar')) {
  addChooseChild();
}

/*
 * Change favicon of beta environment to green icon
 */
function changeFavicon(img) {
  var favicon = $('link[rel="shortcut icon"]');
  if (!favicon) $('head').append('<link rel="shortcut icon">');
  favicon.attr('type', 'image/png');
  favicon.attr('href', img);
}

if (window.location.hostname.indexOf('beta')) {
  changeFavicon('https://i.imgur.com/DpAI7L4.png');
}
<|endoftext|>