<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Zest from 'react-zest';

import {
	Menu,
	Container,
	Segment,
	Grid,
	Divider,
	Header,
	Image,
	Message,
	Icon,
	Statistic,
	Accordion,
	Card
} from 'semantic-ui-react'

import RenderPolygons from './components/Polygons'

const items = [
	{ color: 'blue', label: 'Downloads', value: '3,200' },
	{ color: 'violet', label: 'Likes', value: '10,000' },
	{ color: 'red', label: 'Faves', value: '22' },
	{ color: 'orange', label: 'Views', value: '31,200' },
	{ color: 'yellow', label: 'Members', value: '22' },
]

class App extends Component {

	constructor(props) {
		super(props)
		this.state = {
			stageHeight: props.stageHeight,
			stageWidth: props.stageWidth,
			activeNavItem: props.activeNavItem,
			session: props.session,
			notification: props.notification
		}
		this.updateWindowDimensions = this.updateWindowDimensions.bind(this)
	}

	componentDidMount() {
		this.updateWindowDimensions()
		window.addEventListener('resize', this.updateWindowDimensions)
	}

	componentWillUnmount() {
		window.removeEventListener('resize', this.updateWindowDimensions)
	}

	updateWindowDimensions = () => this.setState({
		stageWidth: window.innerWidth,
		stageHeight: window.innerHeight
	})

	handleItemClick = (e, { name }) => this.setState({
		activeNavItem: name
	})

	handleLoginClick = (e, { name }) => this.setState({
		sessionState: '1'
	})

	handleLogoutClick = (e, { name }) => this.setState({
		sessionState: '-1'
	})

	render() {

		const {
			activeNavItem,
			session,
			notification,
			stageWidth,
			stageHeight
		} = this.state

		return (

{
				//

				// 	<RenderPolygons
				// 		width={stageWidth}
				// 		height={stageHeight}
				// 		inverted
				// 		/>
				//

}
				<Container>

					<Menu pointing inverted secondary>
						<Menu.Item name='home' active={activeNavItem === 'home'} onClick={this.handleItemClick} />
						<Menu.Item name='messages' active={activeNavItem === 'messages'} onClick={this.handleItemClick} />
						<Menu.Item name='friends' active={activeNavItem === 'friends'} onClick={this.handleItemClick} />
						<Menu.Menu position='right'>
							{
								session &&
								<Menu.Item name='logout' active={activeNavItem === 'logout'} onClick={this.handleLogoutClick} />
							}
							{
								!session &&
								<Menu.Item name='login' active={activeNavItem === 'login'} onClick={this.handleLoginClick} />
							}
						</Menu.Menu>
					</Menu>

					{ notification &&
						<Message color={notification.color}>
							<Icon name={notification.icon} loading />
							<Message.Content>
								<Message.Header>{notification.header}</Message.Header>
									{notification.content}
							</Message.Content>
						</Message>
					}

					<Segment className='landing-top' inverted>

						<Image src='/main-logo.png' size='large' centered />

						<Image src='/header-1.png' centered />

						<Image src='/timer.png' centered />

						<Image src='/header-2.png' centered />

					</Segment>

			        <Divider horizontal inverted>What we do</Divider>

					<Segment className='landing-top' inverted>

						<Grid stackable divided='vertically'>
							<Grid.Row columns={2}>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
							</Grid.Row>

							<Grid.Row columns={3}>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
							</Grid.Row>
						</Grid>

					</Segment>

			        <Divider horizontal inverted>Partners</Divider>

					<Segment inverted>

							<Icon name='users' circular />

								Friends

						<Image centered size='large' src='/centered-paragraph.png' />
					</Segment>

			        <Divider horizontal inverted>Core Team</Divider>

					<Segment inverted>

						<Card.Group itemsPerRow={4}>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
						</Card.Group>

					</Segment>

			        <Divider horizontal inverted>Ambassadors & Associates</Divider>

					<Segment inverted>

						<Card.Group itemsPerRow={4}>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
						</Card.Group>

					</Segment>

			        <Divider horizontal inverted>Frequently asked Questions</Divider>

					<Segment>
						<Accordion>
							<Accordion.Title>
								<Icon name='dropdown' />
								What is a dog?
							</Accordion.Title>
							<Accordion.Content>

								A dog is a type of domesticated animal. Known for its loyalty and faithfulness,
								{' '}it can be found as a welcome guest in many households across the world.

							</Accordion.Content>
							<Accordion.Title>
								<Icon name='dropdown' />
								What kinds of dogs are there?
							</Accordion.Title>
							<Accordion.Content>

								There are many breeds of dogs. Each breed varies in size and temperament.
								{' '}Owners often select a breed of dog that they find to be compatible
								with their own lifestyle and desires from a companion.

							</Accordion.Content>
							<Accordion.Title>
								<Icon name='dropdown' />
								How do you acquire a dog?
							</Accordion.Title>
							<Accordion.Content>

								Three common ways for a prospective owner to acquire a dog is from pet shops,
								{' '}private owners, or shelters.

 A pet shop may be the most convenient way to buy a dog.
								{' '}Buying a dog from a private owner allows you to assess the pedigree and
								{' '}upbringing of your dog before choosing to take it home. Lastly, finding your dog
								{' '}from a shelter, helps give a good home to a dog who may not find one so readily.

							</Accordion.Content>
						</Accordion>
  					</Segment>

					<Segment className='landing-bottom' inverted>
							<Statistic.Group items={items} />

					</Segment>

				</Container>

		)
	}
}

App.propTypes = {
	activeNavItem: PropTypes.string,
	stageHeight: PropTypes.number,
	stageWidth: PropTypes.number,
	notification: PropTypes.object,
	session: PropTypes.string
}

App.defaultProps = {
	stageHeight: 0,
	stageWidth: 0,
	activeNavItem:'home',
	session:'-1',
	notification: null
	// {
	// 	color: 'green',
	// 	icon: 'circle notched',
	// 	header: 'This is a message',
	// 	content: 'Some content may show up here.'
	// }
}

export default App
<commit_msg>feat(mockup): enable stars<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Zest from 'react-zest';

import {
	Menu,
	Container,
	Segment,
	Grid,
	Divider,
	Header,
	Image,
	Message,
	Icon,
	Statistic,
	Accordion,
	Card
} from 'semantic-ui-react'

import RenderPolygons from './components/Polygons'

const items = [
	{ color: 'blue', label: 'Downloads', value: '3,200' },
	{ color: 'violet', label: 'Likes', value: '10,000' },
	{ color: 'red', label: 'Faves', value: '22' },
	{ color: 'orange', label: 'Views', value: '31,200' },
	{ color: 'yellow', label: 'Members', value: '22' },
]

class App extends Component {

	constructor(props) {
		super(props)
		this.state = {
			stageHeight: props.stageHeight,
			stageWidth: props.stageWidth,
			activeNavItem: props.activeNavItem,
			session: props.session,
			notification: props.notification
		}
		this.updateWindowDimensions = this.updateWindowDimensions.bind(this)
	}

	componentDidMount() {
		this.updateWindowDimensions()
		window.addEventListener('resize', this.updateWindowDimensions)
	}

	componentWillUnmount() {
		window.removeEventListener('resize', this.updateWindowDimensions)
	}

	updateWindowDimensions = () => this.setState({
		stageWidth: window.innerWidth,
		stageHeight: window.innerHeight
	})

	handleItemClick = (e, { name }) => this.setState({
		activeNavItem: name
	})

	handleLoginClick = (e, { name }) => this.setState({
		sessionState: '1'
	})

	handleLogoutClick = (e, { name }) => this.setState({
		sessionState: '-1'
	})

	render() {

		const {
			activeNavItem,
			session,
			notification,
			stageWidth,
			stageHeight
		} = this.state

		return (

{

					<RenderPolygons
						width={stageWidth}
						height={stageHeight}
						inverted
						/>

}
				<Container>

					<Menu pointing inverted secondary>
						<Menu.Item name='home' active={activeNavItem === 'home'} onClick={this.handleItemClick} />
						<Menu.Item name='messages' active={activeNavItem === 'messages'} onClick={this.handleItemClick} />
						<Menu.Item name='friends' active={activeNavItem === 'friends'} onClick={this.handleItemClick} />
						<Menu.Menu position='right'>
							{
								session &&
								<Menu.Item name='logout' active={activeNavItem === 'logout'} onClick={this.handleLogoutClick} />
							}
							{
								!session &&
								<Menu.Item name='login' active={activeNavItem === 'login'} onClick={this.handleLoginClick} />
							}
						</Menu.Menu>
					</Menu>

					{ notification &&
						<Message color={notification.color}>
							<Icon name={notification.icon} loading />
							<Message.Content>
								<Message.Header>{notification.header}</Message.Header>
									{notification.content}
							</Message.Content>
						</Message>
					}

					<Segment className='landing-top' inverted>

						<Image src='/main-logo.png' size='large' centered />

						<Image src='/header-1.png' centered />

						<Image src='/timer.png' centered />

						<Image src='/header-2.png' centered />

					</Segment>

			        <Divider horizontal inverted>What we do</Divider>

					<Segment className='landing-top' inverted>

						<Grid stackable divided='vertically'>
							<Grid.Row columns={2}>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
							</Grid.Row>

							<Grid.Row columns={3}>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
								<Grid.Column>
									<Image src='/paragraph.png' />
								</Grid.Column>
							</Grid.Row>
						</Grid>

					</Segment>

			        <Divider horizontal inverted>Partners</Divider>

					<Segment inverted>

							<Icon name='users' circular />

								Friends

						<Image centered size='large' src='/centered-paragraph.png' />
					</Segment>

			        <Divider horizontal inverted>Core Team</Divider>

					<Segment inverted>

						<Card.Group itemsPerRow={4}>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
						</Card.Group>

					</Segment>

			        <Divider horizontal inverted>Ambassadors & Associates</Divider>

					<Segment inverted>

						<Card.Group itemsPerRow={4}>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
							<Card>
								<Card.Content>
									<Card.Header>Matthew Harris</Card.Header>
									<Card.Meta>Co-Worker</Card.Meta>
									<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
								</Card.Content>
							</Card>

							<Card>
								<Card.Content>
									<Card.Header content='Jake Smith' />
									<Card.Meta content='Musicians' />
									<Card.Description content='Jake is a drummer living in New York.' />
								</Card.Content>
							</Card>

							<Card>
								<Card.Content
									header='Elliot Baker'
									meta='Friend'
									description='Elliot is a music producer living in Chicago.'
									/>
							</Card>

							<Card
								header='Jenny Hess'
								meta='Friend'
								description='Jenny is a student studying Media Management at the New School'
								/>
						</Card.Group>

					</Segment>

			        <Divider horizontal inverted>Frequently asked Questions</Divider>

					<Segment>
						<Accordion>
							<Accordion.Title>
								<Icon name='dropdown' />
								What is a dog?
							</Accordion.Title>
							<Accordion.Content>

								A dog is a type of domesticated animal. Known for its loyalty and faithfulness,
								{' '}it can be found as a welcome guest in many households across the world.

							</Accordion.Content>
							<Accordion.Title>
								<Icon name='dropdown' />
								What kinds of dogs are there?
							</Accordion.Title>
							<Accordion.Content>

								There are many breeds of dogs. Each breed varies in size and temperament.
								{' '}Owners often select a breed of dog that they find to be compatible
								with their own lifestyle and desires from a companion.

							</Accordion.Content>
							<Accordion.Title>
								<Icon name='dropdown' />
								How do you acquire a dog?
							</Accordion.Title>
							<Accordion.Content>

								Three common ways for a prospective owner to acquire a dog is from pet shops,
								{' '}private owners, or shelters.

 A pet shop may be the most convenient way to buy a dog.
								{' '}Buying a dog from a private owner allows you to assess the pedigree and
								{' '}upbringing of your dog before choosing to take it home. Lastly, finding your dog
								{' '}from a shelter, helps give a good home to a dog who may not find one so readily.

							</Accordion.Content>
						</Accordion>
  					</Segment>

					<Segment className='landing-bottom' inverted>
							<Statistic.Group items={items} />

					</Segment>

				</Container>

		)
	}
}

