<commit_before>/**
 * Expose the MediaStreamRenderer class.
 */
module.exports = MediaStreamRenderer;

/**
 * Dependencies.
 */
var
	debug = require('debug')('iosrtc:MediaStreamRenderer'),
	exec = require('cordova/exec'),
	randomNumber = require('random-number').generator({min: 10000, max: 99999, integer: true}),
	EventTarget = require('./EventTarget'),
	MediaStream = require('./MediaStream');

function MediaStreamRenderer(element) {
	debug('new() | [element:"%s"]', element);

	var self = this;

	// Make this an EventTarget.
	EventTarget.call(this);

	if (!(element instanceof HTMLElement)) {
		throw new Error('a valid HTMLElement is required');
	}

	// Public atributes.
	this.element = element;
	this.stream = undefined;
	this.videoWidth = undefined;
	this.videoHeight = undefined;

	// Private attributes.
	this.id = randomNumber();

	function onResultOK(data) {
		onEvent.call(self, data);
	}

	exec(onResultOK, null, 'iosrtcPlugin', 'new_MediaStreamRenderer', [this.id]);

	this.refresh(this);
	this.refreshInterval = setInterval(function () {
		self.refresh(self);
	}, 500);

	element.render = this;
}

MediaStreamRenderer.prototype = Object.create(EventTarget.prototype);
MediaStreamRenderer.prototype.constructor = MediaStreamRenderer;

MediaStreamRenderer.prototype.render = function (stream) {
	debug('render() [stream:%o]', stream);

	var self = this;

	if (!(stream instanceof MediaStream.originalMediaStream)) {
		throw new Error('render() requires a MediaStream instance as argument');
	}

	this.stream = stream;

	exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_render', [this.id, stream.id]);

	// Subscribe to 'update' event so we call native mediaStreamChanged() on it.
	stream.addEventListener('update', function () {
		if (self.stream !== stream) {
			return;
		}

		debug('MediaStream emits "update", calling native mediaStreamChanged()');

		exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_mediaStreamChanged', [self.id]);
	});

	// Subscribe to 'inactive' event and emit "close" so the video element can react.
	stream.addEventListener('inactive', function () {
		if (self.stream !== stream) {
			return;
		}

		debug('MediaStream emits "inactive", emiting "close" and closing this MediaStreamRenderer');

		self.dispatchEvent(new Event('close'));
		self.close();
	});

	if (stream.connected) {
		connected();
	// Otherwise subscribe to 'connected' event to emulate video elements events.
	} else {
		stream.addEventListener('connected', function () {
			if (self.stream !== stream) {
				return;
			}

			connected();
		});
	}

	function connected() {
		// Emit video events.
		self.element.dispatchEvent(new Event('loadedmetadata'));
		self.element.dispatchEvent(new Event('loadeddata'));
		self.element.dispatchEvent(new Event('canplay'));
		self.element.dispatchEvent(new Event('canplaythrough'));
	}
};

MediaStreamRenderer.prototype.save = function (callback) {
	console.log("TakeScreen");
	debug('save()');

	if (!this.stream) {
		callback(null);
		return;
	}

	function onResultOK(data) {
		callback(data);
	}

	function onResultError() {
		callback(null);
	}

	exec(onResultOK, onResultError, 'iosrtcPlugin', 'MediaStreamRenderer_save', [this.id]);
};

MediaStreamRenderer.prototype.refresh = function () {
	debug('refresh()');

	var elementPositionAndSize = getElementPositionAndSize.call(this),
		computedStyle,
		videoRatio,
		elementRatio,
		elementLeft = elementPositionAndSize.left,
		elementTop = elementPositionAndSize.top,
		elementWidth = elementPositionAndSize.width,
		elementHeight = elementPositionAndSize.height,
		videoViewWidth,
		videoViewHeight,
		visible,
		opacity,
		zIndex,
		mirrored,
		objectFit,
		clip,
		borderRadius,
		paddingTop,
		paddingBottom,
		paddingLeft,
		paddingRight,
		self = this;

	computedStyle = window.getComputedStyle(this.element);

	// get padding values
	paddingTop = parseInt(computedStyle.paddingTop) | 0;
	paddingBottom = parseInt(computedStyle.paddingBottom) | 0;
	paddingLeft = parseInt(computedStyle.paddingLeft) | 0;
	paddingRight = parseInt(computedStyle.paddingRight) | 0;

	// fix position according to padding
	elementLeft += paddingLeft;
	elementTop += paddingTop;

	// fix width and height according to padding
	elementWidth -= (paddingLeft + paddingRight);
	elementHeight -= (paddingTop + paddingBottom);

	videoViewWidth = elementWidth;
	videoViewHeight = elementHeight;

	// visible
	if (computedStyle.visibility === 'hidden') {
		visible = false;
	} else {
		visible = !!this.element.offsetHeight;  // Returns 0 if element or any parent is hidden.
	}

	// opacity
	opacity = parseFloat(computedStyle.opacity);

	// zIndex
	zIndex = parseFloat(computedStyle.zIndex) || parseFloat(this.element.style.zIndex) || 0;

	// mirrored (detect "-webkit-transform: scaleX(-1);" or equivalent)
	if (computedStyle.transform === 'matrix(-1, 0, 0, 1, 0, 0)' ||
		computedStyle['-webkit-transform'] === 'matrix(-1, 0, 0, 1, 0, 0)') {
		mirrored = true;
	} else {
		mirrored = false;
	}

	// objectFit ('contain' is set as default value)
	objectFit = computedStyle.objectFit || 'contain';

	// clip
	if (objectFit === 'none') {
		clip = false;
	} else {
		clip = true;
	}

	// borderRadius
	borderRadius = parseFloat(computedStyle.borderRadius);
	if (/%$/.test(borderRadius)) {
		borderRadius = Math.min(elementHeight, elementWidth) * borderRadius;
	}

	/**
	 * No video yet, so just update the UIView with the element settings.
	 */

	if (!this.videoWidth || !this.videoHeight) {
		debug('refresh() | no video track yet');

		nativeRefresh.call(this);
		return;
	}

	videoRatio = this.videoWidth / this.videoHeight;

	/**
	 * Element has no width and/or no height.
	 */

	if (!elementWidth || !elementHeight) {
		debug('refresh() | video element has 0 width and/or 0 height');

		nativeRefresh.call(this);
		return;
	}

	/**
	 * Set video view position and size.
	 */

	elementRatio = elementWidth / elementHeight;

	switch (objectFit) {
		case 'cover':
			// The element has higher or equal width/height ratio than the video.
			if (elementRatio >= videoRatio) {
				videoViewWidth = elementWidth;
				videoViewHeight = videoViewWidth / videoRatio;
			// The element has lower width/height ratio than the video.
			} else if (elementRatio < videoRatio) {
				videoViewHeight = elementHeight;
				videoViewWidth = videoViewHeight * videoRatio;
			}
			break;

		case 'fill':
			videoViewHeight = elementHeight;
			videoViewWidth = elementWidth;
			break;

		case 'none':
			videoViewHeight = this.videoHeight;
			videoViewWidth = this.videoWidth;
			break;

		case 'scale-down':
			// Same as 'none'.
			if (this.videoWidth <= elementWidth && this.videoHeight <= elementHeight) {
				videoViewHeight = this.videoHeight;
				videoViewWidth = this.videoWidth;
			// Same as 'contain'.
			} else {
				// The element has higher or equal width/height ratio than the video.
				if (elementRatio >= videoRatio) {
					videoViewHeight = elementHeight;
					videoViewWidth = videoViewHeight * videoRatio;
				// The element has lower width/height ratio than the video.
				} else if (elementRatio < videoRatio) {
					videoViewWidth = elementWidth;
					videoViewHeight = videoViewWidth / videoRatio;
				}
			}
			break;

		// 'contain'.
		default:
			objectFit = 'contain';
			// The element has higher or equal width/height ratio than the video.
			if (elementRatio >= videoRatio) {
				videoViewHeight = elementHeight;
				videoViewWidth = videoViewHeight * videoRatio;
			// The element has lower width/height ratio than the video.
			} else if (elementRatio < videoRatio) {
				videoViewWidth = elementWidth;
				videoViewHeight = videoViewWidth / videoRatio;
			}
			break;
	}

	nativeRefresh.call(this);

	function hash(str) {
		var hash = 5381,
		i = str.length;

		while (i) {
			hash = (hash * 33) ^ str.charCodeAt(--i);
		}

		return hash >>> 0;
	}

	function nativeRefresh() {
		var data = {
			elementLeft: elementLeft,
			elementTop: elementTop,
			elementWidth: elementWidth,
			elementHeight: elementHeight,
			videoViewWidth: videoViewWidth,
			videoViewHeight: videoViewHeight,
			visible: visible,
			opacity: opacity,
			zIndex: zIndex,
			mirrored: mirrored,
			objectFit: objectFit,
			clip: clip,
			borderRadius: borderRadius
		},
		newRefreshCached = hash(JSON.stringify(data));

		if (newRefreshCached === self.refreshCached) {
			return;
		}

		self.refreshCached = newRefreshCached;

		debug('refresh() | [data:%o]', data);

		exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_refresh', [this.id, data]);
	}
};

MediaStreamRenderer.prototype.close = function () {
	debug('close()');

	if (!this.stream) {
		return;
	}
	this.stream = undefined;

	exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_close', [this.id]);
	if (this.refreshInterval) {
		clearInterval(this.refreshInterval);
		delete this.refreshInterval;
	}
};

/**
 * Private API.
 */

function onEvent(data) {
	var type = data.type,
		event;

	debug('onEvent() | [type:%s, data:%o]', type, data);

	switch (type) {
		case 'videoresize':
			this.videoWidth = data.size.width;
			this.videoHeight = data.size.height;
			this.refresh(this);

			event = new Event(type);
			event.videoWidth = data.size.width;
			event.videoHeight = data.size.height;
			this.dispatchEvent(event);

			break;
	}
}

function getElementPositionAndSize() {
	var rect = this.element.getBoundingClientRect();

	return {
		left:   rect.left + this.element.clientLeft,
		top:    rect.top + this.element.clientTop,
		width:  this.element.clientWidth,
		height: this.element.clientHeight
	};
}
<commit_msg>remove js/MediaStreamRenderer.js debug<commit_after>/**
 * Expose the MediaStreamRenderer class.
 */
module.exports = MediaStreamRenderer;

/**
 * Dependencies.
 */
var
	debug = require('debug')('iosrtc:MediaStreamRenderer'),
	exec = require('cordova/exec'),
	randomNumber = require('random-number').generator({min: 10000, max: 99999, integer: true}),
	EventTarget = require('./EventTarget'),
	MediaStream = require('./MediaStream');

function MediaStreamRenderer(element) {
	debug('new() | [element:"%s"]', element);

	var self = this;

	// Make this an EventTarget.
	EventTarget.call(this);

	if (!(element instanceof HTMLElement)) {
		throw new Error('a valid HTMLElement is required');
	}

	// Public atributes.
	this.element = element;
	this.stream = undefined;
	this.videoWidth = undefined;
	this.videoHeight = undefined;

	// Private attributes.
	this.id = randomNumber();

	function onResultOK(data) {
		onEvent.call(self, data);
	}

	exec(onResultOK, null, 'iosrtcPlugin', 'new_MediaStreamRenderer', [this.id]);

	this.refresh(this);
	this.refreshInterval = setInterval(function () {
		self.refresh(self);
	}, 500);

	element.render = this;
}

MediaStreamRenderer.prototype = Object.create(EventTarget.prototype);
MediaStreamRenderer.prototype.constructor = MediaStreamRenderer;

MediaStreamRenderer.prototype.render = function (stream) {
	debug('render() [stream:%o]', stream);

	var self = this;

	if (!(stream instanceof MediaStream.originalMediaStream)) {
		throw new Error('render() requires a MediaStream instance as argument');
	}

	this.stream = stream;

	exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_render', [this.id, stream.id]);

	// Subscribe to 'update' event so we call native mediaStreamChanged() on it.
	stream.addEventListener('update', function () {
		if (self.stream !== stream) {
			return;
		}

		debug('MediaStream emits "update", calling native mediaStreamChanged()');

		exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_mediaStreamChanged', [self.id]);
	});

	// Subscribe to 'inactive' event and emit "close" so the video element can react.
	stream.addEventListener('inactive', function () {
		if (self.stream !== stream) {
			return;
		}

		debug('MediaStream emits "inactive", emiting "close" and closing this MediaStreamRenderer');

		self.dispatchEvent(new Event('close'));
		self.close();
	});

	if (stream.connected) {
		connected();
	// Otherwise subscribe to 'connected' event to emulate video elements events.
	} else {
		stream.addEventListener('connected', function () {
			if (self.stream !== stream) {
				return;
			}

			connected();
		});
	}

	function connected() {
		// Emit video events.
		self.element.dispatchEvent(new Event('loadedmetadata'));
		self.element.dispatchEvent(new Event('loadeddata'));
		self.element.dispatchEvent(new Event('canplay'));
		self.element.dispatchEvent(new Event('canplaythrough'));
	}
};

MediaStreamRenderer.prototype.save = function (callback) {
	debug('save()');

	if (!this.stream) {
		callback(null);
		return;
	}

	function onResultOK(data) {
		callback(data);
	}

	function onResultError() {
		callback(null);
	}

	exec(onResultOK, onResultError, 'iosrtcPlugin', 'MediaStreamRenderer_save', [this.id]);
};

MediaStreamRenderer.prototype.refresh = function () {
	debug('refresh()');

	var elementPositionAndSize = getElementPositionAndSize.call(this),
		computedStyle,
		videoRatio,
		elementRatio,
		elementLeft = elementPositionAndSize.left,
		elementTop = elementPositionAndSize.top,
		elementWidth = elementPositionAndSize.width,
		elementHeight = elementPositionAndSize.height,
		videoViewWidth,
		videoViewHeight,
		visible,
		opacity,
		zIndex,
		mirrored,
		objectFit,
		clip,
		borderRadius,
		paddingTop,
		paddingBottom,
		paddingLeft,
		paddingRight,
		self = this;

	computedStyle = window.getComputedStyle(this.element);

	// get padding values
	paddingTop = parseInt(computedStyle.paddingTop) | 0;
	paddingBottom = parseInt(computedStyle.paddingBottom) | 0;
	paddingLeft = parseInt(computedStyle.paddingLeft) | 0;
	paddingRight = parseInt(computedStyle.paddingRight) | 0;

	// fix position according to padding
	elementLeft += paddingLeft;
	elementTop += paddingTop;

	// fix width and height according to padding
	elementWidth -= (paddingLeft + paddingRight);
	elementHeight -= (paddingTop + paddingBottom);

	videoViewWidth = elementWidth;
	videoViewHeight = elementHeight;

	// visible
	if (computedStyle.visibility === 'hidden') {
		visible = false;
	} else {
		visible = !!this.element.offsetHeight;  // Returns 0 if element or any parent is hidden.
	}

	// opacity
	opacity = parseFloat(computedStyle.opacity);

	// zIndex
	zIndex = parseFloat(computedStyle.zIndex) || parseFloat(this.element.style.zIndex) || 0;

	// mirrored (detect "-webkit-transform: scaleX(-1);" or equivalent)
	if (computedStyle.transform === 'matrix(-1, 0, 0, 1, 0, 0)' ||
		computedStyle['-webkit-transform'] === 'matrix(-1, 0, 0, 1, 0, 0)') {
		mirrored = true;
	} else {
		mirrored = false;
	}

	// objectFit ('contain' is set as default value)
	objectFit = computedStyle.objectFit || 'contain';

	// clip
	if (objectFit === 'none') {
		clip = false;
	} else {
		clip = true;
	}

	// borderRadius
	borderRadius = parseFloat(computedStyle.borderRadius);
	if (/%$/.test(borderRadius)) {
		borderRadius = Math.min(elementHeight, elementWidth) * borderRadius;
	}

	/**
	 * No video yet, so just update the UIView with the element settings.
	 */

	if (!this.videoWidth || !this.videoHeight) {
		debug('refresh() | no video track yet');

		nativeRefresh.call(this);
		return;
	}

	videoRatio = this.videoWidth / this.videoHeight;

	/**
	 * Element has no width and/or no height.
	 */

	if (!elementWidth || !elementHeight) {
		debug('refresh() | video element has 0 width and/or 0 height');

		nativeRefresh.call(this);
		return;
	}

	/**
	 * Set video view position and size.
	 */

	elementRatio = elementWidth / elementHeight;

	switch (objectFit) {
		case 'cover':
			// The element has higher or equal width/height ratio than the video.
			if (elementRatio >= videoRatio) {
				videoViewWidth = elementWidth;
				videoViewHeight = videoViewWidth / videoRatio;
			// The element has lower width/height ratio than the video.
			} else if (elementRatio < videoRatio) {
				videoViewHeight = elementHeight;
				videoViewWidth = videoViewHeight * videoRatio;
			}
			break;

		case 'fill':
			videoViewHeight = elementHeight;
			videoViewWidth = elementWidth;
			break;

		case 'none':
			videoViewHeight = this.videoHeight;
			videoViewWidth = this.videoWidth;
			break;

		case 'scale-down':
			// Same as 'none'.
			if (this.videoWidth <= elementWidth && this.videoHeight <= elementHeight) {
				videoViewHeight = this.videoHeight;
				videoViewWidth = this.videoWidth;
			// Same as 'contain'.
			} else {
				// The element has higher or equal width/height ratio than the video.
				if (elementRatio >= videoRatio) {
					videoViewHeight = elementHeight;
					videoViewWidth = videoViewHeight * videoRatio;
				// The element has lower width/height ratio than the video.
				} else if (elementRatio < videoRatio) {
					videoViewWidth = elementWidth;
					videoViewHeight = videoViewWidth / videoRatio;
				}
			}
			break;

		// 'contain'.
		default:
			objectFit = 'contain';
			// The element has higher or equal width/height ratio than the video.
			if (elementRatio >= videoRatio) {
				videoViewHeight = elementHeight;
				videoViewWidth = videoViewHeight * videoRatio;
			// The element has lower width/height ratio than the video.
			} else if (elementRatio < videoRatio) {
				videoViewWidth = elementWidth;
				videoViewHeight = videoViewWidth / videoRatio;
			}
			break;
	}

	nativeRefresh.call(this);

	function hash(str) {
		var hash = 5381,
		i = str.length;

		while (i) {
			hash = (hash * 33) ^ str.charCodeAt(--i);
		}

		return hash >>> 0;
	}

	function nativeRefresh() {
		var data = {
			elementLeft: elementLeft,
			elementTop: elementTop,
			elementWidth: elementWidth,
			elementHeight: elementHeight,
			videoViewWidth: videoViewWidth,
			videoViewHeight: videoViewHeight,
			visible: visible,
			opacity: opacity,
			zIndex: zIndex,
			mirrored: mirrored,
			objectFit: objectFit,
			clip: clip,
			borderRadius: borderRadius
		},
		newRefreshCached = hash(JSON.stringify(data));

		if (newRefreshCached === self.refreshCached) {
			return;
		}

		self.refreshCached = newRefreshCached;

		debug('refresh() | [data:%o]', data);

		exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_refresh', [this.id, data]);
	}
};