App.propTypes = {
	activeNavItem: PropTypes.string,
	stageHeight: PropTypes.number,
	stageWidth: PropTypes.number,
	notification: PropTypes.object,
	session: PropTypes.string
}

App.defaultProps = {
	stageHeight: 0,
	stageWidth: 0,
	activeNavItem:'home',
	session:'-1',
	notification: null
	// {
	// 	color: 'green',
	// 	icon: 'circle notched',
	// 	header: 'This is a message',
	// 	content: 'Some content may show up here.'
	// }
}

export default App
<|endoftext|>


<commit_before>app.controller('HomeController', function ($scope) {
	// todo not sure what I want on the page yet, since we didn't have it before
});

app.controller('GamesController', function ($scope, $http) {
	$scope.currentPage = 0;
	$scope.pageSize = 10;
	$scope.games = [];
	$http.get('/Content/json/VideoGames.json').success(function (data) {
		$scope.games = data.VideoGames;
	});
	$scope.numberOfPages = function () {
		return Math.ceil($scope.games.length / $scope.pageSize);
	}
});

app.controller('ProfileController', function ($scope, $http, $window) {
	$scope.psnProfile = [];
	$scope.xblProfile = [];
	$http.get('Content/json/_psnProfile.xml.json').success(function (data) {
		$scope.psnProfile = data.PsnProfile;
		$scope.psnPointsPercent = 100 * data.PsnProfile.Points / data.PsnProfile.PossiblePoints;
		$scope.psnTrophiesPercent = 100 * data.PsnProfile.Trophies / data.PsnProfile.PossibleTrophies;
		$scope.psnTrophiesBronzePercent = 100 * data.PsnProfile.TrophiesBronze / data.PsnProfile.PossibleTrophiesBronze;
		$scope.psnTrophiesSilverPercent = 100 * data.PsnProfile.TrophiesSilver / data.PsnProfile.PossibleTrophiesSilver;
		$scope.psnTrophiesGoldPercent = 100 * data.PsnProfile.TrophiesGold / data.PsnProfile.PossibleTrophiesGold;
		$scope.psnTrophiesPlatinumPercent = 100 * data.PsnProfile.TrophiesPlatinum / data.PsnProfile.PossibleTrophiesPlatinum;
	});
	$http.get('Content/json/_xblProfile.xml.json').success(function (data) {
		$scope.xblProfile = data.XblProfile;
		$scope.xblPointsPercent = 100 * data.XblProfile.GamerScore / data.XblProfile.PossibleGamerScore;
		$scope.xblAchievementsPercent = 100 * data.XblProfile.Achievements / data.XblProfile.PossibleAchievements;
	});
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.quantityToPercent = function (obtained, total, percent) {
		if (total * percent / 100 <= obtained) {
			return "";
		} else {
			//50% = {{Math.round(xblProfile.PossibleAchievements * .50)}} (56)
			var numberAtPercent = $window.Math.round(total * percent / 100);
			return percent + "% = " + numberAtPercent + " (" + (numberAtPercent - obtained) + ")";
		}
	};

	// todo remove once I figure out what I'm doing with # of bronze trophies to percent display
	$scope.Math = window.Math;
});

app.controller('BasicsController', function ($scope, $http, $window) {
	$scope.psnGamesBasic = [];
	$scope.xblGamesBasic = [];
	$http.get('Content/json/_psnGamesBasic.xml.json').success(function (data) {
		$scope.psnGamesBasic = data.PsnGamesBasic;
	});
	$http.get('Content/json/_xblGamesBasic.xml.json').success(function (data) {
		$scope.xblGamesBasic = data.XblGamesBasic;
	});
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.extractDate = function (date) {
		var uglyDate = new Date(parseInt(date.substr(6)));
		return uglyDate;
	}
});

app.controller('PsnGameController', function ($scope, $http, $routeParams) {
	var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
	if (gameId != "") {
		$http.get('Content/json/_psnGames.xml.json').success(function (data) {
			for (var i = 0; i < data.PsnGames.length; i++) {
				if (data.PsnGames[i].Id == gameId) {
					$scope.game = data.PsnGames[i];
					break;
				}
			}
		});
	}
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.extractDate = function (date) {
		var uglyDate = new Date(parseInt(date.substr(6)));
		return uglyDate;
	}
	$scope.wasEarned = function (accomplishment) {
		return accomplishment.Earned != null;
	};
	$scope.notEarned = function (accomplishment) {
		return accomplishment.Earned == null;
	};
});

app.controller('XblGameController', function ($scope, $http, $routeParams) {
	var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
	if (gameId != "") {
		$http.get('Content/json/_xblGames.xml.json').success(function (data) {
			for (var i = 0; i < data.XblGames.length; i++) {
				if (data.XblGames[i].Id == gameId) {
					$scope.game = data.XblGames[i];
					break;
				}
			}
		});
	}
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.extractDate = function (date) {
		var uglyDate = new Date(parseInt(date.substr(6)));
		return uglyDate;
	}
	$scope.wasEarned = function (accomplishment) {
		return accomplishment.Earned != null;
	};
	$scope.notEarned = function (accomplishment) {
		return accomplishment.Earned == null;
	};
});

app.controller('NavbarController', function ($scope, $location) {
	$scope.getClass = function (path) {
		if ($location.path().substr(0, path.length) == path) {
			return true
		} else {
			return false;
		}
	}
});

// From http://jsfiddle.net/2ZzZB/56/
app.filter('startFrom', function () {
	return function (input, start) {
		start = +start; //parse to int
		return input.slice(start);
	}
});<commit_msg>Hack to fix extractDate errors.<commit_after>app.controller('HomeController', function ($scope) {
	// todo not sure what I want on the page yet, since we didn't have it before
});

app.controller('GamesController', function ($scope, $http) {
	$scope.currentPage = 0;
	$scope.pageSize = 10;
	$scope.games = [];
	$http.get('/Content/json/VideoGames.json').success(function (data) {
		$scope.games = data.VideoGames;
	});
	$scope.numberOfPages = function () {
		return Math.ceil($scope.games.length / $scope.pageSize);
	}
});

app.controller('ProfileController', function ($scope, $http, $window) {
	$scope.psnProfile = [];
	$scope.xblProfile = [];
	$http.get('Content/json/_psnProfile.xml.json').success(function (data) {
		$scope.psnProfile = data.PsnProfile;
		$scope.psnPointsPercent = 100 * data.PsnProfile.Points / data.PsnProfile.PossiblePoints;
		$scope.psnTrophiesPercent = 100 * data.PsnProfile.Trophies / data.PsnProfile.PossibleTrophies;
		$scope.psnTrophiesBronzePercent = 100 * data.PsnProfile.TrophiesBronze / data.PsnProfile.PossibleTrophiesBronze;
		$scope.psnTrophiesSilverPercent = 100 * data.PsnProfile.TrophiesSilver / data.PsnProfile.PossibleTrophiesSilver;
		$scope.psnTrophiesGoldPercent = 100 * data.PsnProfile.TrophiesGold / data.PsnProfile.PossibleTrophiesGold;
		$scope.psnTrophiesPlatinumPercent = 100 * data.PsnProfile.TrophiesPlatinum / data.PsnProfile.PossibleTrophiesPlatinum;
	});
	$http.get('Content/json/_xblProfile.xml.json').success(function (data) {
		$scope.xblProfile = data.XblProfile;
		$scope.xblPointsPercent = 100 * data.XblProfile.GamerScore / data.XblProfile.PossibleGamerScore;
		$scope.xblAchievementsPercent = 100 * data.XblProfile.Achievements / data.XblProfile.PossibleAchievements;
	});
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.quantityToPercent = function (obtained, total, percent) {
		if (total * percent / 100 <= obtained) {
			return "";
		} else {
			//50% = {{Math.round(xblProfile.PossibleAchievements * .50)}} (56)
			var numberAtPercent = $window.Math.round(total * percent / 100);
			return percent + "% = " + numberAtPercent + " (" + (numberAtPercent - obtained) + ")";
		}
	};

	// todo remove once I figure out what I'm doing with # of bronze trophies to percent display
	$scope.Math = window.Math;
});

app.controller('BasicsController', function ($scope, $http, $window) {
	$scope.psnGamesBasic = [];
	$scope.xblGamesBasic = [];
	$http.get('Content/json/_psnGamesBasic.xml.json').success(function (data) {
		$scope.psnGamesBasic = data.PsnGamesBasic;
	});
	$http.get('Content/json/_xblGamesBasic.xml.json').success(function (data) {
		$scope.xblGamesBasic = data.XblGamesBasic;
	});
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.extractDate = function (date) {
		if (date.length > 6) {
			var uglyDate = new Date(parseInt(date.substr(6)));
			return uglyDate;
		}
		return "";
	}
});

app.controller('PsnGameController', function ($scope, $http, $routeParams) {
	var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
	if (gameId != "") {
		$http.get('Content/json/_psnGames.xml.json').success(function (data) {
			for (var i = 0; i < data.PsnGames.length; i++) {
				if (data.PsnGames[i].Id == gameId) {
					$scope.game = data.PsnGames[i];
					break;
				}
			}
		});
	}
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.extractDate = function (date) {
		if (date != null) {
			var uglyDate = new Date(parseInt(date.substr(6)));
			return uglyDate;
		}
		return "";
	}
	$scope.wasEarned = function (accomplishment) {
		return accomplishment.Earned != null;
	};
	$scope.notEarned = function (accomplishment) {
		return accomplishment.Earned == null;
	};
});