MediaStreamRenderer.prototype.close = function () {
	debug('close()');

	if (!this.stream) {
		return;
	}
	this.stream = undefined;

	exec(null, null, 'iosrtcPlugin', 'MediaStreamRenderer_close', [this.id]);
	if (this.refreshInterval) {
		clearInterval(this.refreshInterval);
		delete this.refreshInterval;
	}
};

/**
 * Private API.
 */

function onEvent(data) {
	var type = data.type,
		event;

	debug('onEvent() | [type:%s, data:%o]', type, data);

	switch (type) {
		case 'videoresize':
			this.videoWidth = data.size.width;
			this.videoHeight = data.size.height;
			this.refresh(this);

			event = new Event(type);
			event.videoWidth = data.size.width;
			event.videoHeight = data.size.height;
			this.dispatchEvent(event);

			break;
	}
}

function getElementPositionAndSize() {
	var rect = this.element.getBoundingClientRect();

	return {
		left:   rect.left + this.element.clientLeft,
		top:    rect.top + this.element.clientTop,
		width:  this.element.clientWidth,
		height: this.element.clientHeight
	};
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || 'getInput()';
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || 'randomPlay()';
}

function getWinner(playerMove,computerMove) {
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    var winner;
if (PlayerMove === ComputerMove) {
    winner = "Tie";
}
else if (PlayerMove === "Rock") {
        if (ComputerMove === "Scissor") {
            winner = "Player";
        }
        else if (ComputerMove === "Paper") {
            winner ="Computer";
        }
}
else if (PlayerMove === "Scissor") {
        if (ComputerMove === "Rock") {
            winner = "Computer";
        }
        else if (ComputerMove === "Paper") {
            winner ="Player";
        }
}
else (PlayerMove === "Paper") {
        if (ComputerMove === "Rock") {
            winner = "Player";
        }
        else if (ComputerMove === "Scissor") {
            winner ="Computer";
        }
}
    return winner;
}

function playToFive() {
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;

    var playerMove =getPlayerMove();
    var computerMove =getComputerMove();
    var winner = getWinner(playerMove, computerMove);

    while (playerwins <5 || computerWins <5) {
        getWinner();
        if (winner ="Player") {
            playerWins += 1;
        }
        else if (winner ="Computer") {
            computerWins += 1;
        }
    }
    return [playerWins, computerWins];
}<commit_msg>unit 6 homework<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || 'getInput()';
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || 'randomPlay()';
}

function getWinner(playerMove,computerMove) {
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    var winner;
if (PlayerMove === ComputerMove) {
    winner = "Tie";
}
else if (PlayerMove === "Rock") {
        if (ComputerMove === "Scissor") {
            winner = "Player";
        }
        else if (ComputerMove === "Paper") {
            winner ="Computer";
        }
}
else if (PlayerMove === "Scissor") {
        if (ComputerMove === "Rock") {
            winner = "Computer";
        }
        else if (ComputerMove === "Paper") {
            winner ="Player";
        }
}
else (PlayerMove === "Paper") {
        if (ComputerMove === "Rock") {
            winner = "Player";
        }
        else if (ComputerMove === "Scissor") {
            winner ="Computer";
        }
}
    return winner;
}

function playToFive() {
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;

    var playerMove = getPlayerMove();
    var computerMove = getComputerMove();
    var winner = getWinner(playerMove, computerMove);

    while (playerwins <5 || computerWins <5) {
        getWinner();
        if (winner ="Player") {
            playerWins += 1;
        }
        else if (winner ="Computer") {
            computerWins += 1;
        }
    }
    return [playerWins, computerWins];
}<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

CLASS({
  package: 'foam.documentation',
  name: 'DocModelFeatureDAOTrait',
  documentation: "Generates a featureDAO of all the inherited features of a $$DOC{ref:'Model'}.",

  requires: [
    'foam.documentation.DocFeatureInheritanceTracker',
    'foam.documentation.DocModelInheritanceTracker',
    'Model',
    'MDAO',
    'foam.dao.FindFallbackDAO'
  ],

  imports: [
    '_DEV_ModelDAO',
    'masterModelList',
    'featureDAO',
    'featureDAOModelsLoading',
    'documentViewRef'
  ],
  exports: [
    'featureDAO',
    'modelDAO',
    'featureDAOModelsLoading',
    'subModelDAO',
    'traitUserDAO',
    '_DEV_ModelDAO',
    'masterModelList',
    'documentViewRef'
  ],

  properties: [
    {
      name: 'featuresToLoad',
      factory: function() {
        return [ 'properties',
          'methods',
          'actions',
          'listeners',
          'models',
          'relationships',
          'templates'];
      }
    },
    {
      name: 'processBaseModels',
      model_: 'BooleanProperty',
      defaultValue: true
    },
    {
      name: 'documentViewRef',
      factory: function() {
         return this.SimpleValue.create(
           this.DocRef.create({ ref: this.data ? this.data.id : "" },
             this.Y.sub({ documentViewRef: null })));
      }
    },
    {
      name: '_DEV_ModelDAO',
      lazyFactory: function() {
        return this.FindFallbackDAO.create({delegate: this.masterModelList, fallback: this.X.ModelDAO});
      }
    },
    {
      name: "masterModelList",
      lazyFactory: function() {
        return this.MDAO.create({model:Model});
      }
    },
    {
      name: 'featureDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.DocFeatureInheritanceTracker, autoIndex:true});
      }
    },
    {
      name: 'featureDAOModelsLoading',
      lazyFactory: function() {
        return { };
      }
    },
    {
      name: 'modelDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.DocModelInheritanceTracker, autoIndex:true});
      }
    },
    {
      name: 'subModelDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.Model, autoIndex:true});
      }
    },
    {
      name: 'traitUserDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.Model, autoIndex:true});
      }
    }
  ],

  methods: {

    generateFeatureDAO: function(data) {
      /* Builds a feature DAO to sort out inheritance and overriding of
        $$DOC{ref:'Property',usePlural:true}, $$DOC{ref:'Method',usePlural:true},
        and other features. */

      //var startTime = Date.now();
      //console.log("Generating FeatureDAO...", this.data );

      if ( ! data.model_ || data.model_.id !== 'Model' ) {
        console.warn("ModelDocView created with non-model instance: ", data);
        return;
      }

      if ( ! this.Y.modelDAO ) {
        // we aren't done init yet, so wait and our init(); will call us again
        return;
      }

      if ( this.featureDAOModelsLoading[data.id]
          && this.featureDAOModelsLoading[data.id].loading ) {
        // someone is already loading this model for us!
        return;
      }
      console.log("Generating FeatureDAO...", this.data.id );

//       this.featureDAO.removeAll();
//       this.modelDAO.removeAll();
      this.subModelDAO.removeAll();
      this.traitUserDAO.removeAll();
//      this.featureDAOModelsLoading = {};

      // Run through the features in the Model definition in this.data,
      // and load them into the feature DAO. Passing [] assumes we don't
      // care about other models that extend this one. Finding such would
      // be a global search problem.
      if ( this.processBaseModels ) {
        this.Y.setTimeout(function() {
          this.agetInheritanceMap(this.loadFeaturesOfModel, data, { data: data });
        }.bind(this), 20);
      } else {
        this.loadFeaturesOfModel( { data: data } );
      }

//       this.Y.setTimeout(function() {
//           this.findSubModels(data);
//           this.findTraitUsers(data);
//       }.bind(this), 500);

      //console.log("  FeatureDAO complete.", Date.now() - startTime);

      //this.debugLogFeatureDAO();
    },

    agetInheritanceMap: function(ret, model, map) {
      // find all base models of the given model, put into list
      var findFuncs = [];
      model.traits.forEach(function(t) {
        findFuncs.push(function(ret) {
          this._DEV_ModelDAO.find(t, {
            put: function(m) { map[m.id] = m; ret && ret(); },
            error: function() { console.warn("DocModelFeatureDAOTrait could not load trait ", t); ret && ret(); }
          });
        }.bind(this));
      }.bind(this));
      // runs the trait finds first, and when they are done recurse to the next ancestor
      apar.apply(this, findFuncs)(function() {
        if ( model.extendsModel ) {
          this._DEV_ModelDAO.find(model.extendsModel, {
              put: function(ext) {
                map[ext.id] = ext;
                this.agetInheritanceMap(ret, ext, map);
              }.bind(this),
              error: function() { console.warn("DocModelFeatureDAOTrait could not load model ", ext); ret && ret(map); }
          });
        } else {
          ret && ret(map); // no more extendsModels to follow, finished
        }
      }.bind(this));

    },

    debugLogFeatureDAO: function() {
      /* For debugging purposes, prints out the state of the FeatureDAO. */

      var features = [];
      console.log("Features DAO: ", this.featureDAO);
      this.featureDAO.select(features);
      console.log(features);

      var modelss = [];
      console.log("Model    DAO: ", this.modelDAO);
      this.modelDAO.select(modelss);
      console.log(modelss);
    },

    findSubModels: function(data) {
      if ( ! this.Model.isInstance(data) ) return;
      this.findDerived(data);
    },

    findTraitUsers: function(data) {
      if ( ! this.Model.isInstance(data) ) return;

      this._DEV_ModelDAO.select(MAP(
        function(obj) {
          if ( obj.traits &&  obj.traits.indexOf(data.id) > -1 ) {
            this.traitUserDAO.put(obj);
          }
        }.bind(this)
      ));
    },

    destroy: function( isParentDestroyed ) {
      if ( isParentDestroyed ) {
        this.featureDAO = null;
        this.modelDAO = null;
        this.subModelDAO = null;
        this.traitUserDAO = null;
      }
      this.SUPER(isParentDestroyed);
    }

  },

  listeners: [
    {
      name: 'findDerived',
      whenIdle: true,
      code: function(extendersOf) {
        this._DEV_ModelDAO.select(MAP(
          function(obj) {
            if ( obj.extendsModel == extendersOf.id ) {
              this.subModelDAO.put(obj);
              // for performance, spread out the load
              // TODO(jacksonic): disabled recursion for speed
              //this.X.setTimeout(function() { this.findDerived(obj); }.bind(this), 200);
            }
          }.bind(this)
        ));
      }

    },
    {
      name: 'loadFeaturesOfModel',
      code: function(map, previousExtenderTrackers, traitInheritanceLevel) {
        /*
Recursively load features of this $$DOC{ref:'Model'} and
          $$DOC{ref:'Model',usePlural:true} it extends.

Returns the inheritance level of model (0 = $$DOC{ref:'Model'}).

          */
        var model = map.data;

        if ( this.featureDAOModelsLoading[model.id]
            && this.featureDAOModelsLoading[model.id].loading ) {
          return this.featureDAOModelsLoading[model.id].inheritanceLevel; //TODO: async?
        }

        if (typeof previousExtenderTrackers == 'undefined') {
          previousExtenderTrackers = [];
        }
        var isTrait = true;
        if (typeof traitInheritanceLevel == 'undefined') {
          traitInheritanceLevel = 0;
          isTrait = false;
        }
        var modelDef = model.definition_?  model.definition_: model;
        var self = this;
        var newModelTr = this.DocModelInheritanceTracker.create();
        newModelTr.model = model.id;
        this.featureDAOModelsLoading[model.id] = { loading: true, inheritanceLevel: -1 };

        this.featuresToLoad.forEach(function(modProp) {
          var modPropVal = modelDef[modProp];
          if ( Array.isArray(modPropVal) ) { // we only care to check inheritance on the array properties
            modPropVal.forEach(function(feature) {
              if ( feature.name ) { // only look at actual objects
                // all features we hit are declared (or overridden) in this model
                var featTr = self.DocFeatureInheritanceTracker.create({
                      isDeclared:true,
                      feature: feature,
                      model: newModelTr.model,
                      type: modProp,
                      fromTrait: isTrait
                });
                self.featureDAO.put(featTr);

                // for the models that extend this model, make sure they have
                // the feature too, if they didn't already have it declared (overridden).
                // isTrait is not set, as we don't distinguish between inherited trait features and
                // extendsModel features.
                previousExtenderTrackers.forEach(function(extModelTr) {
                  self.featureDAO
                        .where(EQ(self.DocFeatureInheritanceTracker.PRIMARY_KEY,
                                  extModelTr.model+":::"+feature.name))
                        .select(COUNT())(function(c) {
                            if (c.count <= 0) {
                              var featTrExt = self.DocFeatureInheritanceTracker.create({
                                  isDeclared: false,
                                  feature: feature,
                                  model: extModelTr.model,
                                  type: modProp });
                              self.featureDAO.put(featTrExt);
                            }
                        });
                });
              }
            });
          }
        });

        if ( ! isTrait && this.processBaseModels ) {
          // Check if we extend something, and recurse.
          if (!model.extendsModel) {
            newModelTr.inheritanceLevel = 0;
          } else {
            // add the tracker we're building to the list, for updates from our base models
            previousExtenderTrackers.push(newModelTr);
            // inheritance level will bubble back up the stack once we know where the bottom is.
            // pass a copy of previousExtenderTrackers so we know what to update in the traits section after.
            newModelTr.inheritanceLevel = 1 + this.loadFeaturesOfModel(
              { __proto__: map, data: map[model.extendsModel] },
              previousExtenderTrackers.slice(0));
          }

          // Process traits with the same inheritance level we were assigned, since they appear first in the
          // apparent inheritance chain before our extendsModel.
          if (model.traits && model.traits.length > 0) {
            model.traits.forEach(function(trait) {
              var traitExtenderTrackers = previousExtenderTrackers.slice(0);
              traitExtenderTrackers.push(newModelTr);
              this.loadFeaturesOfModel(
                { __proto__: map, data: map[trait] },
                traitExtenderTrackers,
                newModelTr.inheritanceLevel);
            }.bind(this));
          }
        }

        // the tracker is now complete
        this.modelDAO.put(newModelTr);
        this.featureDAOModelsLoading[model.id].inheritanceLevel = newModelTr.inheritanceLevel;
        return newModelTr.inheritanceLevel;
      }

    }
  ]

});
<commit_msg>Fixed DocModelFeatureDAOTrait DAO building optimization<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