app.controller('XblGameController', function ($scope, $http, $routeParams) {
	var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
	if (gameId != "") {
		$http.get('Content/json/_xblGames.xml.json').success(function (data) {
			for (var i = 0; i < data.XblGames.length; i++) {
				if (data.XblGames[i].Id == gameId) {
					$scope.game = data.XblGames[i];
					break;
				}
			}
		});
	}
	$scope.percentClass = function (percent) {
		return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
	};
	$scope.extractDate = function (date) {
		if (date != null) {
			var uglyDate = new Date(parseInt(date.substr(6)));
			return uglyDate;
		}
		return "";
	}
	$scope.wasEarned = function (accomplishment) {
		return accomplishment.Earned != null;
	};
	$scope.notEarned = function (accomplishment) {
		return accomplishment.Earned == null;
	};
});

app.controller('NavbarController', function ($scope, $location) {
	$scope.getClass = function (path) {
		if ($location.path().substr(0, path.length) == path) {
			return true
		} else {
			return false;
		}
	}
});

// From http://jsfiddle.net/2ZzZB/56/
app.filter('startFrom', function () {
	return function (input, start) {
		start = +start; //parse to int
		return input.slice(start);
	}
});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import './App.css';
import ErrorMsg from './ErrorMsg.js';
import LoadingMsg from './LoadingMsg.js';
import TimeTable from './TimeTable.js';
import UserLocation from './UserLocation.js';
import MapView from './MapView.js';

class App extends Component {
	constructor(props) {
		super(props);
		this.state = {};
	}

	componentDidMount() {
		var self = this;

		var currentURL = window.location.href;

		if (/niemi/.exec(currentURL)) {
			self.setState({
				lat:60.186269 ,lon:24.830909, maxDistance:1000, filterOut:'Otaniemi'
			});
		} else if (/kara/.exec(currentURL)) {
			self.setState({
				lat:[60.224655, 60.215923],
				lon:[24.759257, 24.753498],
				maxDistance:[300, 100]
			});
		} else if (/sello/.exec(currentURL)) {
			self.setState({
				lat:60.219378, lon:24.815121, maxDistance:325, filterOut:'Leppävaara'
			});
		} else if (/keskusta/.exec(currentURL)) {
			self.setState({
				lat:60.170508, lon:24.941104, maxDistance:300, filterOut:'Leppävaara'
			});
		} else if (/kamppi/.exec(currentURL)) {
			self.setState({
				lat:60.169038, lon:24.932908, maxDistance:100, filterOut:'Leppävaara'
			});
		}
		else {
			UserLocation.getUserLocation((loc) => {
				self.setState({
					lat:loc.coords.latitude, lon:loc.coords.longitude, maxDistance:500
				});
			}, (e) => {
				this.setState({error: {
					name: 'User location not available.',
					message: e.toString()
				}});
			});
		}
	}

	render() {
		if (this.state.hasOwnProperty('error')) {
			return (

					<ErrorMsg name={this.state.error.name} message={this.state.error.message}/>

			);
		}
		if ((!this.state.hasOwnProperty('lat') || !this.state.hasOwnProperty('lon')) && !this.state.hasOwnProperty('stopCode')) {
			return (

					<LoadingMsg name='User location' message={UserLocation.waitingForUserLocation}/>

			);
		}
		return (

					<TimeTable lat={this.state.lat} lon={this.state.lon} maxDistance={this.state.maxDistance} maxResults={15} filterOut={this.state.filterOut}/>

					<MapView
						lat={Array.isArray(this.state.lat) ? this.state.lat[0] : this.state.lat}
						lon={Array.isArray(this.state.lon) ? this.state.lon[0] : this.state.lon}
					/>

		);
	}
}

export default App;
<commit_msg>Modify options.<commit_after>import React, { Component } from 'react';
import './App.css';
import ErrorMsg from './ErrorMsg.js';
import LoadingMsg from './LoadingMsg.js';
import TimeTable from './TimeTable.js';
import UserLocation from './UserLocation.js';
import MapView from './MapView.js';

class App extends Component {
	constructor(props) {
		super(props);
		this.state = {};
	}

	componentDidMount() {
		var self = this;

		var currentURL = window.location.href;

		if (/kamppi/.exec(currentURL)) {
			self.setState({
				lat:60.169038, lon:24.932908, maxDistance:100, filterOut:'Leppävaara'
			});
		}
		else if (/kara/.exec(currentURL)) {
			self.setState({
				lat:[60.224655, 60.215923],
				lon:[24.759257, 24.753498],
				maxDistance:[300, 100]
			});
		} else if (/keskusta/.exec(currentURL)) {
			self.setState({
				lat:60.170508, lon:24.941104, maxDistance:300, filterOut:'Leppävaara'
			});
		} else if (/mattby/.exec(currentURL)) {
			self.setState({
				lat:60.161874, lon:24.739518, maxDistance:1000, filterOut:'Otaniemi'
			});
		} else if (/niemi/.exec(currentURL)) {
			self.setState({
				lat:60.186269 ,lon:24.830909, maxDistance:1000, filterOut:'Otaniemi'
			});
		} else if (/sello/.exec(currentURL)) {
			self.setState({
				lat:60.219378, lon:24.815121, maxDistance:325, filterOut:'Leppävaara'
			});
		} else  {
			UserLocation.getUserLocation((loc) => {
				self.setState({
					lat:loc.coords.latitude, lon:loc.coords.longitude, maxDistance:500
				});
			}, (e) => {
				this.setState({error: {
					name: 'User location not available.',
					message: e.toString()
				}});
			});
		}
	}

	render() {
		if (this.state.hasOwnProperty('error')) {
			return (

					<ErrorMsg name={this.state.error.name} message={this.state.error.message}/>

			);
		}
		if ((!this.state.hasOwnProperty('lat') || !this.state.hasOwnProperty('lon')) && !this.state.hasOwnProperty('stopCode')) {
			return (

					<LoadingMsg name='User location' message={UserLocation.waitingForUserLocation}/>

			);
		}
		return (

					<TimeTable lat={this.state.lat} lon={this.state.lon} maxDistance={this.state.maxDistance} maxResults={15} filterOut={this.state.filterOut}/>

					<MapView
						lat={Array.isArray(this.state.lat) ? this.state.lat[0] : this.state.lat}
						lon={Array.isArray(this.state.lon) ? this.state.lon[0] : this.state.lon}
					/>

		);
	}
}

export default App;
<|endoftext|>


<commit_before>// @flow
import React from 'react'
import PropTypes from 'prop-types'
import { shallow } from 'enzyme'

import { resetStyled, expectCSSMatches } from './utils'

let styled