CLASS({
  package: 'foam.documentation',
  name: 'DocModelFeatureDAOTrait',
  documentation: "Generates a featureDAO of all the inherited features of a $$DOC{ref:'Model'}.",

  requires: [
    'foam.documentation.DocFeatureInheritanceTracker',
    'foam.documentation.DocModelInheritanceTracker',
    'Model',
    'MDAO',
    'foam.dao.FindFallbackDAO'
  ],

  imports: [
    '_DEV_ModelDAO',
    'masterModelList',
    'featureDAO',
    'featureDAOModelsLoading',
    'documentViewRef'
  ],
  exports: [
    'featureDAO',
    'modelDAO',
    'featureDAOModelsLoading',
    'subModelDAO',
    'traitUserDAO',
    '_DEV_ModelDAO',
    'masterModelList',
    'documentViewRef'
  ],

  properties: [
    {
      name: 'featuresToLoad',
      factory: function() {
        return [ 'properties',
          'methods',
          'actions',
          'listeners',
          'models',
          'relationships',
          'templates'];
      }
    },
    {
      name: 'processBaseModels',
      model_: 'BooleanProperty',
      defaultValue: true
    },
    {
      name: 'documentViewRef',
      factory: function() {
         return this.SimpleValue.create(
           this.DocRef.create({ ref: this.data ? this.data.id : "" },
             this.Y.sub({ documentViewRef: null })));
      }
    },
    {
      name: '_DEV_ModelDAO',
      lazyFactory: function() {
        return this.FindFallbackDAO.create({delegate: this.masterModelList, fallback: this.X.ModelDAO});
      }
    },
    {
      name: "masterModelList",
      lazyFactory: function() {
        return this.MDAO.create({model:Model});
      }
    },
    {
      name: 'featureDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.DocFeatureInheritanceTracker, autoIndex:true});
      }
    },
    {
      name: 'featureDAOModelsLoading',
      lazyFactory: function() {
        return { };
      }
    },
    {
      name: 'modelDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.DocModelInheritanceTracker, autoIndex:true});
      }
    },
    {
      name: 'subModelDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.Model, autoIndex:true});
      }
    },
    {
      name: 'traitUserDAO',
      model_: 'foam.core.types.DAOProperty',
      lazyFactory: function() {
        return this.MDAO.create({model:this.Model, autoIndex:true});
      }
    }
  ],

  methods: {

    generateFeatureDAO: function(data) {
      /* Builds a feature DAO to sort out inheritance and overriding of
        $$DOC{ref:'Property',usePlural:true}, $$DOC{ref:'Method',usePlural:true},
        and other features. */

      //var startTime = Date.now();
      //console.log("Generating FeatureDAO...", this.data );

      if ( ! data.model_ || data.model_.id !== 'Model' ) {
        console.warn("ModelDocView created with non-model instance: ", data);
        return;
      }

      if ( ! this.Y.modelDAO ) {
        // we aren't done init yet, so wait and our init(); will call us again
        return;
      }

      console.log("Generating FeatureDAO...", this.data.id );

//       this.featureDAO.removeAll();
//       this.modelDAO.removeAll();
      this.subModelDAO.removeAll();
      this.traitUserDAO.removeAll();
//      this.featureDAOModelsLoading = {};

      // Run through the features in the Model definition in this.data,
      // and load them into the feature DAO. Passing [] assumes we don't
      // care about other models that extend this one. Finding such would
      // be a global search problem.
      if ( this.processBaseModels ) {
        this.Y.setTimeout(function() {
          this.agetInheritanceMap(this.loadFeaturesOfModel, data, { data: data });
        }.bind(this), 20);
      } else {
        this.loadFeaturesOfModel( { data: data } );
      }

      // TODO(jacksonic): relocate submodels and trait users to a different model
//       this.Y.setTimeout(function() {
//           this.findSubModels(data);
//           this.findTraitUsers(data);
//       }.bind(this), 500);

      //console.log("  FeatureDAO complete.", Date.now() - startTime);

      //this.debugLogFeatureDAO();
    },

    agetInheritanceMap: function(ret, model, map) {
      // find all base models of the given model, put into list
      var findFuncs = [];
      model.traits.forEach(function(t) {
        findFuncs.push(function(ret) {
          this._DEV_ModelDAO.find(t, {
            put: function(m) { map[m.id] = m; ret && ret(); },
            error: function() { console.warn("DocModelFeatureDAOTrait could not load trait ", t); ret && ret(); }
          });
        }.bind(this));
      }.bind(this));
      // runs the trait finds first, and when they are done recurse to the next ancestor
      apar.apply(this, findFuncs)(function() {
        if ( model.extendsModel ) {
          this._DEV_ModelDAO.find(model.extendsModel, {
              put: function(ext) {
                map[ext.id] = ext;
                this.agetInheritanceMap(ret, ext, map);
              }.bind(this),
              error: function() { console.warn("DocModelFeatureDAOTrait could not load model ", ext); ret && ret(map); }
          });
        } else {
          ret && ret(map); // no more extendsModels to follow, finished
        }
      }.bind(this));

    },

    debugLogFeatureDAO: function() {
      /* For debugging purposes, prints out the state of the FeatureDAO. */

      var features = [];
      console.log("Features DAO: ", this.featureDAO);
      this.featureDAO.select(features);
      console.log(features);

      var modelss = [];
      console.log("Model    DAO: ", this.modelDAO);
      this.modelDAO.select(modelss);
      console.log(modelss);
    },

    findSubModels: function(data) {
      if ( ! this.Model.isInstance(data) ) return;
      this.findDerived(data);
    },

    findTraitUsers: function(data) {
      if ( ! this.Model.isInstance(data) ) return;

      this._DEV_ModelDAO.select(MAP(
        function(obj) {
          if ( obj.traits &&  obj.traits.indexOf(data.id) > -1 ) {
            this.traitUserDAO.put(obj);
          }
        }.bind(this)
      ));
    },

    destroy: function( isParentDestroyed ) {
      if ( isParentDestroyed ) {
        this.featureDAO = null;
        this.modelDAO = null;
        this.subModelDAO = null;
        this.traitUserDAO = null;
      }
      this.SUPER(isParentDestroyed);
    }

  },

  listeners: [
    {
      name: 'findDerived',
      whenIdle: true,
      code: function(extendersOf) {
        this._DEV_ModelDAO.select(MAP(
          function(obj) {
            if ( obj.extendsModel == extendersOf.id ) {
              this.subModelDAO.put(obj);
              // for performance, spread out the load
              // TODO(jacksonic): disabled recursion for speed
              //this.X.setTimeout(function() { this.findDerived(obj); }.bind(this), 200);
            }
          }.bind(this)
        ));
      }

    },
    {
      name: 'loadFeaturesOfModel',
      code: function(map, previousExtenderTrackers, traitInheritanceLevel) {
        /*
Recursively load features of this $$DOC{ref:'Model'} and
          $$DOC{ref:'Model',usePlural:true} it extends.

Returns the inheritance level of model (0 = $$DOC{ref:'Model'}).

          */
        var model = map.data;

        if (typeof previousExtenderTrackers == 'undefined') {
          previousExtenderTrackers = [];
        }
        var isTrait = true;
        if (typeof traitInheritanceLevel == 'undefined') {
          traitInheritanceLevel = 0;
          isTrait = false;
        }
        var modelDef = model.definition_?  model.definition_: model;
        var self = this;
        var newModelTr = this.DocModelInheritanceTracker.create();
        newModelTr.model = model.id;
        // track what is loading, so child daos don't load it again needlessly
        if (   ! this.featureDAOModelsLoading[model.id]
            || ! this.featureDAOModelsLoading[model.id].loading ) {
          this.featureDAOModelsLoading[model.id] = {
            loading: true,
            inheritanceLevel: -1,
            features: {}
          };
        }

        this.featuresToLoad.forEach(function(modProp) {
          // check if someone else has processed the feature, then indicate we have process this feature
          if ( self.featureDAOModelsLoading[model.id].features[modProp] ) return;
          self.featureDAOModelsLoading[model.id].features[modProp] = true;

          var modPropVal = modelDef[modProp];
          if ( Array.isArray(modPropVal) ) { // we only care to check inheritance on the array properties
            modPropVal.forEach(function(feature) {
              if ( feature.name ) { // only look at actual objects
                // all features we hit are declared (or overridden) in this model
                var featTr = self.DocFeatureInheritanceTracker.create({
                      isDeclared:true,
                      feature: feature,
                      model: newModelTr.model,
                      type: modProp,
                      fromTrait: isTrait
                });
                self.featureDAO.put(featTr);

                // for the models that extend this model, make sure they have
                // the feature too, if they didn't already have it declared (overridden).
                // isTrait is not set, as we don't distinguish between inherited trait features and
                // extendsModel features.
                previousExtenderTrackers.forEach(function(extModelTr) {
                  self.featureDAO
                        .where(EQ(self.DocFeatureInheritanceTracker.PRIMARY_KEY,
                                  extModelTr.model+":::"+feature.name))
                        .select(COUNT())(function(c) {
                            if (c.count <= 0) {
                              var featTrExt = self.DocFeatureInheritanceTracker.create({
                                  isDeclared: false,
                                  feature: feature,
                                  model: extModelTr.model,
                                  type: modProp });
                              self.featureDAO.put(featTrExt);
                            }
                        });
                });
              }
            });
          }
        });

        if ( ! isTrait && this.processBaseModels ) {
          // Check if we extend something, and recurse.
          if (!model.extendsModel) {
            newModelTr.inheritanceLevel = 0;
          } else {
            // add the tracker we're building to the list, for updates from our base models
            previousExtenderTrackers.push(newModelTr);
            // inheritance level will bubble back up the stack once we know where the bottom is.
            // pass a copy of previousExtenderTrackers so we know what to update in the traits section after.
            newModelTr.inheritanceLevel = 1 + this.loadFeaturesOfModel(
              { __proto__: map, data: map[model.extendsModel] },
              previousExtenderTrackers.slice(0));
          }

          // Process traits with the same inheritance level we were assigned, since they appear first in the
          // apparent inheritance chain before our extendsModel.
          if (model.traits && model.traits.length > 0) {
            model.traits.forEach(function(trait) {
              var traitExtenderTrackers = previousExtenderTrackers.slice(0);
              traitExtenderTrackers.push(newModelTr);
              this.loadFeaturesOfModel(
                { __proto__: map, data: map[trait] },
                traitExtenderTrackers,
                newModelTr.inheritanceLevel);
            }.bind(this));
          }
        }

        // the tracker is now complete
        this.modelDAO.put(newModelTr);
        this.featureDAOModelsLoading[model.id].inheritanceLevel = newModelTr.inheritanceLevel;
        return newModelTr.inheritanceLevel;
      }

    }
  ]

});
<|endoftext|>