describe('extending', () => {
  /**
   * Make sure the setup is the same for every test
   */
  beforeEach(() => {
    styled = resetStyled()
  })

  it('should generate empty classes with no styles', () => {
    const Parent = styled.div``
    const Child = Parent.extend``

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches('.sc-a {} .sc-b {}')
  })

  it('should attach styles to both classes if only parent has styles', () => {
    const Parent = styled.div`color: blue;`
    const Child = Parent.extend``

    shallow(<Parent />)
    shallow(<Child />)

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

  it('should attach styles to child class if only child has styles', () => {
    const Parent = styled.div``
    const Child = Parent.extend`color: blue;`

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches('.sc-a {} .sc-b {} .d { color: blue; }')
  })

  it('should generate a class for the child with the rules of the parent', () => {
    const Parent = styled.div`color: blue;`
    const Child = Parent.extend`color: red;`

    shallow(<Child />)

    expectCSSMatches('.sc-b {} .c { color: blue;color: red; }')
  })

  it('should generate different classes for both parent and child', () => {
    const Parent = styled.div`color: blue;`
    const Child = Parent.extend`color: red;`

    shallow(<Parent />)
    shallow(<Child />)

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

  it('should copy nested rules to the child', () => {
    const Parent = styled.div`
      color: blue;
      > h1 { font-size: 4rem; }
    `
    const Child = Parent.extend`color: red;`

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches(`
      .sc-a {}
      .c{ color: blue; }
      .c > h1{ font-size: 4rem; }
      .sc-b {}
      .d { color: blue; color: red; }
      .d > h1 { font-size: 4rem; }
    `)
  })

  it('should keep default props from parent', () => {
    const Parent = styled.div`
      color: ${(props) => props.color};
    `
    Parent.defaultProps = {
      color: 'red'
    }

    const Child = Parent.extend`background-color: green;`

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches(`
      .sc-a {} .c { color: red; }
      .sc-b {} .d { color: red; background-color: green; }
    `)
  })

  it('should keep prop types from parent', () => {
    const Parent = styled.div`
      color: ${(props) => props.color};
    `
    Parent.propTypes = {
      color: PropTypes.string
    }

    const Child = Parent.extend`background-color: green;`

    expect(Child.propTypes).toEqual(Parent.propTypes)
  })

  it('should keep custom static member from parent', () => {
    const Parent = styled.div`color: red;`

    Parent.fetchData = () => 1

    const Child = Parent.extend`color: green;`

    expect(Child.fetchData).toBeTruthy()
    expect(Child.fetchData()).toEqual(1)
  })

  it('should keep static member in triple inheritance', () => {
    const GrandParent = styled.div`color: red;`
    GrandParent.fetchData = () => 1

    const Parent = GrandParent.extend`color: red;`
    const Child = Parent.extend`color:red;`

    expect(Child.fetchData).toBeTruthy()
    expect(Child.fetchData()).toEqual(1)
  })

  it('should allow changing component', () => {
    const Parent = styled.div`color: red;`
    const Child = Parent.withComponent('span')

    expect(shallow(<Child />).html()).toEqual('')
  })

  it('should allow changing component and extending', () => {
    const Parent = styled.div`
      color: red;
    `
    const Child = Parent.withComponent('span').extend`
      color: green;
    `

    expect(shallow(<Child />).html()).toEqual('')
    expectCSSMatches(`
      .sc-c {} .d { color: red; color: green; }
    `)
  })
})
<commit_msg>Failing test: withComponent(...).attrs is not a function<commit_after>// @flow
import React from 'react'
import PropTypes from 'prop-types'
import { shallow } from 'enzyme'

import { resetStyled, expectCSSMatches } from './utils'

let styled

describe('extending', () => {
  /**
   * Make sure the setup is the same for every test
   */
  beforeEach(() => {
    styled = resetStyled()
  })

  it('should generate empty classes with no styles', () => {
    const Parent = styled.div``
    const Child = Parent.extend``

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches('.sc-a {} .sc-b {}')
  })

  it('should attach styles to both classes if only parent has styles', () => {
    const Parent = styled.div`color: blue;`
    const Child = Parent.extend``

    shallow(<Parent />)
    shallow(<Child />)

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

  it('should attach styles to child class if only child has styles', () => {
    const Parent = styled.div``
    const Child = Parent.extend`color: blue;`

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches('.sc-a {} .sc-b {} .d { color: blue; }')
  })

  it('should generate a class for the child with the rules of the parent', () => {
    const Parent = styled.div`color: blue;`
    const Child = Parent.extend`color: red;`

    shallow(<Child />)

    expectCSSMatches('.sc-b {} .c { color: blue;color: red; }')
  })

  it('should generate different classes for both parent and child', () => {
    const Parent = styled.div`color: blue;`
    const Child = Parent.extend`color: red;`

    shallow(<Parent />)
    shallow(<Child />)

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

  it('should copy nested rules to the child', () => {
    const Parent = styled.div`
      color: blue;
      > h1 { font-size: 4rem; }
    `
    const Child = Parent.extend`color: red;`

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches(`
      .sc-a {}
      .c{ color: blue; }
      .c > h1{ font-size: 4rem; }
      .sc-b {}
      .d { color: blue; color: red; }
      .d > h1 { font-size: 4rem; }
    `)
  })

  it('should keep default props from parent', () => {
    const Parent = styled.div`
      color: ${(props) => props.color};
    `
    Parent.defaultProps = {
      color: 'red'
    }

    const Child = Parent.extend`background-color: green;`

    shallow(<Parent />)
    shallow(<Child />)

    expectCSSMatches(`
      .sc-a {} .c { color: red; }
      .sc-b {} .d { color: red; background-color: green; }
    `)
  })

  it('should keep prop types from parent', () => {
    const Parent = styled.div`
      color: ${(props) => props.color};
    `
    Parent.propTypes = {
      color: PropTypes.string
    }

    const Child = Parent.extend`background-color: green;`

    expect(Child.propTypes).toEqual(Parent.propTypes)
  })

  it('should keep custom static member from parent', () => {
    const Parent = styled.div`color: red;`

    Parent.fetchData = () => 1

    const Child = Parent.extend`color: green;`

    expect(Child.fetchData).toBeTruthy()
    expect(Child.fetchData()).toEqual(1)
  })

  it('should keep static member in triple inheritance', () => {
    const GrandParent = styled.div`color: red;`
    GrandParent.fetchData = () => 1

    const Parent = GrandParent.extend`color: red;`
    const Child = Parent.extend`color:red;`

    expect(Child.fetchData).toBeTruthy()
    expect(Child.fetchData()).toEqual(1)
  })

  it('should allow changing component', () => {
    const Parent = styled.div`color: red;`
    const Child = Parent.withComponent('span')

    expect(shallow(<Child />).html()).toEqual('')
  })

  it('should allow changing component and extending', () => {
    const Parent = styled.div`
      color: red;
    `
    const Child = Parent.withComponent('span').extend`
      color: green;
    `

    expect(shallow(<Child />).html()).toEqual('')
    expectCSSMatches(`
      .sc-c {} .d { color: red; color: green; }
    `)
  })

  it('should allow changing component and adding attributes', () => {
    const Parent = styled.button`
      color: red;
    `
    const Child = Parent.withComponent('a').attrs({
      href: '/test'
    })``

    expect(shallow(<Child />).html()).toEqual('')
  })
})
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { createGraph } from './graph';

const EDGES = [
  ['technology', 'hardware'],
  ['technology', 'software'],
  ['technology', 'network'],
  ['hardware', 'computer'],
  ['hardware', 'large hadron collider'],
  ['large hadron collider', 'quantum mechanics'],
  ['quantum mechanics', 'quantum computer'],
  ['quantum computer', 'computer'],
  ['network', 'phone'],
  ['network', 'internet'],
  ['phone', 'mobile'],
  ['computer', 'mobile'],
  ['internet', 'cloud'],
  ['internet', 'html'],
  ['internet', 'communication'],
  ['phone', 'communication'],
  ['communication', 'satellite'],
  ['satellite', 'global positioning system'],
  ['mobile', 'global positioning system'],
  ['global positioning system', 'car'],
  ['elon musk', 'car'],
  ['elon musk', 'satellite'],
  ['elon musk', 'engineer'],
  ['engineer', 'steve wozniak'],
  ['engineer', 'bill gates'],
  ['windows', 'bill gates'],
  ['car', 'windows'],
  ['windows', 'operating system'],
  ['linux', 'operating system'],
  ['operating system', 'software'],
  ['linux', 'android'],
  ['android', 'mobile'],
  ['android', 'google'],
  ['google', 'internet'],
  ['android', 'robot'],
  ['robot', 'technology'],
  ['software', 'programming'],
  ['programming', 'keyboard'],
  ['keyboard', 'computer'],
  ['keyboard', 'space'],
  ['space', 'satellite'],
  ['programming', 'algorithm'],
  ['programming', 'programming language'],
  ['programming language', 'cobol'],
  ['programming language', 'c'],
  ['c', 'operating system'],
  ['google', 'car'],
];

const WIDTH = 1000, HEIGHT = 800;

const GRAPH = createGraph(EDGES, WIDTH, HEIGHT);

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nodeStates: {
        'technology': 'visible'
      },
      currentName: '',
    };
  }
  render() {
    return (

<Board graph={GRAPH} nodeStates={this.state.nodeStates} />

<input value={this.state.currentName} onChange={this.changeInput.bind(this)} />

    );
  }

  changeInput(e) {
    let currentName = e.target.value;
    this.setState({currentName: currentName});
  }

  guess(name) {
    if (!(GRAPH.nodeMap[name] && this.getNodeState(name) == 'visible')) {
      console.log('not guessing', name);
      return;
    }

    console.log('guessing', name);
    this.setNodeState(name, 'guessed');

    for (let [name1, name2] of GRAPH.edges) {
      if (name1 == name || name2 == name) {
	let otherName = name == name1 ? name2 : name1;
	if (this.getNodeState(otherName) === null) {
          this.setNodeState(otherName, 'visible');
	}
      }
    }
  }

  getNodeState(name) {
    return this.state.nodeStates[name] || null;
  }

  setNodeState(name, value) {
    this.setState({
      nodeStates: Object.assign({}, this.state.nodeStates, { [name]: value })
    });
  }
}

class Board extends Component {
  render() {
    let {graph, nodeStates} = this.props;
    return (
      <svg width={WIDTH} height={HEIGHT}>
        <rect x="0" y="0" width={WIDTH} height={HEIGHT} stroke="black" fill="white" strokeWidth="2"/>
        {graph.edges.map(([name1, name2], i) => <BoardEdge name1={name1} name2={name2} nodes={graph.nodes} key={i} />)}
        {graph.nodes.map(({name, x, y}, i) => <BoardNode name={name} x={x} y={y} state={nodeStates[name]} key={i} />)}
      </svg>
    );
  }
  shouldComponentUpdate(nextProps, nextState) {
    return nextProps !== this.props;
  }
}

function getNode(nodes, name) {
  for (let node of nodes)
    if (node.name == name)
      return node;
  throw new Error(`There is no such node: ${name}.`);
}

function BoardEdge({name1, name2, nodes}) {
  let n1 = getNode(nodes, name1), n2 = getNode(nodes, name2);
  return (
    <line x1={n1.x} y1={n1.y} x2={n2.x} y2={n2.y} stroke="black" strokeWidth="1" />
  );
}

function BoardNode({name, x, y, state}) {
  let h = 20, w = name.length * 10, padding = 5;
  let color = 'white';
  if (state == 'visible') color = 'yellow';
  else if (state == 'guessed') color = 'red';
  return (
    <g>
      <rect x={x-w/2-padding} y={y-h/2} width={w+padding*2} height={h} stroke="black" fill={color} strokeWidth="2" />
      <text x={x-w/2} y={y+h/4} fontFamily="monospace" fontSize="16">{name}</text>
    </g>
  );
}
<commit_msg>Fix guess()<commit_after>import React, { Component } from 'react';
import { createGraph } from './graph';

const EDGES = [
  ['technology', 'hardware'],
  ['technology', 'software'],
  ['technology', 'network'],
  ['hardware', 'computer'],
  ['hardware', 'large hadron collider'],
  ['large hadron collider', 'quantum mechanics'],
  ['quantum mechanics', 'quantum computer'],
  ['quantum computer', 'computer'],
  ['network', 'phone'],
  ['network', 'internet'],
  ['phone', 'mobile'],
  ['computer', 'mobile'],
  ['internet', 'cloud'],
  ['internet', 'html'],
  ['internet', 'communication'],
  ['phone', 'communication'],
  ['communication', 'satellite'],
  ['satellite', 'global positioning system'],
  ['mobile', 'global positioning system'],
  ['global positioning system', 'car'],
  ['elon musk', 'car'],
  ['elon musk', 'satellite'],
  ['elon musk', 'engineer'],
  ['engineer', 'steve wozniak'],
  ['engineer', 'bill gates'],
  ['windows', 'bill gates'],
  ['car', 'windows'],
  ['windows', 'operating system'],
  ['linux', 'operating system'],
  ['operating system', 'software'],
  ['linux', 'android'],
  ['android', 'mobile'],
  ['android', 'google'],
  ['google', 'internet'],
  ['android', 'robot'],
  ['robot', 'technology'],
  ['software', 'programming'],
  ['programming', 'keyboard'],
  ['keyboard', 'computer'],
  ['keyboard', 'space'],
  ['space', 'satellite'],
  ['programming', 'algorithm'],
  ['programming', 'programming language'],
  ['programming language', 'cobol'],
  ['programming language', 'c'],
  ['c', 'operating system'],
  ['google', 'car'],
];

const WIDTH = 1000, HEIGHT = 800;

const GRAPH = createGraph(EDGES, WIDTH, HEIGHT);

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nodeStates: {
        'technology': 'visible'
      },
      currentName: '',
    };
  }
  render() {
    return (

<Board graph={GRAPH} nodeStates={this.state.nodeStates} />

<input value={this.state.currentName} onChange={this.changeInput.bind(this)} />

    );
  }

  changeInput(e) {
    let currentName = e.target.value;
    this.setState({currentName: currentName});
  }

  guess(name) {
    if (!(GRAPH.nodeMap[name] && this.getNodeState(name) == 'visible')) {
      console.log('not guessing', name);
      return;
    }

    console.log('guessing', name);
    this.setNodeState(name, 'guessed');

    let nodeStates = Object.assign({}, nodeStates);
    for (let [name1, name2] of GRAPH.edges) {
      if (name1 == name || name2 == name) {
	let otherName = name == name1 ? name2 : name1;

        nodeStates[otherName] = 'visible';
      }
    }
    this.setState({nodeStates: nodeStates});
  }

  getNodeState(name) {
    return this.state.nodeStates[name] || null;
  }
}

class Board extends Component {
  render() {
    let {graph, nodeStates} = this.props;
    return (
      <svg width={WIDTH} height={HEIGHT}>
        <rect x="0" y="0" width={WIDTH} height={HEIGHT} stroke="black" fill="white" strokeWidth="2"/>
        {graph.edges.map(([name1, name2], i) => <BoardEdge name1={name1} name2={name2} nodes={graph.nodes} key={i} />)}
        {graph.nodes.map(({name, x, y}, i) => <BoardNode name={name} x={x} y={y} state={nodeStates[name]} key={i} />)}
      </svg>
    );
  }
  shouldComponentUpdate(nextProps, nextState) {
    return nextProps !== this.props;
  }
}

function getNode(nodes, name) {
  for (let node of nodes)
    if (node.name == name)
      return node;
  throw new Error(`There is no such node: ${name}.`);
}

function BoardEdge({name1, name2, nodes}) {
  let n1 = getNode(nodes, name1), n2 = getNode(nodes, name2);
  return (
    <line x1={n1.x} y1={n1.y} x2={n2.x} y2={n2.y} stroke="black" strokeWidth="1" />
  );
}

function BoardNode({name, x, y, state}) {
  let h = 20, w = name.length * 10, padding = 5;
  let color = 'white';
  if (state == 'visible') color = 'yellow';
  else if (state == 'guessed') color = 'red';
  return (
    <g>
      <rect x={x-w/2-padding} y={y-h/2} width={w+padding*2} height={h} stroke="black" fill={color} strokeWidth="2" />
      <text x={x-w/2} y={y+h/4} fontFamily="monospace" fontSize="16">{name}</text>
    </g>
  );
}
<|endoftext|>


<commit_before>var React = require('react');
var $ = require('jquery');
var ReactDOM = require('react-dom');
var Home = require('./Home');
var Application = require('./Application');
var WhatNext = require('./WhatNext');
var Footer = require('./Footer');
var Navbar = require('react-bootstrap').Navbar;

var App = React.createClass({
  getInitialState: function() {
    return {};
  },
  render: function () {
    return (

          <Navbar fixedTop={true} id='nav-section'>
            <Navbar.Brand className='text-center'>
              OverReact
            </Navbar.Brand>
          </Navbar>

          <Home />
          <Application />
          <WhatNext />

    )
  }
});

module.exports = App;

ReactDOM.render(<App />, document.getElementById('main'));
<commit_msg>fixed whatnext<commit_after>var React = require('react');
var $ = require('jquery');
var ReactDOM = require('react-dom');
var Home = require('./Home');
var Application = require('./Application');
var WhatNext = require('./Whatnext');
var Footer = require('./Footer');
var Navbar = require('react-bootstrap').Navbar;

var App = React.createClass({
  getInitialState: function() {
    return {};
  },
  render: function () {
    return (

          <Navbar fixedTop={true} id='nav-section'>
            <Navbar.Brand className='text-center'>
              OverReact
            </Navbar.Brand>
          </Navbar>

          <Home />
          <Application />
          <WhatNext />

    )
  }
});

module.exports = App;

ReactDOM.render(<App />, document.getElementById('main'));
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { createGraph } from './graph';

const EDGES = [
  ['technology', 'hardware'],
  ['technology', 'software'],
  ['technology', 'network'],
  ['hardware', 'computer'],
  ['hardware', 'large hadron collider'],
  ['large hadron collider', 'quantum mechanics'],
  ['quantum mechanics', 'quantum computer'],
  ['quantum computer', 'computer'],
  ['network', 'phone'],
  ['network', 'internet'],
  ['phone', 'mobile'],
  ['computer', 'mobile'],
  ['internet', 'cloud'],
  ['internet', 'html'],
  ['internet', 'communication'],
  ['phone', 'communication'],
  ['communication', 'satellite'],
  ['satellite', 'global positioning system'],
  ['mobile', 'global positioning system'],
  ['global positioning system', 'car'],
  ['elon musk', 'car'],
  ['elon musk', 'satellite'],
  ['elon musk', 'engineer'],
  ['engineer', 'steve wozniak'],
  ['engineer', 'bill gates'],
  ['windows', 'bill gates'],
  ['car', 'windows'],
  ['windows', 'operating system'],
  ['linux', 'operating system'],
  ['operating system', 'software'],
  ['linux', 'android'],
  ['android', 'mobile'],
  ['android', 'google'],
  ['google', 'internet'],
  ['android', 'robot'],
  ['robot', 'technology'],
  ['software', 'programming'],
  ['programming', 'keyboard'],
  ['keyboard', 'computer'],
  ['keyboard', 'space'],
  ['space', 'satellite'],
  ['programming', 'algorithm'],
  ['programming', 'programming language'],
  ['programming language', 'cobol'],
  ['programming language', 'c'],
  ['c', 'operating system'],
  ['google', 'car'],
];

const WIDTH = 1000, HEIGHT = 800;

const GRAPH = createGraph(EDGES, WIDTH, HEIGHT);

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nodeStates: {
        'technology': 'visible'
      },
      currentName: '',
    };
  }
  render() {
    return (

<Board graph={GRAPH} nodeStates={this.state.nodeStates} />

<input value={this.state.currentName} onChange={this.changeInput.bind(this)} />

    );
  }

  changeInput(e) {
    let currentName = e.target.value;
    this.setState({currentName: currentName});
  }

  guess(name) {
    if (!(GRAPH.nodeMap[name] && this.getNodeState(name) == 'visible')) {
      console.log('not guessing', name);
      return;
    }

    console.log('guessing', name);
    this.setNodeState(name, 'guessed');

    let nodeStates = Object.assign({}, nodeStates);
    for (let [name1, name2] of GRAPH.edges) {
      if (name1 == name || name2 == name) {
	let otherName = name == name1 ? name2 : name1;

        nodeStates[otherName] = 'visible';
      }
    }
    this.setState({nodeStates: nodeStates});
  }

  getNodeState(name) {
    return this.state.nodeStates[name] || null;
  }
}