<commit_before><commit_msg>create renderDrawRight functions by type<commit_after><|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Modified rockpaperscissors.js for two lines function getPlayerMove(move) {     // Write an expression that operates on a variable called     // If a  has a value, your expression should evaluate to that value.     // However, if  is not specified / is null, your expression should equal .     return move = move || 'getInput()'; }<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move = move || 'getInput()';
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move = move || 'randomPlay()';
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief test the agency communication layer
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");
var internal = require("internal");
var _ = require("underscore");

// -----------------------------------------------------------------------------
// --SECTION--                                              agency-result-helper
// -----------------------------------------------------------------------------

var createResult = function(prefix, list) {
  var res = {};
  _.each(list, function(v, k) {
    res[prefix + k] = v;
  });
  return res;
};

// -----------------------------------------------------------------------------
// --SECTION--                                                         good-case
// -----------------------------------------------------------------------------

function runGoodCaseTests(test) {

  var Communication = require("org/arangodb/sharding/agency-communication");
  var configResult;
  var tmpConfigResult;
  var registeredResult;
  var agencyMock;
  var resetToDefault;
  var comm;
  var agencyRoutes;
  var setup;
  var teardown;
  var agencyTargetServers;
  var plannedServers;
  var registered;

  agencyRoutes = {
    vision: "Vision/",
    target: "Target/",
    plan: "Plan/",
    current: "Current/",
    fail: "Fail/"
  };

  resetToDefault = function() {
    agencyTargetServers = createResult(agencyRoutes.target + "DBServers/", {
      "pavel": "sandro",
      "paul": "sally",
      "patricia": "sandra"
    });
    plannedServers = createResult(agencyRoutes.plan + "DBServers/", {
      "pavel": "sandro",
      "paul": "sally",
      "patricia": "sandra"
    });
    registered = createResult(agencyRoutes.current + "ServersRegistered/", {
      "pavel": "tcp://192.168.0.1:8529",
      "paul": "tcp://192.168.0.2:8529",
      "patricia": "tcp://192.168.0.3:8529",
      "sandro": "tcp://192.168.0.4:8529",
      "sally": "tcp://192.168.0.5:8529",
      "sandra": "tcp://192.168.0.6:8529"
    });
  };

  setup = function() {
    resetToDefault();
  };

  teardown = function() {

  };

  agencyMock = {
    get: function(route, recursive) {
      if (route === agencyRoutes.target + "DBServers" && recursive) {
        return agencyTargetServers;
      }
      if (route === agencyRoutes.plan + "DBServers" && recursive) {
        return plannedServers;
      }
      if (route === agencyRoutes.current + "ServersRegistered" && recursive) {
        return registered;
      }
      fail();
    }
  };
  Communication._createAgency = function() {
    return agencyMock;
  };

  comm = new Communication.Communication();

  function VisionSuite() {

    return {
      setUp: setup,
      tearDown: teardown,

      testGetVision: function() {
        var expectedResult = {

        };
        assertTrue(false);
      }
    };
  };

  function TargetDBServersSuite() {
    var targetServers;

    return {
      setUp: function() {
        setup();
        targetServers = comm.target.DBServers();
      },
      tearDown: teardown,

      testGetServerList: function() {
        var expected = {
          pavel: {
            role: "primary",
            secondary: "sandro"
          },
          paul: {
            role: "primary",
            secondary: "sally"
          },
          patricia: {
            role: "primary",
            secondary: "sandra"
          },
          sandro: {
            role: "secondary"
          },
          sally: {
            role: "secondary"
          },
          sandra: {
            role: "secondary"
          }
        };
        var res = targetServers.getList();
        assertEqual(res, expected);
      },

      testAddNewPrimaryServer: function() {
        var name = "pancho";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, agencyRoutes.target + "DBServers/" + name);
          assertEqual(value, "none");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addPrimary(name), "Failed to insert a new primary");
        assertTrue(wasCalled, "Agency has not been informed to insert primary.");

        var newList = targetServers.getList();
        assertNotUndefined(newList[name]);
        assertEqual(newList[name].role, "primary");
        assertUndefined(newList[name].secondary);
      },

      testAddNewSecondaryServer: function() {
        var name = "pancho";
        var secName = "samuel";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, agencyRoutes.target + "DBServers/" + name);
          assertEqual(value, "none");
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addPrimary(name), "Failed to insert a new primary");
        assertTrue(wasCalled, "Agency has not been informed to insert primary.");
        wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, agencyRoutes.target + "DBServers/" + name);
          assertEqual(value, secName);
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addSecondary(secName, name), "Failed to insert a new secondary");
        assertTrue(wasCalled, "Agency has not been informed to insert secondary.");

        var newList = targetServers.getList();
        assertNotUndefined(newList[name]);
        assertEqual(newList[name].role, "primary");
        assertEqual(newList[name].secondary, secName);
        assertNotUndefined(newList[secName]);
        assertEqual(newList[secName].role, "secondary");
      },

      testAddNewServerPair: function() {
        var name = "pancho";
        var secName = "samuel";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, agencyRoutes.target + "DBServers/" + name);
          assertEqual(value, secName);
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addPair(name, secName), "Failed to insert a new primary/secondary pair");
        assertTrue(wasCalled, "Agency has not been informed to insert the new pair.");
        var newList = targetServers.getList();
        assertNotUndefined(newList[name]);
        assertEqual(newList[name].role, "primary");
        assertEqual(newList[name].secondary, secName);
        assertNotUndefined(newList[secName]);
        assertEqual(newList[secName].role, "secondary");
      },

      testRemovePrimaryServer: function() {
        var name = "pavel";
        var secondaryName = "sandro";
        var setWasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, agencyRoutes.target + "DBServers/" + secondaryName);
          assertEqual(value, "none");
          assertFalse(setWasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          setWasCalled = true;
          return true;
        };
        var delWasCalled = false;
        agencyMock.remove = function(route) {
          assertEqual(route, agencyRoutes.target + "DBServers/" + name);
          assertFalse(delWasCalled, "Delete has been called multiple times");
          delete agencyTargetServers[route];
          delWasCalled = true;
          return true;
        };
        assertTrue(targetServers.removeServer(name), "Failed to remove a primary server");
        assertTrue(setWasCalled, "Agency has not been informed to replace the primary with the secondary.");
        assertTrue(delWasCalled, "Agency has not been informed to remove the primary/secondary pair.");

        var newList = targetServers.getList();
        assertUndefined(newList[name]);
        assertNotUndefined(newList[secondaryName]);
        assertEqual(newList[secondaryName].role, "primary");
        assertUndefined(newList[secondaryName].secondary);
      },

      testRemoveSecondaryServer: function() {
        var name = "sandro";
        var pName = "pavel";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, agencyRoutes.target + "DBServers/" + pName);
          assertEqual(value, "none");
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.removeServer(name), "Failed to remove a secondary server.");
        assertTrue(wasCalled, "Agency has not been informed to update the primary server.");
        var newList = targetServers.getList();
        assertUndefined(newList[name]);
        assertNotUndefined(newList[pName]);
        assertEqual(newList[pName].role, "primary");
        assertUndefined(newList[pName].secondary);
      }

    };

  };

  function TargetShardSuite() {

    return {
      setUp: setup,
      tearDown: teardown,

      testGetDatabaseList: function() {
        assertTrue(true);
      }
    }
  };

  function DBServersSuite() {

    var DBServers;

    return {
      setUp: function() {
        DBServers = comm.DBServers();
      },
      tearDown: function() {},

      testGetList: function() {
        var expectedResult = {
          pavel: {
            address: "tcp://192.168.0.1:8529",
            role: "primary",
            secondary: "sandro"
          },
          paul: {
            address: "tcp://192.168.0.2:8529",
            role: "primary",
            secondary: "sally"
          },
          patricia: {
            address: "tcp://192.168.0.3:8529",
            role: "primary",
            secondary: "sandra"
          },
          sandro: {
            address: "tcp://192.168.0.4:8529",
            role: "secondary"
          },
          sally: {
            address: "tcp://192.168.0.5:8529",
            role: "secondary"
          },
          sandra: {
            address: "tcp://192.168.0.6:8529",
            role: "secondary"
          }
        };
        var res = DBServers.list();
        assertEqual(expectedResult, res);
      }
    };
  };

//  test.run(VisionSuite);
  test.run(TargetDBServersSuite);
  test.run(TargetShardSuite);
//  test.run(DBServersSuite);
};

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

runGoodCaseTests(jsunity);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<commit_msg>Optimized readability of routes in agency-comm tests<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief test the agency communication layer
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");
var internal = require("internal");
var _ = require("underscore");

// -----------------------------------------------------------------------------
// --SECTION--                                              agency-result-helper
// -----------------------------------------------------------------------------

var createResult = function(prefixes, list) {
  var prefix = prefixes.join("/") + "/";
  var res = {};
  _.each(list, function(v, k) {
    res[prefix + k] = v;
  });
  return res;
};

// -----------------------------------------------------------------------------
// --SECTION--                                                         good-case
// -----------------------------------------------------------------------------

function runGoodCaseTests(test) {

  var Communication = require("org/arangodb/sharding/agency-communication");
  var configResult;
  var tmpConfigResult;
  var registeredResult;
  var agencyMock;
  var resetToDefault;
  var comm;
  var agencyRoutes;
  var setup;
  var teardown;
  var agencyTargetServers;
  var plannedServers;
  var registered;

  agencyRoutes = {
    vision: "Vision",
    target: "Target",
    plan: "Plan",
    current: "Current",
    fail: "Fail"
  };

  resetToDefault = function() {
    agencyTargetServers = createResult([agencyRoutes.target, "DBServers"], {
      "pavel": "sandro",
      "paul": "sally",
      "patricia": "sandra"
    });
    plannedServers = createResult([agencyRoutes.plan, "DBServers"], {
      "pavel": "sandro",
      "paul": "sally",
      "patricia": "sandra"
    });
    registered = createResult([agencyRoutes.current, "ServersRegistered"], {
      "pavel": "tcp://192.168.0.1:8529",
      "paul": "tcp://192.168.0.2:8529",
      "patricia": "tcp://192.168.0.3:8529",
      "sandro": "tcp://192.168.0.4:8529",
      "sally": "tcp://192.168.0.5:8529",
      "sandra": "tcp://192.168.0.6:8529"
    });
  };

  setup = function() {
    resetToDefault();
  };

  teardown = function() {

  };

  agencyMock = {
    get: function(route, recursive) {
      var parts = route.split("/");
      switch (parts[0]) {
        case agencyRoutes.target:
          if (parts[1] === "DBServers" && recursive) {
            return agencyTargetServers;
          }
          break;
        case agencyRoutes.plan:
          if (parts[1] === "DBServers" && recursive) {
            return plannedServers;
          }
          break;
        case agencyRoutes.current:
          if (parts[1] === "ServersRegesitered" && recursive) {
            return registered;
          }
          break;
        default:
          fail();
      }
    }
  };
  Communication._createAgency = function() {
    return agencyMock;
  };

  comm = new Communication.Communication();

  function VisionSuite() {

    return {
      setUp: setup,
      tearDown: teardown,

      testGetVision: function() {
        var expectedResult = {

        };
        assertTrue(false);
      }
    };
  };

  function TargetDBServersSuite() {
    var targetServers;

    return {
      setUp: function() {
        setup();
        targetServers = comm.target.DBServers();
      },
      tearDown: teardown,

      testGetServerList: function() {
        var expected = {
          pavel: {
            role: "primary",
            secondary: "sandro"
          },
          paul: {
            role: "primary",
            secondary: "sally"
          },
          patricia: {
            role: "primary",
            secondary: "sandra"
          },
          sandro: {
            role: "secondary"
          },
          sally: {
            role: "secondary"
          },
          sandra: {
            role: "secondary"
          }
        };
        var res = targetServers.getList();
        assertEqual(res, expected);
      },

      testAddNewPrimaryServer: function() {
        var name = "pancho";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, [agencyRoutes.target, "DBServers", name].join("/"));
          assertEqual(value, "none");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addPrimary(name), "Failed to insert a new primary");
        assertTrue(wasCalled, "Agency has not been informed to insert primary.");

        var newList = targetServers.getList();
        assertNotUndefined(newList[name]);
        assertEqual(newList[name].role, "primary");
        assertUndefined(newList[name].secondary);
      },

      testAddNewSecondaryServer: function() {
        var name = "pancho";
        var secName = "samuel";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, [agencyRoutes.target, "DBServers", name].join("/"));
          assertEqual(value, "none");
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addPrimary(name), "Failed to insert a new primary");
        assertTrue(wasCalled, "Agency has not been informed to insert primary.");
        wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, [agencyRoutes.target, "DBServers", name].join("/"));
          assertEqual(value, secName);
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addSecondary(secName, name), "Failed to insert a new secondary");
        assertTrue(wasCalled, "Agency has not been informed to insert secondary.");

        var newList = targetServers.getList();
        assertNotUndefined(newList[name]);
        assertEqual(newList[name].role, "primary");
        assertEqual(newList[name].secondary, secName);
        assertNotUndefined(newList[secName]);
        assertEqual(newList[secName].role, "secondary");
      },

      testAddNewServerPair: function() {
        var name = "pancho";
        var secName = "samuel";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, [agencyRoutes.target, "DBServers", name].join("/"));
          assertEqual(value, secName);
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.addPair(name, secName), "Failed to insert a new primary/secondary pair");
        assertTrue(wasCalled, "Agency has not been informed to insert the new pair.");
        var newList = targetServers.getList();
        assertNotUndefined(newList[name]);
        assertEqual(newList[name].role, "primary");
        assertEqual(newList[name].secondary, secName);
        assertNotUndefined(newList[secName]);
        assertEqual(newList[secName].role, "secondary");
      },

      testRemovePrimaryServer: function() {
        var name = "pavel";
        var secondaryName = "sandro";
        var setWasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, [agencyRoutes.target, "DBServers", secondaryName].join("/"));
          assertEqual(value, "none");
          assertFalse(setWasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          setWasCalled = true;
          return true;
        };
        var delWasCalled = false;
        agencyMock.remove = function(route) {
          assertEqual(route, [agencyRoutes.target, "DBServers", name].join("/"));
          assertFalse(delWasCalled, "Delete has been called multiple times");
          delete agencyTargetServers[route];
          delWasCalled = true;
          return true;
        };
        assertTrue(targetServers.removeServer(name), "Failed to remove a primary server");
        assertTrue(setWasCalled, "Agency has not been informed to replace the primary with the secondary.");
        assertTrue(delWasCalled, "Agency has not been informed to remove the primary/secondary pair.");

        var newList = targetServers.getList();
        assertUndefined(newList[name]);
        assertNotUndefined(newList[secondaryName]);
        assertEqual(newList[secondaryName].role, "primary");
        assertUndefined(newList[secondaryName].secondary);
      },

      testRemoveSecondaryServer: function() {
        var name = "sandro";
        var pName = "pavel";
        var wasCalled = false;
        agencyMock.set = function(route, value) {
          assertEqual(route, [agencyRoutes.target, "DBServers", pName].join("/"));
          assertEqual(value, "none");
          assertFalse(wasCalled, "Set has been called multiple times");
          agencyTargetServers[route] = value;
          wasCalled = true;
          return true;
        };
        assertTrue(targetServers.removeServer(name), "Failed to remove a secondary server.");
        assertTrue(wasCalled, "Agency has not been informed to update the primary server.");
        var newList = targetServers.getList();
        assertUndefined(newList[name]);
        assertNotUndefined(newList[pName]);
        assertEqual(newList[pName].role, "primary");
        assertUndefined(newList[pName].secondary);
      }

    };

  };

  function TargetShardSuite() {

    return {
      setUp: setup,
      tearDown: teardown,

      testGetDatabaseList: function() {
        /*
        var list = [
          "_system",
          "a_db",
          "b_db",
          "z_db"
        ];
        assertEqual(targetDBs.getList(), list);
        */
        assertTrue(true);
      }
    }
  };

//  test.run(VisionSuite);
  test.run(TargetDBServersSuite);
  test.run(TargetShardSuite);
};

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

runGoodCaseTests(jsunity);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<|endoftext|>


<commit_before>export default function deepValue(object, path = '') {
  let parts = path.split('.');
  for (let part of parts) {
    if (!object[part]) return undefined;
    object = object[part];
  }
  return object;
}
<commit_msg>fix: deepValue and 0 value<commit_after>export default function deepValue(object, path = '') {
  let parts = path.split('.');
  for (let part of parts) {
    if (object[part] === undefined) return undefined;
    object = object[part];
  }
  return object;
}
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminPage");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserTitle");}, gvm);

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);
    gvm.userActions = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserActions");}, gvm);
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn");}, gvm);

    gvm.users = ko.observableArray([]);

    gvm.updateUsers = function(user)
    {
        gvm.users.push(user);
    },

    gvm.removeUser = function(user) {
        gvm.users.remove(user);
        removeUser(user);
    },

    gvm.refreshUsers = function()
    {
        gvm.users.destroyAll();
    }
}

function fetchUsersData()
{
    viewModel.refreshUsers();
    $.getJSON("/api/alluserswithroles/", function(data)
    {
        $.each(data, function(i, item){
            viewModel.updateUsers(new User(item.id, item.username, item.firstname, item.lastname, item.status));
        });
    });
}

function removeUser(user)
{
    $.getJSON("/api/removeuser/" + user.id(), function(data)
    {
        console.log("User was removed");
        fetchUsersData();
    });
}

function User(id, username, firstname, lastname, status) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            //WORDT NOG NIET VERANDERD
            //WORDT NOG NIET OPGESLAAN OP DB
            console.log(status);
        }
    };
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showAddUserModal(id, username, firstname, lastname, status)
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function initPage() {
    fetchUsersData();
}<commit_msg>Admin page<commit_after>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminPage");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserTitle");}, gvm);

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);
    gvm.userActions = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserActions");}, gvm);
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn");}, gvm);

    gvm.users = ko.observableArray([]);

    gvm.updateUsers = function(user)
    {
        gvm.users.push(user);
    },

    gvm.removeUser = function(user) {
        gvm.users.remove(user);
        removeUser(user);
    },

    gvm.refreshUsers = function()
    {
        gvm.users.destroyAll();
    }
}

function fetchUsersData()
{
    viewModel.refreshUsers();
    $.getJSON("/api/alluserswithroles/", function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            if (addedUsername != current){
                addedUsername = item.username;
                viewModel.updateUsers(new User(item.id, item.username, item.firstname, item.lastname, item.status));
            }
        });
    });
}

function removeUser(user)
{
    $.getJSON("/api/removeuser/" + user.id(), function(data)
    {
        console.log("User was removed");
        fetchUsersData();
    });
}

function User(id, username, firstname, lastname, status) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            //WORDT NOG NIET VERANDERD
            //WORDT NOG NIET OPGESLAAN OP DB
            console.log(status);
        }
    };
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showAddUserModal(id, username, firstname, lastname, status)
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function initPage() {
    fetchUsersData();
}<|endoftext|>


<commit_before>/*========================
EDIT BELOW
========================*/
var JSONUrl = "https://survival.gamealition.com/data/signshop.json";
var dynmapURL = "http://survival.gamealition.com:8123";
/*========================
EDIT ABOVE
========================*/

var ENCHANTS = {
    "ARROW_DAMAGE": "Power",
    "ARROW_FIRE": "Flame",
    "ARROW_INFINITE": "Infinity",
    "ARROW_KNOCKBACK": "Punch",
    "DAMAGE_ALL": "Sharpness",
    "DAMAGE_ARTHROPODS": "Bane of Arthropods",
    "DAMAGE_UNDEAD": "Smite",
    "DEPTH_STRIDER": "Depth Strider",
    "DIG_SPEED": "Efficiency",
    "DURABILITY": "Unbreaking",
    "FIRE_ASPECT": "Fire Aspect",
    "FROST_WALKER": "Frost Walker",
    "KNOCKBACK": "Knockback",
    "LOOT_BONUS_BLOCKS": "Fortune",
    "LOOT_BONUS_MOBS": "Looting",
    "LUCK": "Luck of the Sea",
    "LURE": "Lure",
    "MENDING": "Mending",
    "OXYGEN": "Respiration",
    "PROTECTION_ENVIRONMENTAL": "Protection",
    "PROTECTION_EXPLOSIONS": "Blast Protection",
    "PROTECTION_FALL": "Feather Falling",
    "PROTECTION_FIRE": "Fire Protection",
    "PROTECTION_PROJECTILE": "Projectile Protection",
    "SILK_TOUCH": "Silk Touch",
    "THORNS": "Thorns",
    "WATER_WORKER": "Aqua Affinity"
}
var NUMERALS = {
    "1": "I",
    "2": "II",
    "3": "III",
    "4": "IV",
    "5": "V"
}
var sorted;
var signShopData;
var result;
var $select = $("#itemselect");
$.ajax({
    url: "items.json",
    dataType: "JSON",
    success: function (data) {
        sorted = _.sortBy(data, "name")
        $.each(sorted, function (key, val) {
            $select.append("<option value='" + val.type + ":" + val.meta + "'>" + val.name + "</option>");
        })
    },
    error: function () {
        $select.html("<option value=''>ERROR! Could not load items!</option>");
    }
});
$("#itemselect").select2({
    placeholder: "Choose an item",
    allowClear: true
});