class Board extends Component {
  render() {
    let {graph, nodeStates} = this.props;
    return (
      <svg width={WIDTH} height={HEIGHT}>
        <rect x="0" y="0" width={WIDTH} height={HEIGHT} stroke="black" fill="white" strokeWidth="2"/>
        {graph.edges.map(([name1, name2], i) => <BoardEdge name1={name1} name2={name2} nodes={graph.nodes} key={i} />)}
        {graph.nodes.map(({name, x, y}, i) => <BoardNode name={name} x={x} y={y} state={nodeStates[name]} key={i} />)}
      </svg>
    );
  }
  shouldComponentUpdate(nextProps, nextState) {
    return nextProps !== this.props;
  }
}

function getNode(nodes, name) {
  for (let node of nodes)
    if (node.name == name)
      return node;
  throw new Error(`There is no such node: ${name}.`);
}

function BoardEdge({name1, name2, nodes}) {
  let n1 = getNode(nodes, name1), n2 = getNode(nodes, name2);
  return (
    <line x1={n1.x} y1={n1.y} x2={n2.x} y2={n2.y} stroke="black" strokeWidth="1" />
  );
}

function BoardNode({name, x, y, state}) {
  let h = 20, w = name.length * 10, padding = 5;
  let color = 'white';
  if (state == 'visible') color = 'yellow';
  else if (state == 'guessed') color = 'red';
  return (
    <g>
      <rect x={x-w/2-padding} y={y-h/2} width={w+padding*2} height={h} stroke="black" fill={color} strokeWidth="2" />
      <text x={x-w/2} y={y+h/4} fontFamily="monospace" fontSize="16">{name}</text>
    </g>
  );
}
<commit_msg>Guess fixes<commit_after>import React, { Component } from 'react';
import { createGraph } from './graph';

const EDGES = [
  ['technology', 'hardware'],
  ['technology', 'software'],
  ['technology', 'network'],
  ['hardware', 'computer'],
  ['hardware', 'large hadron collider'],
  ['large hadron collider', 'quantum mechanics'],
  ['quantum mechanics', 'quantum computer'],
  ['quantum computer', 'computer'],
  ['network', 'phone'],
  ['network', 'internet'],
  ['phone', 'mobile'],
  ['computer', 'mobile'],
  ['internet', 'cloud'],
  ['internet', 'html'],
  ['internet', 'communication'],
  ['phone', 'communication'],
  ['communication', 'satellite'],
  ['satellite', 'global positioning system'],
  ['mobile', 'global positioning system'],
  ['global positioning system', 'car'],
  ['elon musk', 'car'],
  ['elon musk', 'satellite'],
  ['elon musk', 'engineer'],
  ['engineer', 'steve wozniak'],
  ['engineer', 'bill gates'],
  ['windows', 'bill gates'],
  ['car', 'windows'],
  ['windows', 'operating system'],
  ['linux', 'operating system'],
  ['operating system', 'software'],
  ['linux', 'android'],
  ['android', 'mobile'],
  ['android', 'google'],
  ['google', 'internet'],
  ['android', 'robot'],
  ['robot', 'technology'],
  ['software', 'programming'],
  ['programming', 'keyboard'],
  ['keyboard', 'computer'],
  ['keyboard', 'space'],
  ['space', 'satellite'],
  ['programming', 'algorithm'],
  ['programming', 'programming language'],
  ['programming language', 'cobol'],
  ['programming language', 'c'],
  ['c', 'operating system'],
  ['google', 'car'],
];

const WIDTH = 1000, HEIGHT = 800;

const GRAPH = createGraph(EDGES, WIDTH, HEIGHT);

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nodeStates: {
        'technology': 'visible'
      },
      currentName: '',
    };
  }
  render() {
    return (

<Board graph={GRAPH} nodeStates={this.state.nodeStates} />

<input value={this.state.currentName} onChange={this.changeInput.bind(this)} onKeyDown={this.keyDown.bind(this)} />

    );
  }

  changeInput(e) {
    let currentName = e.target.value;
    this.setState({currentName: currentName});
  }

  keyDown(e) {
    if (e.keyCode == 13) {
      this.guess(this.state.currentName);
      this.setState({currentName: ''});
    }
  }

  guess(name) {
    if (!(GRAPH.nodeMap[name] && this.getNodeState(name) == 'visible')) {
      console.log('not guessing', name);
      return;
    }

    console.log('guessing', name);
    let nodeStates = Object.assign({}, this.state.nodeStates);

    nodeStates[name] = 'guessed';

    for (let [name1, name2] of GRAPH.edges) {
      if (name1 == name || name2 == name) {
	let otherName = name == name1 ? name2 : name1;

	if (nodeStates[otherName] === undefined)
	  nodeStates[otherName] = 'visible';
      }
    }
    this.setState({nodeStates: nodeStates});
  }
}