$.ajax({
    url: JSONUrl,
    dataType: "JSON",
    success: function (data) {
    },
    error: function () {
        alert("ERROR! Could not connect to the shop data!");
    }
});

function findshops() {
    var selecteditem = $('#itemselect option:selected').val();
    var itemname = $('#itemselect option:selected').text();
    var fields = selecteditem.split(/:/);
    var itemid = fields[0];
    var itemid2 = fields[1];
    var matches = [];
    var displayedmatches = [];
    $.each(sortedbyprice, function (key, val) {
        $.each(val.invItems, function (key2, val2) {
            var type = val2.type;
            var durability = val2.durability;
            if (type == itemid && durability == itemid2 && (val.signType == "buy" || val.signType == "sell" || val.signType == "ibuy" || val.signType == "isell")) {

                $("#2").text(val.amount);
                matches.push(val);

            }
        });

    });
    if (matches.length == 0) {
        $("#responsecontainer").addClass("hide");
        $("#1").text("Error! No shops found with that item!");
        $("#2").text("");
    } else {
        $("#responsecontainer").empty();
        $("#responsecontainer").removeClass("hide");
        $("#1").text("");
        $("#2").text("Fetched " + matches.length + " results. Displaying sorted by price.")
        $.each(matches, function (key3, val3) {

            $.each(val3.invItems, function (key4, val4) {
                if (val4.type != itemid || val4.durability != itemid2) {
                    return;
                }
                var $signtype = val3.signType;
                var $amount = val4.amount;
                var $signprice = val3.signPrice;
                var $ownername = val3.ownerName;
                var $locworld = val3.locWorld;
                var $x = val3.locX;
                var $y = val3.locY;
                var $z = val3.locZ;
                if ($signtype == "ibuy" || $signtype == "isell") {
                    var $invinstock = "infinite";
                } else {
                    var $invinstock = val3.invInStock;
                }
                var currentmatch = {
                    signType: $signtype,
                    amount: $amount,
                    signPrice: $signprice,
                    ownerName: $ownername,
                    locWorld: $locworld,
                    locX: $x,
                    locY: $y,
                    locZ: $z,
                    invInStock: $invinstock
                };

                displayedmatches.push(val3);

            });

        });

        matches.length = 0;

        $.each(displayedmatches, function (key5, val5) {
            $.each(val5.invItems, function (key6, val6) {

                var enchants = val6.meta.enchantments,
                    enchantLabels = [],
                    enchant = null,
                    level = null;
                for (enchant in enchants) {
                    level = enchants[enchant];
                    enchantLabels.push(ENCHANTS[enchant] + " " + NUMERALS[level]);

                }

                if (enchants == null) {
                    var displayedenchant = "none";
                } else {
                    var displayedenchant = enchantLabels.join(", ");
                }
                if (val5.signType == "ibuy" || val5.signType == "isell") {
                    var $invinstock = "infinite";
                } else {
                    var $invinstock = val5.invInStock;
                }
                if ($invinstock == false) {
                    var textColor = "red-text";
                } else {
                    var textColor = "green-text";
                }

                var $appendrow = $("

" + itemname + "

Owner:

" + val5.ownerName + "

Enchantments:

" + displayedenchant + "

Location:

" + val5.locWorld + " @ " + val5.locX + ", " + val5.locY + ", " + val5.locZ + "

In Stock?: " + $invinstock + "

" + val5.signType + " " + val6.amount + " for G" + val5.signPrice + "

");
                $appendrow.appendTo("#responsecontainer");
            });

        });

    }
}
<commit_msg>quick fix<commit_after>/*========================
EDIT BELOW
========================*/
var JSONUrl = "https://survival.gamealition.com/data/signshop.json";
var dynmapURL = "http://survival.gamealition.com:8123";
/*========================
EDIT ABOVE
========================*/

var ENCHANTS = {
    "ARROW_DAMAGE": "Power",
    "ARROW_FIRE": "Flame",
    "ARROW_INFINITE": "Infinity",
    "ARROW_KNOCKBACK": "Punch",
    "DAMAGE_ALL": "Sharpness",
    "DAMAGE_ARTHROPODS": "Bane of Arthropods",
    "DAMAGE_UNDEAD": "Smite",
    "DEPTH_STRIDER": "Depth Strider",
    "DIG_SPEED": "Efficiency",
    "DURABILITY": "Unbreaking",
    "FIRE_ASPECT": "Fire Aspect",
    "FROST_WALKER": "Frost Walker",
    "KNOCKBACK": "Knockback",
    "LOOT_BONUS_BLOCKS": "Fortune",
    "LOOT_BONUS_MOBS": "Looting",
    "LUCK": "Luck of the Sea",
    "LURE": "Lure",
    "MENDING": "Mending",
    "OXYGEN": "Respiration",
    "PROTECTION_ENVIRONMENTAL": "Protection",
    "PROTECTION_EXPLOSIONS": "Blast Protection",
    "PROTECTION_FALL": "Feather Falling",
    "PROTECTION_FIRE": "Fire Protection",
    "PROTECTION_PROJECTILE": "Projectile Protection",
    "SILK_TOUCH": "Silk Touch",
    "THORNS": "Thorns",
    "WATER_WORKER": "Aqua Affinity"
}
var NUMERALS = {
    "1": "I",
    "2": "II",
    "3": "III",
    "4": "IV",
    "5": "V"
}
var sorted;
var signShopData;
var result;
var $select = $("#itemselect");
$.ajax({
    url: "items.json",
    dataType: "JSON",
    success: function (data) {
        sorted = _.sortBy(data, "name")
        $.each(sorted, function (key, val) {
            $select.append("<option value='" + val.type + ":" + val.meta + "'>" + val.name + "</option>");
        })
    },
    error: function () {
        $select.html("<option value=''>ERROR! Could not load items!</option>");
    }
});
$("#itemselect").select2({
    placeholder: "Choose an item",
    allowClear: true
});

$.ajax({
    url: JSONUrl,
    dataType: "JSON",
    success: function (data) {
        sortedbyprice = _.sortBy(data, "signPrice");
    },
    error: function () {
        alert("ERROR! Could not connect to the shop data!");
    }
});

function findshops() {
    var selecteditem = $('#itemselect option:selected').val();
    var itemname = $('#itemselect option:selected').text();
    var fields = selecteditem.split(/:/);
    var itemid = fields[0];
    var itemid2 = fields[1];
    var matches = [];
    var displayedmatches = [];
    $.each(sortedbyprice, function (key, val) {
        $.each(val.invItems, function (key2, val2) {
            var type = val2.type;
            var durability = val2.durability;
            if (type == itemid && durability == itemid2 && (val.signType == "buy" || val.signType == "sell" || val.signType == "ibuy" || val.signType == "isell")) {

                $("#2").text(val.amount);

                matches.push(val);

            }
        });

    });
    if (matches.length == 0) {
        $("#responsecontainer").addClass("hide");
        $("#1").text("Error! No shops found with that item!");
        $("#2").text("");
    } else {
        $("#responsecontainer").empty();
        $("#responsecontainer").removeClass("hide");
        $("#1").text("");
        $("#2").text("Fetched " + matches.length + " results. Displaying sorted by price.")
        $.each(matches, function (key3, val3) {

            $.each(val3.invItems, function (key4, val4) {
                if (val4.type != itemid || val4.durability != itemid2) {
                    return;
                }
                var $signtype = val3.signType;
                var $amount = val4.amount;
                var $signprice = val3.signPrice;
                var $ownername = val3.ownerName;
                var $locworld = val3.locWorld;
                var $x = val3.locX;
                var $y = val3.locY;
                var $z = val3.locZ;
                if ($signtype == "ibuy" || $signtype == "isell") {
                    var $invinstock = "infinite";
                } else {
                    var $invinstock = val3.invInStock;
                }
                var currentmatch = {
                    signType: $signtype,
                    amount: $amount,
                    signPrice: $signprice,
                    ownerName: $ownername,
                    locWorld: $locworld,
                    locX: $x,
                    locY: $y,
                    locZ: $z,
                    invInStock: $invinstock
                };

                displayedmatches.push(val3);

            });

        });

        matches.length = 0;

        $.each(displayedmatches, function (key5, val5) {
            $.each(val5.invItems, function (key6, val6) {

                var enchants = val6.meta.enchantments,
                    enchantLabels = [],
                    enchant = null,
                    level = null;
                for (enchant in enchants) {
                    level = enchants[enchant];
                    enchantLabels.push(ENCHANTS[enchant] + " " + NUMERALS[level]);

                }

                if (enchants == null) {
                    var displayedenchant = "none";
                } else {
                    var displayedenchant = enchantLabels.join(", ");
                }
                if (val5.signType == "ibuy" || val5.signType == "isell") {
                    var $invinstock = "infinite";
                } else {
                    var $invinstock = val5.invInStock;
                }
                if ($invinstock == false) {
                    var textColor = "red-text";
                } else {
                    var textColor = "green-text";
                }

                var $appendrow = $("

" + itemname + "

Owner:

" + val5.ownerName + "

Enchantments:

" + displayedenchant + "

Location:

" + val5.locWorld + " @ " + val5.locX + ", " + val5.locY + ", " + val5.locZ + "

In Stock?: " + $invinstock + "

" + val5.signType + " " + val6.amount + " for G" + val5.signPrice + "

");
                $appendrow.appendTo("#responsecontainer");
            });

        });

    }
}<|endoftext|>