class Board extends Component {
  render() {
    let {graph, nodeStates} = this.props;
    return (
      <svg width={WIDTH} height={HEIGHT}>
        <rect x="0" y="0" width={WIDTH} height={HEIGHT} stroke="black" fill="white" strokeWidth="2"/>
        {graph.edges.map(([name1, name2], i) => <BoardEdge name1={name1} name2={name2} nodes={graph.nodes} key={i} />)}
        {graph.nodes.map(({name, x, y}, i) => <BoardNode name={name} x={x} y={y} state={nodeStates[name]} key={i} />)}
      </svg>
    );
  }
  shouldComponentUpdate(nextProps, nextState) {
    return nextProps !== this.props;
  }
}

function getNode(nodes, name) {
  for (let node of nodes)
    if (node.name == name)
      return node;
  throw new Error(`There is no such node: ${name}.`);
}

function BoardEdge({name1, name2, nodes}) {
  let n1 = getNode(nodes, name1), n2 = getNode(nodes, name2);
  return (
    <line x1={n1.x} y1={n1.y} x2={n2.x} y2={n2.y} stroke="black" strokeWidth="1" />
  );
}

function BoardNode({name, x, y, state}) {
  let h = 20, w = name.length * 10, padding = 5;
  let color = 'white';
  if (state == 'visible') color = 'yellow';
  else if (state == 'guessed') color = 'red';

  return (
    <g>
      <rect x={x-w/2-padding} y={y-h/2} width={w+padding*2} height={h} stroke="black" fill={color} strokeWidth="2" />
      <text x={x-w/2} y={y+h/4} fontFamily="monospace" fontSize="16">{name}</text>
    </g>
  );
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Headers from './components/Headers';
import { SectionTitle } from './components/Section';

class App extends Component {
  render() {
    return (

        <Headers />
        <SectionTitle title="oiee" />

    );
  }
}

export default App;
<commit_msg>Add into App Career and Skills<commit_after>import React, { Component } from 'react';
import Headers from './components/Headers';
import Career from './components/Career';
import Skills  from './components/Skills';

class App extends Component {
  render() {
    return (

        <Headers />
        <Career />
        <Skills />

    );
  }
}

export default App;
<|endoftext|>


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

class App extends Component {

  render() {
    return (

        <Heading/>
        app content here

    );
  }

}

export default App;
<commit_msg>Show static list of users<commit_after>import React, { Component } from 'react';
import Heading from './Heading';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      users: [
        { name: { first: 'Alice', last: 'A' }, email: 'alice@example.com' },
        { name: { first: 'Bob', last: 'B' }, email: 'bob@example.com' },
        { name: { first: 'Charlie', last: 'C' }, email: 'charlie@example.com' }
      ]
    };
  }

  render() {
    return (

        <Heading/>
        {this.state.users.map(user =>

{user.name.first + ' ' + user.name.last + ' ' + user.email}

        )}

    );
  }

}

export default App;
<|endoftext|>


<commit_before>function PlatformGenerator(width, xFirst, yFirst) {
    this.width = width;

    this.xSpaceMin = 30;
    this.xSpaceRandom = 5;
    this.ySpaceMin = 60;
    this.ySpaceRandom = 10;

    this.platforms = [new Platform(xFirst, yFirst)];
}

PlatformGenerator.prototype.generatePlatforms = function(yLower, yUpper) {
    var highestPlatform = this.platforms[this.platforms.length - 1];

    var newPlatforms = this.platforms.filter(function(platform) {
        return platform.y <= yLower;
    });

    while (highestPlatform.y > yUpper) {
        var toss = Math.random() < 0.5 ? -1 : 1,
            dx = toss * (this.xSpaceMin + this.xSpaceRandom * Math.random()),
            dy = this.ySpaceMin + this.ySpaceRandom * Math.random();
        var x = Math.min(Math.max(highestPlatform.x + dx, 0), this.width);
        highestPlatform = new Platform(x, highestPlatform.y - dy);
        newPlatforms.push(highestPlatform);
    }

    this.platforms = newPlatforms;
};

<commit_msg>Round platform coordinates.<commit_after>function PlatformGenerator(width, xFirst, yFirst) {
    this.width = width;

    this.xSpaceMin = 30;
    this.xSpaceRandom = 5;
    this.ySpaceMin = 60;
    this.ySpaceRandom = 10;

    this.platforms = [new Platform(xFirst, yFirst)];
}

PlatformGenerator.prototype.generatePlatforms = function(yLower, yUpper) {
    var highestPlatform = this.platforms[this.platforms.length - 1];

    var newPlatforms = this.platforms.filter(function(platform) {
        return platform.y <= yLower;
    });

    while (highestPlatform.y > yUpper) {
        var toss = Math.random() < 0.5 ? -1 : 1,
            dx = toss * (this.xSpaceMin + this.xSpaceRandom * Math.random()),
            dy = this.ySpaceMin + this.ySpaceRandom * Math.random();
        var x = Math.min(Math.max(highestPlatform.x + dx, 0), this.width);
        highestPlatform = new Platform(Math.round(x),
            Math.round(highestPlatform.y - dy));
        newPlatforms.push(highestPlatform);
    }

    this.platforms = newPlatforms;
};

<|endoftext|>


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

'use strict';

const URL_TEST = 'www.google.com';

module.exports = {
	title: 'Connectivity tests',
	tests: [
		{
			title: 'Interface tests',
			tests: ['wired', 'wireless'].map(adaptor => {
				return {
					title: `${adaptor.charAt(0).toUpperCase()}${adaptor.slice(1)} test`,
					os: {
						type: 'object',
						required: ['network'],
						properties: {
							network: {
								type: 'object',
								required: [adaptor],
								properties: {
									[adaptor]: {
										type: 'boolean',
										const: true,
									},
								},
							},
						},
					},
					run: async function(test) {
						let testIface = adaptor === 'wireless' ? 'wifi' : 'ethernet';
						const iface = await this.context
							.get()
							.worker.executeCommandInHostOS(
								`nmcli d  | grep ' ${testIface} ' | grep connected | awk '{print $1}'`,
								this.context.get().link,
							);

						if (iface === '') {
							throw new Error(`No ${testIface} interface found.`);
						}

						let ping = await this.context
							.get()
							.worker.executeCommandInHostOS(
								`ping -c 10 -I ${iface} ${URL_TEST}`,
								this.context.get().link,
							);

						test.ok(
							ping.includes('10 packets transmitted, 10 packets received'),
							`${URL_TEST} responded over ${testIface}`,
						);
					},
				};
			}),
		},
		{
			title: 'Proxy tests',
			tests: ['socks5', 'http-connect'].map(proxy => {
				return {
					title: `${proxy.charAt(0).toUpperCase()}${proxy.slice(1)} test`,
					run: async function(test) {
						let getProxyContainerID = async() => {
							return this.context
								.get()
								.worker.executeCommandInHostOS(
									['balena', 'ps', '-qf', 'name=proxy'].join(' '),
									this.context.get().link
								);
						};

						const ip = await this.context.get()
							.worker.ip(this.context.get().link);

						// Ensure we only push and run the proxy container once
						if (!await getProxyContainerID()) {
							test.comment('Running proxy in container');
							const state = await this.context.get()
								.worker.pushContainerToDUT(ip, __dirname, 'proxy');
							test.comment(state);
						}

						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'mkdir -p /mnt/boot/system-proxy',
								this.context.get().link,
							);

						test.comment(`Creating redsocks.conf for ${proxy}...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'printf "' +
									'base { \n' +
									'log_debug = off; \n' +
									'log_info = on; \n' +
									'log = stderr; \n' +
									'daemon = off; \n' +
									'redirector = iptables; \n' +
									'} \n' +
									'redsocks { \n' +
									`type = ${proxy}; \n` +
									`ip = 127.0.0.1; \n` +
									`port = 8123; \n` +
									'local_ip = 127.0.0.1; \n' +
									'local_port = 12345; \n' +
									'} \n" > /mnt/boot/system-proxy/redsocks.conf',
								this.context.get().link,
							);

						// the supervisor would do this if proxy config were set via the supervisor sdk
						// https://www.balena.io/docs/reference/OS/network/2.x/#connecting-behind-a-proxy
						test.comment(`Manually restarting services...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'systemctl restart balena-proxy-config.service redsocks.service',
								this.context.get().link,
							);

						test.is(
							await this.context
								.get()
								.worker.executeCommandInHostOS(
									'systemctl is-active redsocks.service',
									this.context.get().link,
								),
							'active',
							'Redsocks proxy service should be active',
						);

						await this.context
							.get()
							.worker.executeCommandInHostOS(
								`curl -I https://${URL_TEST}`,
								this.context.get().link,
							);

						test.comment('Getting proxy container logs...');
						const proxyLog = await this.context
							.get()
							.worker.executeCommandInHostOS(
								['balena',
									'logs',
									await getProxyContainerID(),
									'|', 'tail', '-n1'].join(' '),
								this.context.get().link,
							);

						const pattern = {
							'socks5': new RegExp(/\[socks5\] 127\.0\.0\.1:[0-9]* <->/),
							'http-connect': new RegExp(/\[http\] 127\.0\.0\.1:[0-9]* <->/),
						}[proxy];

						test.comment(`Looking for ${proxy} connection logs...`);
						test.match(
							proxyLog,
							pattern,
							`${URL_TEST} responded over ${proxy} proxy`
						);

						test.comment(`Removing redsocks.conf...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'rm -rf /mnt/boot/system-proxy',
								this.context.get().link,
							);

						test.comment(`Manually restarting services...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'systemctl restart balena-proxy-config.service redsocks.service',
								this.context.get().link,
							);
					},
				};
			}),
		},
	],
};
<commit_msg>connectivity: reduce ping interval to minimum<commit_after>/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const URL_TEST = 'www.google.com';

module.exports = {
	title: 'Connectivity tests',
	tests: [
		{
			title: 'Interface tests',
			tests: ['wired', 'wireless'].map(adaptor => {
				return {
					title: `${adaptor.charAt(0).toUpperCase()}${adaptor.slice(1)} test`,
					os: {
						type: 'object',
						required: ['network'],
						properties: {
							network: {
								type: 'object',
								required: [adaptor],
								properties: {
									[adaptor]: {
										type: 'boolean',
										const: true,
									},
								},
							},
						},
					},
					run: async function(test) {
						let testIface = adaptor === 'wireless' ? 'wifi' : 'ethernet';
						const iface = await this.context
							.get()
							.worker.executeCommandInHostOS(
								`nmcli d  | grep ' ${testIface} ' | grep connected | awk '{print $1}'`,
								this.context.get().link,
							);

						if (iface === '') {
							throw new Error(`No ${testIface} interface found.`);
						}

						let ping = await this.context
							.get()
							.worker.executeCommandInHostOS(
								`ping -c 10 -i 0.002 -I ${iface} ${URL_TEST}`,
								this.context.get().link,
							);

						test.ok(
							ping.includes('10 packets transmitted, 10 packets received'),
							`${URL_TEST} responded over ${testIface}`,
						);
					},
				};
			}),
		},
		{
			title: 'Proxy tests',
			tests: ['socks5', 'http-connect'].map(proxy => {
				return {
					title: `${proxy.charAt(0).toUpperCase()}${proxy.slice(1)} test`,
					run: async function(test) {
						let getProxyContainerID = async() => {
							return this.context
								.get()
								.worker.executeCommandInHostOS(
									['balena', 'ps', '-qf', 'name=proxy'].join(' '),
									this.context.get().link
								);
						};

						const ip = await this.context.get()
							.worker.ip(this.context.get().link);

						// Ensure we only push and run the proxy container once
						if (!await getProxyContainerID()) {
							test.comment('Running proxy in container');
							const state = await this.context.get()
								.worker.pushContainerToDUT(ip, __dirname, 'proxy');
							test.comment(state);
						}

						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'mkdir -p /mnt/boot/system-proxy',
								this.context.get().link,
							);

						test.comment(`Creating redsocks.conf for ${proxy}...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'printf "' +
									'base { \n' +
									'log_debug = off; \n' +
									'log_info = on; \n' +
									'log = stderr; \n' +
									'daemon = off; \n' +
									'redirector = iptables; \n' +
									'} \n' +
									'redsocks { \n' +
									`type = ${proxy}; \n` +
									`ip = 127.0.0.1; \n` +
									`port = 8123; \n` +
									'local_ip = 127.0.0.1; \n' +
									'local_port = 12345; \n' +
									'} \n" > /mnt/boot/system-proxy/redsocks.conf',
								this.context.get().link,
							);

						// the supervisor would do this if proxy config were set via the supervisor sdk
						// https://www.balena.io/docs/reference/OS/network/2.x/#connecting-behind-a-proxy
						test.comment(`Manually restarting services...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'systemctl restart balena-proxy-config.service redsocks.service',
								this.context.get().link,
							);

						test.is(
							await this.context
								.get()
								.worker.executeCommandInHostOS(
									'systemctl is-active redsocks.service',
									this.context.get().link,
								),
							'active',
							'Redsocks proxy service should be active',
						);

						await this.context
							.get()
							.worker.executeCommandInHostOS(
								`curl -I https://${URL_TEST}`,
								this.context.get().link,
							);

						test.comment('Getting proxy container logs...');
						const proxyLog = await this.context
							.get()
							.worker.executeCommandInHostOS(
								['balena',
									'logs',
									await getProxyContainerID(),
									'|', 'tail', '-n1'].join(' '),
								this.context.get().link,
							);

						const pattern = {
							'socks5': new RegExp(/\[socks5\] 127\.0\.0\.1:[0-9]* <->/),
							'http-connect': new RegExp(/\[http\] 127\.0\.0\.1:[0-9]* <->/),
						}[proxy];

						test.comment(`Looking for ${proxy} connection logs...`);
						test.match(
							proxyLog,
							pattern,
							`${URL_TEST} responded over ${proxy} proxy`
						);

						test.comment(`Removing redsocks.conf...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'rm -rf /mnt/boot/system-proxy',
								this.context.get().link,
							);

						test.comment(`Manually restarting services...`);
						await this.context
							.get()
							.worker.executeCommandInHostOS(
								'systemctl restart balena-proxy-config.service redsocks.service',
								this.context.get().link,
							);
					},
				};
			}),
		},
	],
};
<|endoftext|>


<commit_before>"use strict";

var Game = function(player1, player2) {
  this.deck = [];
  this.players = [player1, player2];
};

Game.prototype.createDeck = function() {
  var suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'],
      ranks = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'],
      i,
      j;
  for (i = 0; i < 4; i++) {
    for (j = 0; j < 13; j++) {
      this.deck.push((ranks[j]) + ' of ' + (suits[i]));
    }
  }
};

Game.prototype.shuffleDeck = function() {
  var currentIndex = this.deck.length,
      temporaryValue = 0,
      randomIndex = 0;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = this.deck[currentIndex];
    this.deck[currentIndex] = this.deck[randomIndex];
    this.deck[randomIndex] = temporaryValue;
  }
  return this.deck;
};

Game.prototype.dealFirstHand = function() {
  var i;
  for (i = 0; i < 4; i += 2) {
    this.players[0].hand.push(this.deck.shift(i));
    this.players[1].hand.push(this.deck.shift((i + 1)));
  };
};

Game.prototype.calcCardScore = function(cardString) {
  var specialScores = { 'Jack':10, 'Queen':10, 'King':10, 'Ace':11 },
      card = cardString.split(' ')[0],
      score = 0;
  if (card in specialScores) {
    score = specialScores[card];
  } else { score = (parseInt(cardString.split(' ')[0], 10));
  };
  return score;
};

Game.prototype.scoreHand = function(player) {
  var hand = player.hand,
      points = [],
      score = 0,
      i;
  for (i = 0; i < hand.length ; i++) {
    points.push(this.calcCardScore(hand[i]));
  };
  points.reduce(function(previousValue, currentValue, currentIndex, array) {
    score = previousValue + currentValue;
  });
  if (score === 21) {
    return player.name + ' has won!';
  } else {
    return score
  };
};

module.exports = Game;<commit_msg>refractoring<commit_after>"use strict";

var Game = function(player1, player2) {
  this.deck = [];
  this.players = [player1, player2];
};

Game.prototype.createDeck = function() {
  var suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'],
      ranks = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'],
      i,
      j;
  for (i = 0; i < 4; i++) {
    for (j = 0; j < 13; j++) {
      this.deck.push((ranks[j]) + ' of ' + (suits[i]));
    }
  }
};

Game.prototype.shuffleDeck = function() {
  var currentIndex = this.deck.length,
      temporaryValue = 0,
      randomIndex = 0;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = this.deck[currentIndex];
    this.deck[currentIndex] = this.deck[randomIndex];
    this.deck[randomIndex] = temporaryValue;
  }
  return this.deck;
};

Game.prototype.dealFirstHand = function() {
  var i;
  for (i = 0; i < 4; i += 2) {
    this.players[0].hand.push(this.deck.shift(i));
    this.players[1].hand.push(this.deck.shift((i + 1)));
  };
};

Game.prototype.calcCardScore = function(cardString) {
  var specialScores = { 'Jack':10, 'Queen':10, 'King':10, 'Ace':11 },
      card = cardString.split(' ')[0],
      score = 0;
  if (card in specialScores) {
    score = specialScores[card];
  } else { score = (parseInt(cardString.split(' ')[0], 10));
  };
  return score;
};

Game.prototype.scoreHand = function(player) {
  var hand = player.hand,
      points = [],
      score = 0,
      i;
  for (i = 0; i < hand.length ; i++) {
    points.push(this.calcCardScore(hand[i]));
  };
  points.reduce(function(previousValue, currentValue, currentIndex, array) {
    score = previousValue + currentValue;
  });
  return (checkIfPerfectScore(player, score));
};

var checkIfPerfectScore = function(player, score) {
  if (score === 21) {
    return player.name + ' has won!';
  } else {
    return score
  };
};

module.exports = Game;<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint anon:true, sloppy:true, nomen:true, stupid:true, plusplus:true */
/*globals YUI*/

YUI().use('test', function(Y) {

    var suite = new Y.Test.Suite('version tests'),
        A = Y.Assert,
        AA = Y.ArrayAssert,
        OA = Y.ObjectAssert,

        libpath = require('path'),
        cmdpath = libpath.join(__dirname, '../../../../../lib/app/commands/version.js'),
        libutils = require(libpath.join(__dirname, '../../../../../lib/management/utils.js')),
        version = require(cmdpath);

    suite.add(new Y.Test.Case({

        name: 'version test cases',

        'test require': function() {
            A.isNotNull(version);
            A.isFunction(version.run, 'No run function exported');
            A.isString(version.usage, 'No usage string exported');
        },

        'test run mojito': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "log",
                args: [Y.Mock.Value.String],
                run: function (message) {
                    A.isTrue(/Version of mojito is/.test(message));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(null, null, function() {});
        },

        'test run mojito1': function() {
            try {
                version.run(null, null, function() {});
            } catch (e) {
                A.fail('Run exception: ' + e.message);
            }
        },

        'test run mojit': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "error",
                args: [Y.Mock.Value.Any],
                run: function (err) {
                    A.isTrue(/no such file or directory/.test(err));
                    A.isTrue(/mojits\/package.json/.test(err));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(["mojit"], null, function() {});
        },

        'test run app': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "error",
                args: [Y.Mock.Value.Any],
                run: function (err) {
                    A.isTrue(/no such file or directory/.test(err));
                    A.isTrue(/package.json/.test(err));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(["app"], null, function() {});
        },

        'test run wrong params': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "error",
                args: [Y.Mock.Value.Any],
                run: function (err) {
                    A.isTrue(/Unrecognized parameter: wrongparam/.test(err));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(["wrongparam"], null, function() {});
        }
    }));

    Y.Test.Runner.add(suite);
});
<commit_msg>partial fix issue #1053; pass "" to test instead of nothing<commit_after>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint anon:true, sloppy:true, nomen:true, stupid:true, plusplus:true */
/*globals YUI*/

YUI().use('test', function(Y) {

    var suite = new Y.Test.Suite('version tests'),
        A = Y.Assert,
        AA = Y.ArrayAssert,
        OA = Y.ObjectAssert,

        libpath = require('path'),
        cmdpath = libpath.join(__dirname, '../../../../../lib/app/commands/version.js'),
        libutils = require(libpath.join(__dirname, '../../../../../lib/management/utils.js')),
        version = require(cmdpath);

    suite.add(new Y.Test.Case({

        name: 'version test cases',

        'test require': function() {
            A.isNotNull(version);
            A.isFunction(version.run, 'No run function exported');
            A.isString(version.usage, 'No usage string exported');
        },

        'test run mojito': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "log",
                args: [Y.Mock.Value.String],
                run: function (message) {
                    A.isTrue(/Version of mojito is/.test(message));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(null, null, function() {});
        },

        'test run mojito1': function() {
            try {
                version.run(null, null, function() {});
            } catch (e) {
                A.fail('Run exception: ' + e.message);
            }
        },

        'test run mojit': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "error",
                args: [Y.Mock.Value.Any],
                run: function (err) {
                    A.isTrue(/no such file or directory/.test(err));
                    A.isTrue(/mojits\/package.json/.test(err));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(["mojit", ""], null, function() {});
        },

        'test run app': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "error",
                args: [Y.Mock.Value.Any],
                run: function (err) {
                    A.isTrue(/no such file or directory/.test(err));
                    A.isTrue(/package.json/.test(err));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(["app"], null, function() {});
        },

        'test run wrong params': function() {
            var mockConsole = Y.Mock();
            Y.Mock.expect(mockConsole, {
                method: "error",
                args: [Y.Mock.Value.Any],
                run: function (err) {
                    A.isTrue(/Unrecognized parameter: wrongparam/.test(err));
                }
            });
            libutils.test.setConsole(mockConsole);
            version.run(["wrongparam"], null, function() {});
        }
    }));

    Y.Test.Runner.add(suite);
});
<|endoftext|>


<commit_before>(function ($, window, undefined) {

/**
 * @module Assets-tools
 */

/**
 * Implements an input field that send search string to Amazon Product store and retrieve top ten relevant products
 * @class Assets Amazon tool
 * @constructor
 * @param {Object} [options] options to pass to this tool, so far nothing
 * @return {Q.Tool}
 */

Q.Tool.define("Assets/amazon/preview", "Streams/preview", function(options, preview) {

  if (!Q.Users.loggedInUser) {
      tool.element.style.display = 'none';
      console.warn("Assets/amazon: Don't render tool when user is not logged in");
      return;
  }

  var ps = preview.state;
  this.preview = preview;

  // proceed to construct the tool
  var tool = this;
  var state = tool.state;
  var $te = $(tool.element);

  // draw the tool
  ps.onRefresh.add(this.refresh.bind(this));

  $te.on(Q.Pointer.fastclick, '.Assets_amazon_results_item', tool, function () {

      var stream = tool.preview.stream;

      var asin = $(this).attr('data-asin');
      var title = $(this).attr('data-title');

      stream.fields.title = title;
      stream.set({'asin': asin, 'title': title});
      stream.save();

      console.log(stream);

      tool.filter = Q.Tool.from(tool.$('.Q_filter_tool'), 'Q/filter');
      tool.filter.input = tool.filter.$('.Q_filter_input');
      tool.filter.input.attr('value', '');
      tool.filter.input.next().show();
      tool.filter.end();
  }
  );

},

{ // DEFAULT OPTIONS
  onChoose: new Q.Event(),
  onSelect: new Q.Event(),
  onFilter: new Q.Event(),
  onCreate: new Q.Event(),
  onUpdate: new Q.Event(),
  onRefresh: new Q.Event()
},

{ // YOUR TOOL'S METHODS

  refresh: function (callback) {
    var tool = this;
    var state = tool.state;
    var $te = $(tool.element);

    $items = tool.$('[data-assets-amazon], .Assets_amazon_preview_tool');

    Q.Template.render(
        'Assets/amazon/response/wishlist',
        $items,
        function (err, html) {

            if (err) {
                return;
            }

            var options = {};

            var filterAmazon = Q.Tool.setUpElement(
                'div',
                'Q/filter',
                options,
                tool.prefix + 'filter'
            );

            Q.replace(tool.element, null);

            $(filterAmazon)
                .appendTo($te)
                .activate(
                    function () {

                        var tool = this;
                        var state = tool.state;

                        state.onFilter.set(
                          function (query, element) {

                              var latest = Q.latest(tool);

                              Q.req("Assets/amazon", 'results',
                                function (err, response) {

                                  if (Q.latest(tool, latest)) {

                                    var msg = Q.firstErrorMessage(err, response && response.errors);
                                    if (msg) {
                                        return console.warn(msg);
                                    }

                                    var results = response.slots.results;
                                    var fields = {results: ''};
                                    if (results) {
                                        fields = {results: results};
                                    }

                                    Q.Template.render(
                                        'Assets/amazon/response/results',
                                        fields,
                                        function (err, html) {
                                            $(element).html(html);
                                        }
                                    );
                                  }
                                },
                                {
                                  fields: {
                                      input: query
                                  }
                              });

                          }, tool);
                });

            $te.append(html);
            });
  },

  // optional methods for your tool
  // that would be called by Qbix
  Q: {
    onInit: function () {
      // occurs after onInit
      // of all child tools
    },
    beforeRemove: function () {
      // clean up anything you've attached
      // to the elements, such as
      // jQuery event handlers, data, etc.
    },
    onRetain: function (newOptions) {
      // compare newOptions to this.state
      // and update the tool's appearance.
      // after this event, the tool's
      // state will be extended with
      // the new options.
    },
    onLayout: function (elem, container) {
      // Occurs if the layout is being
      // updated for this tool's element.
      // If you want more fine-grained control
      // then use Q.onLayout(element) instead.
    }
  }
});

Q.Template.set('Assets/amazon/response/wishlist',
    '
'
    + '
'
    + '
Price:'
    + '
'
    + '{{&tool "Streams/inplace" inplaceType="text" inplace-placeholder="Name of the wish" attribute="title"}}
'
);

Q.Template.set('Assets/amazon/response/results',
    '{{#if results}}'
    + '
'
    + '{{#each results}}'
    + '
'
    + ''
    + '
'
    + '
{{title}}
'
    + '{{price}}'
    + '
'
    + '
'
    + '
'
    + '{{/each}}'
    + '
'
    + '{{/if}}'
);

})(window.jQuery, window);<commit_msg>share stream between tools for saving results<commit_after>(function ($, window, undefined) {

/**
 * @module Assets-tools
 */

/**
 * Implements an input field that send search string to Amazon Product store and retrieve top ten relevant products
 * @class Assets Amazon tool
 * @constructor
 * @param {Object} [options] options to pass to this tool, so far nothing
 * @return {Q.Tool}
 */

Q.Tool.define("Assets/amazon/preview", "Streams/preview", function(options, preview) {

  if (!Q.Users.loggedInUser) {
      tool.element.style.display = 'none';
      console.warn("Assets/amazon: Don't render tool when user is not logged in");
      return;
  }

  var ps = preview.state;
  this.preview = preview;

  // proceed to construct the tool
  var tool = this;
  var state = tool.state;
  var $te = $(tool.element);

  // draw the tool
  ps.onRefresh.add(this.refresh.bind(this));

  $te.on(Q.Pointer.fastclick, '.Assets_amazon_results_item', tool, function () {

      var stream = tool.preview.stream;

      var asin = $(this).attr('data-asin');
      var title = $(this).attr('data-title');

      stream.fields.title = title;
      stream.set({'asin': asin, 'title': title});
      stream.save();

      console.log(stream);

      tool.filter = Q.Tool.from(tool.$('.Q_filter_tool'), 'Q/filter');
      tool.filter.input = tool.filter.$('.Q_filter_input');
      tool.filter.input.attr('value', '');
      tool.filter.input.next().show();
      tool.filter.end();
  }
  );

},

{ // DEFAULT OPTIONS
  onChoose: new Q.Event(),
  onSelect: new Q.Event(),
  onFilter: new Q.Event(),
  onCreate: new Q.Event(),
  onUpdate: new Q.Event(),
  onRefresh: new Q.Event()
},

{ // YOUR TOOL'S METHODS

  refresh: function (callback) {
    var tool = this;
    var state = tool.state;
    var $te = $(tool.element);

    var stream = tool.stream = tool.preview.stream;

    $items = tool.$('[data-assets-amazon], .Assets_amazon_preview_tool');

    Q.Template.render(
        'Assets/amazon/response/wishlist',
        $items,
        function (err, html) {

            if (err) {
                return;
            }

            var options = {};

            var filterAmazon = Q.Tool.setUpElement(
                'div',
                'Q/filter',
                options,
                tool.prefix + 'filter'
            );

            Q.replace(tool.element, null);

            $(filterAmazon)
                .appendTo($te)
                .activate(
                    function () {

                        var tool = this;
                        var state = tool.state;

                        state.onFilter.set(
                          function (query, element) {

                              var latest = Q.latest(tool);

                              Q.req("Assets/amazon", 'results',
                                function (err, response) {

                                  if (Q.latest(tool, latest)) {

                                    var msg = Q.firstErrorMessage(err, response && response.errors);
                                    if (msg) {
                                        return console.warn(msg);
                                    }

                                    var results = response.slots.results;
                                    var fields = {results: ''};
                                    if (results) {
                                        fields = {results: results};
                                    }

                                    Q.Template.render(
                                        'Assets/amazon/response/results',
                                        fields,
                                        function (err, html) {
                                            $(element).html(html);
                                        }
                                    );
                                  }
                                },
                                {
                                  fields: {
                                      input: query
                                  }
                              });

                          }, tool);
                });

            $te.append(html);
            });
  },

  // optional methods for your tool
  // that would be called by Qbix
  Q: {
    onInit: function () {
      // occurs after onInit
      // of all child tools
    },
    beforeRemove: function () {
      // clean up anything you've attached
      // to the elements, such as
      // jQuery event handlers, data, etc.
    },
    onRetain: function (newOptions) {
      // compare newOptions to this.state
      // and update the tool's appearance.
      // after this event, the tool's
      // state will be extended with
      // the new options.
    },
    onLayout: function (elem, container) {
      // Occurs if the layout is being
      // updated for this tool's element.
      // If you want more fine-grained control
      // then use Q.onLayout(element) instead.
    }
  }
});

Q.Template.set('Assets/amazon/response/wishlist',
      ''
    + '{{&tool "Streams/inplace" stream=stream inplaceType="text" inplace-placeholder="Name of the good" attribute="asin"}}'

);

Q.Template.set('Assets/amazon/response/results',
    '{{#if results}}'
    + '
'
    + '{{#each results}}'
    + '
'
    + ''
    + '
'
    + '
{{title}}
'
    + '{{price}}'
    + '
'
    + '
'
    + '
'
    + '{{/each}}'
    + '
'
    + '{{/if}}'
);

})(window.jQuery, window);<|endoftext|>


<commit_before>import React, { Component } from 'react';
// // import logo from './logo.svg';
// import icon from './hr-logo-for-black.png';
// import smallIcon from './logoSmall.png';
// import hrText from './hr-text-for-black.png'
import './App.css';

class App extends Component {
  render() {
    return (

Mock Interview Manager

Interview Question List

          {this.props.children}

    )
  }
}

export default App;
<commit_msg>fix(menu): adjust menu width<commit_after>import React, { Component } from 'react';
// // import logo from './logo.svg';
// import icon from './hr-logo-for-black.png';
// import smallIcon from './logoSmall.png';
// import hrText from './hr-text-for-black.png'
import './App.css';

class App extends Component {
  render() {
    return (

Mock Interview Manager

Interview Question List

          {this.props.children}

    )
  }
}

export default App;
<|endoftext|>