<commit_before>// @flow

import * as React from 'react'
import {
	View,
	Text,
	TextInput,
	StyleSheet,
	ScrollView,
	TouchableHighlight,
	Image,
	Clipboard,
	Dimensions,
} from 'react-native'
import glamorous from 'glamorous-native'
import * as c from '../components/colors'
import type {Building, Feature} from './types'
import {parseLinkString} from './types'
import startCase from 'lodash/startCase'
import {Row, Column} from '../components/layout'
import {ListRow, Title} from '../components/list'
import openUrl from '../components/open-url'
import {Touchable} from '../components/touchable'

type Props = {
	feature: Feature<Building>,
	onClose: () => any,
	overlaySize: 'min' | 'mid' | 'max',
}

export class BuildingInfo extends React.Component<Props> {
	onClose = () => {
		this.props.onClose()
	}

	makeBuildingCategory = (building: Building) => {
		let blacklist = ['hall', 'house', 'building']
		return building.categories
			.filter(name => !blacklist.includes(name))
			.map(name => startCase(name))
			.join(' • ')
	}

	render() {
		let feature = this.props.feature
		let building = feature.properties
		let category = this.makeBuildingCategory(building)
		let photos = (building.photos || []).map(
			href => `https://carls-app.github.io/map-data/cache/img/${href}`,
		)

		let departments = building.departments.map(parseLinkString)
		let offices = building.offices.map(parseLinkString)

		let coordinates =
			feature.geometry.geometries.find(geo => geo.type === 'Point') || null
		coordinates = coordinates ? coordinates.coordinates : null

		return (
			<React.Fragment>
				<Row
					alignItems="center"
					justifyContent="space-between"
					marginBottom={12}
					style={styles.container}
				>
					<Column>
						<PlaceTitle>{building.name}</PlaceTitle>
						<PlaceSubtitle>{category}</PlaceSubtitle>
					</Column>
					<CloseButton onPress={this.onClose} />
				</Row>

				<ScrollView
					contentContainerStyle={styles.container}
					contentInsetAdjustmentBehavior="automatic"
					scrollEnabled={this.props.overlaySize === 'max'}
					style={styles.scroll}
				>
					{photos.length ? (

							<ScrollView horizontal={true}>
								{photos.map(href => (
									<Image key={href} source={{uri: href}} style={styles.photo} />
								))}
							</ScrollView>

					) : null}

					{building.address ? (

							<Row alignItems="center">
								<Column flex={1}>
									<SectionTitle>Address</SectionTitle>
									<SectionContent>{building.address}</SectionContent>
								</Column>
								<CopyText
									render={({copied, copy}) => (
										<OutlineButton
											disabled={copied}
											onPress={() => building.address && copy(building.address)}
											title={copied ? 'Copied' : 'Copy'}
										/>
									)}
								/>
							</Row>

					) : null}

					{building.description ? (

							<SectionTitle>Description</SectionTitle>
							<SectionSelectableContent>
								{building.description}
							</SectionSelectableContent>

					) : null}

					{departments.length ? (

							<SectionListTitle>Departments</SectionListTitle>
							<View>
								{departments.map(d => (
									<SectionListItem
										key={d.label}
										href={d.href}
										label={d.label}
									/>
								))}
							</View>

					) : null}

					{offices.length ? (

							<SectionListTitle>Offices</SectionListTitle>
							<View>
								{offices.map(d => (
									<SectionListItem
										key={d.label}
										href={d.href}
										label={d.label}
									/>
								))}
							</View>

					) : null}

					{coordinates ? (

							<Row alignItems="center">
								<Column flex={1}>
									<SectionTitle>Coordinates</SectionTitle>
									<SectionContent>{coordinates.join(', ')}</SectionContent>
								</Column>
								<CopyText
									render={({copied, copy}) => (
										<OutlineButton
											disabled={copied}
											onPress={() => copy((coordinates: any).join(', '))}
											title={copied ? 'Copied' : 'Copy'}
										/>
									)}
								/>
							</Row>

					) : null}
				</ScrollView>
			</React.Fragment>
		)
	}
}

const PlaceTitle = glamorous.text({fontSize: 20, fontWeight: '700'})
const PlaceSubtitle = glamorous.text({fontSize: 16})

const Section = glamorous.view({
	paddingVertical: 12,
	borderBottomWidth: StyleSheet.hairlineWidth,
	borderBottomColor: c.black75Percent,
})
const SectionTitle = glamorous.text({fontWeight: '700'})
const SectionContent = glamorous.text()
const SectionSelectableContent = ({children}) => (
	<TextInput dataDetectorTypes="all" editable={false} multiline={true}>
		{children}
	</TextInput>
)

const SectionListTitle = glamorous(SectionTitle)({
	paddingBottom: 8,
})

const OutlineButton = (props: {
	title: string,
	onPress: () => any,
	disabled: boolean,
}) => (
	<Touchable
		accessibilityTraits="button"
		disabled={props.disabled}
		onPress={props.onPress}
		style={[
			styles.outlineButton,
			props.disabled && styles.outlineButtonDisabled,
		]}
	>
		<Text
			style={[
				styles.outlineButtonText,
				props.disabled && styles.outlineButtonTextDisabled,
			]}
		>
			{props.title}
		</Text>
	</Touchable>
)

class CopyText extends React.Component<
	{render: ({copied: boolean, copy: string => any}) => React.Node},
	{copied: boolean},
> {
	state = {
		copied: false,
	}

	onCopy = (text: string) => {
		Clipboard.setString(text)
		this.setState(() => ({copied: true}))
	}

	render() {
		return this.props.render({copied: this.state.copied, copy: this.onCopy})
	}
}

const SectionListItem = ({href, label}) => {
	return (
		<ListRow
			contentContainerStyle={styles.listItem}
			onPress={() => openUrl(href)}
		>
			<Title style={styles.listItemText}>{label}</Title>
		</ListRow>
	)
}

const CloseButton = ({onPress}) => (
	<TouchableHighlight
		accessibilityTraits="button"
		onPress={onPress}
		style={styles.closeButton}
		underlayColor={c.black50Percent}
	>
		<Text style={styles.closeButtonText}>×</Text>
	</TouchableHighlight>
)

const styles = StyleSheet.create({
	container: {
		paddingHorizontal: 12,
	},
	scroll: {
		height: Dimensions.get('window').height - 66 - 66,
	},
	closeButton: {
		width: 24,
		height: 24,
		borderRadius: 24,
		backgroundColor: c.semitransparentGray,
		alignItems: 'center',
		justifyContent: 'center',
	},
	closeButtonText: {
		color: c.white,
		fontWeight: '600',
		textAlign: 'center',
		marginTop: -2,
	},
	photo: {
		width: 265,
		height: 200,
	},
	listItem: {
		paddingLeft: 0,
	},
	listItemText: {
		fontSize: 15,
	},
	outlineButton: {
		borderWidth: 1,
		borderColor: c.infoBlue,
		paddingVertical: 4,
		paddingHorizontal: 6,
		borderRadius: 4,
		marginLeft: 4,
	},
	outlineButtonDisabled: {
		borderColor: c.iosDisabledText,
	},
	outlineButtonText: {
		fontWeight: 'bold',
		color: c.infoBlue,
	},
	outlineButtonTextDisabled: {
		color: c.iosDisabledText,
	},
})
<commit_msg>add button to open the Report screen for maps<commit_after>// @flow

import * as React from 'react'
import {
	View,
	Text,
	TextInput,
	StyleSheet,
	ScrollView,
	TouchableHighlight,
	Image,
	Clipboard,
	Dimensions,
} from 'react-native'
import glamorous from 'glamorous-native'
import * as c from '../components/colors'
import type {Building, Feature} from './types'
import {parseLinkString} from './types'
import startCase from 'lodash/startCase'
import {Row, Column} from '../components/layout'
import {ListRow, Title} from '../components/list'
import openUrl from '../components/open-url'
import {Touchable} from '../components/touchable'

type Props = {
	feature: Feature<Building>,
	onClose: () => any,
	overlaySize: 'min' | 'mid' | 'max',
}

export class BuildingInfo extends React.Component<Props> {
	onClose = () => {
		this.props.onClose()
	}

	makeBuildingCategory = (building: Building) => {
		let blacklist = ['hall', 'house', 'building']
		return building.categories
			.filter(name => !blacklist.includes(name))
			.map(name => startCase(name))
			.join(' • ')
	}

	render() {
		let feature = this.props.feature
		let building = feature.properties
		let category = this.makeBuildingCategory(building)
		let photos = (building.photos || []).map(
			href => `https://carls-app.github.io/map-data/cache/img/${href}`,
		)

		let departments = building.departments.map(parseLinkString)
		let offices = building.offices.map(parseLinkString)

		let coordinates =
			feature.geometry.geometries.find(geo => geo.type === 'Point') || null
		coordinates = coordinates ? coordinates.coordinates : null

		return (
			<React.Fragment>
				<Row
					alignItems="center"
					justifyContent="space-between"
					marginBottom={12}
					style={styles.container}
				>
					<Column>
						<PlaceTitle>{building.name}</PlaceTitle>
						<PlaceSubtitle>{category}</PlaceSubtitle>
					</Column>
					<CloseButton onPress={this.onClose} />
				</Row>

				<ScrollView
					contentContainerStyle={styles.container}
					contentInsetAdjustmentBehavior="automatic"
					scrollEnabled={this.props.overlaySize === 'max'}
					style={styles.scroll}
				>
					{photos.length ? (

							<ScrollView horizontal={true}>
								{photos.map(href => (
									<Image key={href} source={{uri: href}} style={styles.photo} />
								))}
							</ScrollView>

					) : null}

					{building.address ? (

							<Row alignItems="center">
								<Column flex={1}>
									<SectionTitle>Address</SectionTitle>
									<SectionContent>{building.address}</SectionContent>
								</Column>
								<CopyText
									render={({copied, copy}) => (
										<OutlineButton
											disabled={copied}
											onPress={() => building.address && copy(building.address)}
											title={copied ? 'Copied' : 'Copy'}
										/>
									)}
								/>
							</Row>

					) : null}

					{building.description ? (

							<SectionTitle>Description</SectionTitle>
							<SectionSelectableContent>
								{building.description}
							</SectionSelectableContent>

					) : null}

					{departments.length ? (

							<SectionListTitle>Departments</SectionListTitle>
							<View>
								{departments.map(d => (
									<SectionListItem
										key={d.label}
										href={d.href}
										label={d.label}
									/>
								))}
							</View>

					) : null}

					{offices.length ? (

							<SectionListTitle>Offices</SectionListTitle>
							<View>
								{offices.map(d => (
									<SectionListItem
										key={d.label}
										href={d.href}
										label={d.label}
									/>
								))}
							</View>

					) : null}

					{coordinates ? (

							<Row alignItems="center">
								<Column flex={1}>
									<SectionTitle>Coordinates</SectionTitle>
									<SectionContent>{coordinates.join(', ')}</SectionContent>
								</Column>
								<CopyText
									render={({copied, copy}) => (
										<OutlineButton
											disabled={copied}
											onPress={() => copy((coordinates: any).join(', '))}
											title={copied ? 'Copied' : 'Copy'}
										/>
									)}
								/>
							</Row>

					) : null}

						<Row alignItems="center">
							<Column flex={1}>
								<SectionTitle>Found an issue?</SectionTitle>
								<SectionContent>Let us know!</SectionContent>
							</Column>
							<OutlineButton
								onPress={this.openReportScreen}
								title="Report an Issue"
							/>
						</Row>

				</ScrollView>
			</React.Fragment>
		)
	}
}

const PlaceTitle = glamorous.text({fontSize: 20, fontWeight: '700'})
const PlaceSubtitle = glamorous.text({fontSize: 16})

const Section = glamorous.view({
	paddingVertical: 12,
	borderBottomWidth: StyleSheet.hairlineWidth,
	borderBottomColor: c.black75Percent,
})
const SectionTitle = glamorous.text({fontWeight: '700'})
const SectionContent = glamorous.text()
const SectionSelectableContent = ({children}) => (
	<TextInput dataDetectorTypes="all" editable={false} multiline={true}>
		{children}
	</TextInput>
)

const SectionListTitle = glamorous(SectionTitle)({
	paddingBottom: 8,
})

const OutlineButton = (props: {
	title: string,
	onPress: () => any,
	disabled: boolean,
}) => (
	<Touchable
		accessibilityTraits="button"
		disabled={props.disabled}
		onPress={props.onPress}
		style={[
			styles.outlineButton,
			props.disabled && styles.outlineButtonDisabled,
		]}
	>
		<Text
			style={[
				styles.outlineButtonText,
				props.disabled && styles.outlineButtonTextDisabled,
			]}
		>
			{props.title}
		</Text>
	</Touchable>
)

class CopyText extends React.Component<
	{render: ({copied: boolean, copy: string => any}) => React.Node},
	{copied: boolean},
> {
	state = {
		copied: false,
	}

	onCopy = (text: string) => {
		Clipboard.setString(text)
		this.setState(() => ({copied: true}))
	}

	render() {
		return this.props.render({copied: this.state.copied, copy: this.onCopy})
	}
}

const SectionListItem = ({href, label}) => {
	return (
		<ListRow
			contentContainerStyle={styles.listItem}
			onPress={() => openUrl(href)}
		>
			<Title style={styles.listItemText}>{label}</Title>
		</ListRow>
	)
}

const CloseButton = ({onPress}) => (
	<TouchableHighlight
		accessibilityTraits="button"
		onPress={onPress}
		style={styles.closeButton}
		underlayColor={c.black50Percent}
	>
		<Text style={styles.closeButtonText}>×</Text>
	</TouchableHighlight>
)

const styles = StyleSheet.create({
	container: {
		paddingHorizontal: 12,
	},
	scroll: {
		height: Dimensions.get('window').height - 66 - 66,
	},
	closeButton: {
		width: 24,
		height: 24,
		borderRadius: 24,
		backgroundColor: c.semitransparentGray,
		alignItems: 'center',
		justifyContent: 'center',
	},
	closeButtonText: {
		color: c.white,
		fontWeight: '600',
		textAlign: 'center',
		marginTop: -2,
	},
	photo: {
		width: 265,
		height: 200,
	},
	listItem: {
		paddingLeft: 0,
	},
	listItemText: {
		fontSize: 15,
	},
	outlineButton: {
		borderWidth: 1,
		borderColor: c.infoBlue,
		paddingVertical: 4,
		paddingHorizontal: 6,
		borderRadius: 4,
		marginLeft: 4,
	},
	outlineButtonDisabled: {
		borderColor: c.iosDisabledText,
	},
	outlineButtonText: {
		fontWeight: 'bold',
		color: c.infoBlue,
	},
	outlineButtonTextDisabled: {
		color: c.iosDisabledText,
	},
})
<|endoftext|>


<commit_before>/*global describe, it*/
'use strict';
var chai = require( 'chai' );
var expect = chai.expect;
var senseLoc = require( './../lib/index.js' );
var fs = require( 'fs' );

describe( 'sense-loc', function () {

	it( 'contains valid methods', function ( done ) {
		expect( senseLoc ).to.be.ok;
		expect( senseLoc.getLocalExtensionPath ).to.be.a.function;
		done();
	} );

	it( 'should return a valid path', function ( done ) {
		senseLoc.getLocalExtensionPath( function ( err, data ) {
			if ( process.platform === 'win32' ) {
				expect( err ).to.be.null;
				expect( data ).not.to.be.empty;
				expect( data ).to.have.string('Qlik/Sense/Extensions')
			} else {
				expect( err ).to.be.null;
				expect( data ).to.be.null;
			}
			done();
		} );
	} );

} );
<commit_msg>tests: Fix path check with windows specific path separator<commit_after>/*global describe, it*/
'use strict';
var chai = require( 'chai' );
var expect = chai.expect;
var senseLoc = require( './../lib/index.js' );
var fs = require( 'fs' );

describe( 'sense-loc', function () {

	it( 'contains valid methods', function ( done ) {
		expect( senseLoc ).to.be.ok;
		expect( senseLoc.getLocalExtensionPath ).to.be.a.function;
		done();
	} );

	it( 'should return a valid path', function ( done ) {
		senseLoc.getLocalExtensionPath( function ( err, data ) {
			if ( process.platform === 'win32' ) {
				expect( err ).to.be.null;
				expect( data ).not.to.be.empty;
				expect( data ).to.have.string('Qlik\\Sense\\Extensions')
			} else {
				expect( err ).to.be.null;
				expect( data ).to.be.null;
			}
			done();
		} );
	} );

} );
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import isEqual from 'react/lib/shallowCompare';
import invariant from 'invariant';

function create(asyncFn, defaultVariables = () => ({})) {
  const componentName = asyncFn.name || asyncFn.displayName;

  return class AsyncComponent extends Component {
    static get displayName() {
      return `Coroutine(${componentName})`;
    }

    constructor(props) {
      super(props);
      this.state = { body: React.createElement('noscript'),
                     variables: defaultVariables() };
      this.forceUpdateHelper = this.forceUpdate.bind(this);
    }

    forceUpdate(variables = this.state.variables) {
      const additionalProps = { forceUpdate: this.forceUpdateHelper };
      const asyncBody = asyncFn(Object.assign(additionalProps, variables, this.props));

      invariant(asyncBody instanceof Promise || asyncBody[Symbol.iterator]() === asyncBody,
                `${componentName} should return a Promise or Iterator`);

      return asyncBody
        .then(body => this.setState(() => ({ body, variables })));
    }

    componentDidMount() {
      return this.forceUpdate(this.state.variables);
    }

    componentWillReceiveProps(nextProps) {
      return !isEqual(nextProps, this.props) && this.forceUpdate();
    }

    render() {
      return this.state.body;
    }
  }
}

export default { create };
<commit_msg>restrict usage only for promises and async iterators<commit_after>import React, { Component } from 'react';
import isEqual from 'react/lib/shallowCompare';
import invariant from 'invariant';

function create(asyncFn, defaultVariables = () => ({})) {
  const componentName = asyncFn.name || asyncFn.displayName;

  return class AsyncComponent extends Component {
    static get displayName() {
      return `Coroutine(${componentName})`;
    }

    constructor(props) {
      super(props);
      this.state = { body: React.createElement('noscript'),
                     variables: defaultVariables() };
      this.forceUpdateHelper = this.forceUpdate.bind(this);
    }

    async forceUpdate(variables = this.state.variables) {
      const additionalProps = { forceUpdate: this.forceUpdateHelper };
      const asyncBody = asyncFn(Object.assign(additionalProps, variables, this.props));

      invariant(asyncBody instanceof Promise || asyncBody[Symbol.asyncIterator]() === asyncBody,
                `${componentName} should return a Promise or AsyncIterator`);

      if (asyncBody instanceof Promise) {
        const body = await asyncBody;
        this.setState(() => ({ body, variables }));
      } else {
        for await (const body of asyncBody) {
          this.setState(() => ({ body, variables }));
        }
      }
    }

    componentDidMount() {
      return this.forceUpdate(this.state.variables);
    }

    componentWillReceiveProps(nextProps) {
      return !isEqual(nextProps, this.props) && this.forceUpdate();
    }

    render() {
      return this.state.body;
    }
  }
}

export default { create };
<|endoftext|>


<commit_before>/*eslint-env mocha */
var chai = require('chai');
chai.use(require('chai-http'));
var express = require('express');
var implHandler = require('../index');
var expect = chai.expect;
var should = chai.should();

var app = express();
var router = express.Router();

router.route('/')
  .get(function(req, res) {
    return res.end();
  });

router.route('/router-test')
  .post(function(req, res) {
    return res.end();
  })
  .copy(function(req, res) {
    return res.end();
  })
  .delete(function(req, res) {
    return res.end();
  });

app.route('/')
  .get(function(req, res) {
    return res.end();
  });

app.route('/app-test')
  .put(function(req, res) {
    return res.end();
  });

app.use('/router', router);

implHandler(app);

app.use(function(err, req, res, next) {
  if (err) {
    res.status(err.status || 500).send(err);
  }

  next();
});

describe('express-implhandler', function() {
  describe('when called over an app', function() {
    var agent = chai.request.agent(app);

    describe('for the app', function() {
      describe('on defined endpoints', function() {
        it('should not change response on defined methods', function(done) {
          agent.get('/')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(200);
            });
          agent.put('/app-test')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(200);
              done();
            });
        });

        it('should set an error code 501 on undefined methods', function(done) {
          agent.post('/')
            .end(function(err, res) {
              expect(res.error).to.be.ok;
              expect(res).to.has.status(501);
            });
          agent.delete('/app-test')
            .end(function(err, res) {
              expect(res.error).to.be.ok;
              expect(res).to.has.status(501);
              done();
            });
        });
      });

      describe('on undefined endpoints', function() {
        it('should not set any handler', function(done) {
          agent.get('/some-endpoint')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(404);
            });
          agent.post('/another-endpoint')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(404);
              done();
            });
        });
      });
    });

    describe('for the attached router methods', function() {
      it('should not change the response on current methods', function(done) {
        agent.get('/router/')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
          });
        agent.post('/router/router-test')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
          });
        agent.copy('/router/router-test')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
          });
        agent.delete('/router/router-test')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
            done();
          });
      });

      it('should not set handlers for undefined endopints', function(done) {
        agent.get('/router/some-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
          });
        agent.put('/router/some-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
          });
        agent.post('/router/another-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
          });
        agent.delete('/router/another-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
            done();
          });
      });
    });
  });
});
<commit_msg>Refactor tests<commit_after>/*eslint-env mocha */
var chai = require('chai');
chai.use(require('chai-http'));
var express = require('express');
var implHandler = require('../index');
var expect = chai.expect;
var should = chai.should();

var app = express();
var router = express.Router();

var errorHandler = function(err, req, res, next) {
  if (err) {return res.status(err.status || 500).json(err);}

  return next();
};

router.route('/')
  .get(function(req, res) {
    return res.end();
  });

router.route('/router-test')
  .post(function(req, res) {
    return res.end();
  })
  .copy(function(req, res) {
    return res.end();
  })
  .delete(function(req, res) {
    return res.end();
  });

app.route('/')
  .get(function(req, res) {
    return res.end();
  });

app.route('/app-test')
  .put(function(req, res) {
    return res.end();
  });

app.use('/router', router);

describe('express-implhandler', function() {
  describe('when called over an app', function() {
    implHandler(app);
    app.use(errorHandler);
    var agent = chai.request.agent(app);

    describe('for the app', function() {
      describe('on defined endpoints', function() {
        it('should not change response on defined methods', function(done) {
          agent.get('/')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(200);
            });
          agent.put('/app-test')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(200);
              done();
            });
        });

        it('should set an error code 501 on undefined methods', function(done) {
          agent.post('/')
            .end(function(err, res) {
              expect(res.error).to.be.ok;
              expect(res).to.has.status(501);
            });
          agent.delete('/app-test')
            .end(function(err, res) {
              expect(res.error).to.be.ok;
              expect(res).to.has.status(501);
              done();
            });
        });
      });

      describe('on undefined endpoints', function() {
        it('should not set any handler', function(done) {
          agent.get('/some-endpoint')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(404);
            });
          agent.post('/another-endpoint')
            .end(function(err, res) {
              expect(err).to.be.null;
              expect(res).to.has.status(404);
              done();
            });
        });
      });
    });

    describe('for the attached routers methods', function() {
      it('should not change the response on current methods', function(done) {
        agent.get('/router/')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
          });
        agent.post('/router/router-test')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
          });
        agent.copy('/router/router-test')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
          });
        agent.delete('/router/router-test')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(200);
            done();
          });
      });

      it('should not set handlers for undefined endopints', function(done) {
        agent.get('/router/some-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
          });
        agent.put('/router/some-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
          });
        agent.post('/router/another-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
          });
        agent.delete('/router/another-endpoint')
          .end(function(err, res) {
            expect(err).to.be.null;
            expect(res).to.has.status(404);
            done();
          });
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
 * this is the core game logic
 * DO NOT PUT EVENT LISTENERS INTO THIS FILE
 * DO NOT PUT CREATE JS OR JQUERY INTO THIS FILE
 */

 /**
  * Allows an object to be moved based on key press integers
  * @param object to be moved
  * @param direction the object is moving in
  */

var moving = false;

function move (player, direction, canvId) {

    var height = 0.85*window.innerHeight;
    var width = 0.75*window.innerWidth;

    // SCENE 1: Start

    if (canvId == 'startCanvas') {

        switch (direction) {
            // Left
            case 37:
                if (player.x > 360 && player.x < 400 && player.y < 140) { // Stay within vertical sidewalk
                    player.x -= 10;
                } else if (player.x > -10 && player.y > 130) { // Stay within horizontal sidewalk
                    player.x -= 10;
                }
                break;

            // Up
            case 38:
                if (player.y > 140 || (player.x > 350 && player.x < 400 && player.y > 30)) {
                    player.y -= 10;
                }
                break;

            // Right
            case 39:
                if (player.x > 350 && player.x < 390 && player.y < 140) { // Stay within vertical sidewalk
                    player.x += 10;
                } else if (player.x < 710 && player.y > 130) { // Stay within horizontal sidewalk
                    player.x += 10;
                }
                break;

            // Down
            case 40:
                if (player.y < 170) {
                    player.y += 10;
                }
                break;

            default:
                break;
        }
    }

    // SCENE 2: Aha!

    else if (canvId == 'ahaCanvas') {

        switch (direction) {
            // Left
            case 37:
                if (moving == false) {
                    player.gotoAndPlay("left1");
                    moving = true;
                } else {
                    player.gotoAndPlay("left2");
                    moving = false;
                }

                player.x -= 15;
                break;

            // Up
            case 38:

                if (moving == false) {
                    player.gotoAndPlay("up1");
                    moving = true;
                } else {
                    player.gotoAndPlay("up2");
                    moving = false;
                }

                player.y -= 15;
                break;

            // Right
            case 39:

                if (moving == false) {
                    player.gotoAndPlay("right1");
                    moving = true;
                } else {
                    player.gotoAndPlay("right2");
                    moving = false;
                }

                player.x += 15;
                break;

            // Down
            case 40:

                if (moving == false) {
                    player.gotoAndPlay("up1");
                    moving = true;
                } else {
                    player.gotoAndPlay("up2");
                    moving = false;
                }

                player.y += 15;
                break;

            default:
                break;
        }
    }

    // SCENE 3: Gap

    else if (canvId == 'gapCanvas') {

        switch (direction) {
            // Left
            case 37:
                if (player.x > 0.375*width && player.y < 0.07*height)
                    { player.x -=0.01*width; }                                                          // plant
                else if (player.x > 0.05*width && player.y < 0.35*height && player.y > 0.07*height)
                    { player.x -= 0.01*width; }
                else if (player.x > 0.42*width && player.y > 0.31*height)
                    { player.x -= 0.01*width; }                                                         // hallway
                break;

            // Up
            case 38:
                if (player.y > 0.05*height && player.x < 0.2*width)
                    {player.y -=0.02*height;}
                else if (player.y > 0.07*height && player.x > 0.2*width && player.x < 0.375*width)
                    { player.y -= 0.02*height; }                                                        // plant
                else if (player.y > 0.05*height && player.x > 0.375*width && player.x < 0.55*width)
                    { player.y -= 0.02*height; }
                else if (player.y > 0.1*height && player.x > 0.55*width)
                    { player.y -= 0.02*height; }                                                        // chairs
                break;

            // Right
            case 39:
                if (player.x < 0.2*width && player.y < 0.07*height)
                    { player.x +=0.01*width; }                                                          // plant
                else if (player.x < 0.55*width && player.y < 0.1)
                    { player.x += 0.01*width; }
                else if (player.x < 0.515*width && player.y > 0.31*height)
                    { player.x += 0.01*width; }
                else if (player.x < 0.9*width && player.y > 0.1*height)
                    { player.x += 0.01*width; }
                break;

            // Down
            case 40:
                if (player.y < 0.31*height && player.x < 0.42*width)
                    { player.y += 0.02*height; }
                else if (player.y < height && player.x > 0.42*width && player.x < 0.515*width)
                    { player.y += 0.02*height; }                                                        // hallway
                else if (player.y < 0.31*height && player.x > 0.515*width)
                    { player.y += 0.02*height; }
                break;

            default:
                break;
        }
    }

    // SCENE 4: Survey

    else if (canvId == 'survCanvas') {

        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }

    // SCENE 5: Interest

    else if (canvId == 'interCanvas') {

        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }

    // SCENE 6: Elevator

    else if (canvId == 'elevCanvas') {

        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }

    // Scene 7: End

    else {

        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }
}
<commit_msg>Breaking up logic into multi-layer switch. One switch for key code, then one switch PER KEY CODE, which then determines which canvasID<commit_after>/*
 * this is the core game logic
 * DO NOT PUT EVENT LISTENERS INTO THIS FILE
 * DO NOT PUT CREATE JS OR JQUERY INTO THIS FILE
 */

 /**
  * Allows an object to be moved based on key press integers
  * @param object to be moved
  * @param direction the object is moving in
  */

var moving = false;

function move (player, direction, canvId) {

    switch (direction) {
        // Left
        case 37:
            switch (canvId) {
                case 'startCanvas':
                    break;

                case 'ahaCanvas':
                    break;

                case 'gapCanvas':
                    break;

                case 'survCanvas':
                    break;

                case 'interCanvas':
                    break;

                case 'elevCanvas':
                    break;

                case 'endCanvas':
                    break;
            }
            break;

        case 38:
            switch (canvId) {
                case 'startCanvas':
                    break;

                case 'ahaCanvas':
                    break;

                case 'gapCanvas':
                    break;

                case 'survCanvas':
                    break;

                case 'interCanvas':
                    break;

                case 'elevCanvas':
                    break;

                case 'endCanvas':
                    break;
            }
            break;

        case 39:
            switch (canvId) {
                case 'startCanvas':
                    break;

                case 'ahaCanvas':
                    break;

                case 'gapCanvas':
                    break;

                case 'survCanvas':
                    break;

                case 'interCanvas':
                    break;

                case 'elevCanvas':
                    break;

                case 'endCanvas':
                    break;
            }
            break;

        case 40:
            switch (canvId) {
                case 'startCanvas':
                    break;

                case 'ahaCanvas':
                    break;

                case 'gapCanvas':
                    break;

                case 'survCanvas':
                    break;

                case 'interCanvas':
                    break;

                case 'elevCanvas':
                    break;

                case 'endCanvas':
                    break;
            }
            break;

        default:
            break;
    }

    // SCENE 1: Start
    if (canvId == 'startCanvas') {
        switch (direction) {
            // Left
            case 37:
                if (player.x > 360 && player.x < 400 && player.y < 140) { // Stay within vertical sidewalk
                    player.x -= 10;
                } else if (player.x > -10 && player.y > 130) { // Stay within horizontal sidewalk
                    player.x -= 10;
                }
                break;

            // Up
            case 38:
                if (player.y > 140 || (player.x > 350 && player.x < 400 && player.y > 30)) {
                    player.y -= 10;
                }
                break;

            // Right
            case 39:
                if (player.x > 350 && player.x < 390 && player.y < 140) { // Stay within vertical sidewalk
                    player.x += 10;
                } else if (player.x < 710 && player.y > 130) { // Stay within horizontal sidewalk
                    player.x += 10;
                }
                break;

            // Down
            case 40:
                if (player.y < 170) {
                    player.y += 10;
                }
                break;

            default:
                break;
        }
    }

    // SCENE 2: Aha!
    else if (canvId == 'ahaCanvas') {
        switch (direction) {
            // Left
            case 37:
                if (moving == false) {
                    player.gotoAndPlay("left1");
                    moving = true;
                } else {
                    player.gotoAndPlay("left2");
                    moving = false;
                }

                player.x -= 15;
                break;

            // Up
            case 38:

                if (moving == false) {
                    player.gotoAndPlay("up1");
                    moving = true;
                } else {
                    player.gotoAndPlay("up2");
                    moving = false;
                }

                player.y -= 15;
                break;

            // Right
            case 39:

                if (moving == false) {
                    player.gotoAndPlay("right1");
                    moving = true;
                } else {
                    player.gotoAndPlay("right2");
                    moving = false;
                }

                player.x += 15;
                break;

            // Down
            case 40:

                if (moving == false) {
                    player.gotoAndPlay("up1");
                    moving = true;
                } else {
                    player.gotoAndPlay("up2");
                    moving = false;
                }

                player.y += 15;
                break;

            default:
                break;
        }
    }

    // SCENE 3: Gap
    else if (canvId == 'gapCanvas') {
        switch (direction) {
            // Left
            case 37:
                if (player.x > 0.375*width && player.y < 0.07*height)
                    { player.x -=0.01*width; }                                                          // plant
                else if (player.x > 0.05*width && player.y < 0.35*height && player.y > 0.07*height)
                    { player.x -= 0.01*width; }
                else if (player.x > 0.42*width && player.y > 0.31*height)
                    { player.x -= 0.01*width; }                                                         // hallway
                break;

            // Up
            case 38:
                if (player.y > 0.05*height && player.x < 0.2*width)
                    {player.y -=0.02*height;}
                else if (player.y > 0.07*height && player.x > 0.2*width && player.x < 0.375*width)
                    { player.y -= 0.02*height; }                                                        // plant
                else if (player.y > 0.05*height && player.x > 0.375*width && player.x < 0.55*width)
                    { player.y -= 0.02*height; }
                else if (player.y > 0.1*height && player.x > 0.55*width)
                    { player.y -= 0.02*height; }                                                        // chairs
                break;

            // Right
            case 39:
                if (player.x < 0.2*width && player.y < 0.07*height)
                    { player.x +=0.01*width; }                                                          // plant
                else if (player.x < 0.55*width && player.y < 0.1)
                    { player.x += 0.01*width; }
                else if (player.x < 0.515*width && player.y > 0.31*height)
                    { player.x += 0.01*width; }
                else if (player.x < 0.9*width && player.y > 0.1*height)
                    { player.x += 0.01*width; }
                break;

            // Down
            case 40:
                if (player.y < 0.31*height && player.x < 0.42*width)
                    { player.y += 0.02*height; }
                else if (player.y < height && player.x > 0.42*width && player.x < 0.515*width)
                    { player.y += 0.02*height; }                                                        // hallway
                else if (player.y < 0.31*height && player.x > 0.515*width)
                    { player.y += 0.02*height; }
                break;

            default:
                break;
        }
    }

    // SCENE 4: Survey
    else if (canvId == 'survCanvas') {
        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }

    // SCENE 5: Interest
    else if (canvId == 'interCanvas') {
        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }

    // SCENE 6: Elevator
    else if (canvId == 'elevCanvas') {
        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }

    // Scene 7: End
    else {
        switch (direction) {
            // Left
            case 37:
                player.x -= 5;
                break;

            // Up
            case 38:
                player.y -= 5;
                break;

            // Right
            case 39:
                player.x += 5;
                break;

            // Down
            case 40:
                player.y += 5;
                break;

            default:
                break;
        }
    }
}
<|endoftext|>


<commit_before>/*global describe, it */
'use strict';

var assert = require('assert');
var fs = require('fs');
var inline = require('../index');
var path = require('path');
var rework = require('rework');

describe('inline()', function () {
    it('should import stylsheets', function () {
        var original = fs.readFileSync(path.join(__dirname, 'fixtures/original.css'), 'utf8');
        var expected = fs.readFileSync(path.join(__dirname, 'fixtures/expected.css'), 'utf8');

        var css = rework(original)
            .use(inline({ path: path.join(__dirname, 'fixtures') }))
            .toString();

        assert.equal(css, expected);
    });
});
<commit_msg>Minor fix<commit_after>/*global describe, it */
'use strict';

var assert = require('assert');
var fs = require('fs');
var inline = require('../');
var path = require('path');
var rework = require('rework');

describe('inline()', function () {
    it('should import stylsheets', function () {
        var original = fs.readFileSync(path.join(__dirname, 'fixtures/original.css'), 'utf8');
        var expected = fs.readFileSync(path.join(__dirname, 'fixtures/expected.css'), 'utf8');

        var css = rework(original)
            .use(inline({ path: path.join(__dirname, 'fixtures') }))
            .toString();

        assert.equal(css, expected);
    });
});
<|endoftext|>


<commit_before>var debugit = require('debugit').enable();
var debug = debugit.add('samsaara:test:identity');

var test = require('tape').test;
var TapeFence = require('./tapefence');

var WebSocketServer = require('ws').Server;
var samsaara = require('samsaara');
var identity = require('../main');

var theConnection;
var fences = {};
var connectionCount = 0;

var wss = new WebSocketServer({
    port: 8081
});

// test setup

samsaara.on('initialized', function(connection) {
    debug('Connection Initialized', connection.name);
    fences['Connection Initialized'].hit(connection);
});

wss.on('connection', function(ws) {
    theConnection = samsaara.newConnection(ws, 'connection' + connectionCount++);
});

samsaara.expose({
    doneTest: function(cb) {
        cb(true);
        fences['Done Test'].hit(this);
    }
});

// tests

test('Samsaara Server Exists', function(t) {
    t.equal(typeof samsaara, 'object');
    t.end();
});

test('Samsaara can load TimeOffset middleware', function(t) {
    samsaara.use(identity, {
        identityTypes: ['userID']
    });
    t.end();
});

test('Samsaara can initialize', function(t) {
    var initialized = samsaara.initialize();
    t.equal(initialized, samsaara);
    t.end();
});

test('Global identity methods exist', function(t) {

    t.equal(typeof samsaara.identity, 'function');
    t.equal(typeof samsaara.identityType, 'function');
    t.equal(typeof samsaara.removeIdentityType, 'function');
    t.equal(typeof samsaara.createIdentityType, 'function');
    t.equal(typeof samsaara.removeIdentity, 'function');

    t.end();
});

test('Create Identity Type', function(t) {

    var identityType = samsaara.createIdentityType('sessionID');

    t.equal(typeof identityType, 'object');
    t.equal(typeof samsaara.identityType('sessionID'), 'object');
    t.equal(samsaara.identityType('sessionID'), identityType);

    t.end();
});

test('Connection methods exist', function(t) {

    fences['Connection Initialized'] = new TapeFence(1, function() {
        t.equal(samsaara.connection('connection0'), theConnection);
        t.equal(typeof theConnection, 'object');
        t.equal(typeof theConnection.identity, 'function');
        t.equal(typeof theConnection.identifyAs, 'function');
        t.equal(typeof theConnection.unidentify, 'function');
        t.equal(typeof theConnection.validateIdentity, 'function');
        t.end();
    });
});

test('Connection maps to Identity', function(t) {

    theConnection.identifyAs('sessionID', '123456789');
    t.equal(theConnection.identity('sessionID').value, '123456789');
    t.equal(samsaara.identity('sessionID', '123456789'), theConnection.identity('sessionID'));
    t.equal(theConnection.validateIdentity('sessionID', '123456789'), true);

    t.end();
});

test('Unidentify Connection', function(t) {

    theConnection.unidentify('sessionID', true);

    t.equal(theConnection.identity('sessionID'), undefined);
    t.equal(samsaara.identity('sessionID', '123456789'), null);
    t.equal(theConnection.validateIdentity('sessionID', '123456789'), false);

    t.end();
});

test('Add Subidentity', function(t) {

    samsaara.createIdentityType('userID');
    theConnection.identifyAs('sessionID', '123456789');
    samsaara.identity('sessionID', '123456789').identifyAs('userID', 'jambalaya');

    t.equal(theConnection.identity('userID').value, 'jambalaya');
    t.equal(samsaara.identity('userID', 'jambalaya'), theConnection.identity('userID'));
    t.equal(theConnection.validateIdentity('userID', 'jambalaya'), true);

    t.end();
});

test('Unidentify Subidentity', function(t) {

    theConnection.unidentify('sessionID');

    t.equal(theConnection.identity('userID'), undefined);
    t.equal(samsaara.identity('userID', 'jambalaya').connections.length, 0);
    t.equal(theConnection.validateIdentity('userID', 'jambalaya'), false);

    t.end();
});

test('Hold Test', function(t) {
    setTimeout(function() {
        samsaara.connection('connection0').execute('continueTest')();
    }, 500);
    t.end();
});

test('Close Test', function(t) {
    fences['Done Test'] = new TapeFence(1, function() {
        wss.close();
        t.end();
    });
});
<commit_msg>Updating tests to check all lists.<commit_after>var debugit = require('debugit').enable();
var debug = debugit.add('samsaara:test:identity');

var test = require('tape').test;
var TapeFence = require('./tapefence');

var WebSocketServer = require('ws').Server;
var samsaara = require('samsaara');
var identity = require('../main');

var identityList = require('../lib/identityList');

var theConnection;
var fences = {};
var connectionCount = 0;

var wss = new WebSocketServer({
    port: 8081
});

// test setup

samsaara.on('initialized', function(connection) {
    debug('Connection Initialized', connection.name);
    fences['Connection Initialized'].hit(connection);
});

wss.on('connection', function(ws) {
    theConnection = samsaara.newConnection(ws, 'connection' + connectionCount++);
});

samsaara.expose({
    doneTest: function(cb) {
        cb(true);
        fences['Done Test'].hit(this);
    }
});

// tests

test('Samsaara Server Exists', function(t) {
    t.equal(typeof samsaara, 'object');
    t.end();
});

test('Samsaara can load TimeOffset middleware', function(t) {
    samsaara.use(identity, {
        identityTypes: ['userID']
    });
    t.end();
});

test('Samsaara can initialize', function(t) {
    var initialized = samsaara.initialize();
    t.equal(initialized, samsaara);
    t.end();
});

test('Global identity methods exist', function(t) {

    t.equal(typeof samsaara.identity, 'function');
    t.equal(typeof samsaara.identityType, 'function');
    t.equal(typeof samsaara.removeIdentityType, 'function');
    t.equal(typeof samsaara.createIdentityType, 'function');
    t.equal(typeof samsaara.removeIdentity, 'function');

    t.end();
});

test('Create Identity Type', function(t) {

    var identityType = samsaara.createIdentityType('sessionID');

    t.equal(typeof identityType, 'object');
    t.equal(typeof samsaara.identityType('sessionID'), 'object');
    t.equal(samsaara.identityType('sessionID'), identityType);
    t.equal(typeof identityList.list.sessionID, 'object');

    t.end();
});

test('Connection methods exist', function(t) {

    fences['Connection Initialized'] = new TapeFence(1, function() {
        t.equal(samsaara.connection('connection0'), theConnection);
        t.equal(typeof theConnection, 'object');
        t.equal(typeof theConnection.identity, 'function');
        t.equal(typeof theConnection.identifyAs, 'function');
        t.equal(typeof theConnection.unidentify, 'function');
        t.equal(typeof theConnection.validateIdentity, 'function');
        t.end();
    });
});

test('Connection maps to Identity', function(t) {

    theConnection.identifyAs('sessionID', '123456789');
    t.equal(theConnection.identity('sessionID').value, '123456789');
    t.equal(samsaara.identity('sessionID', '123456789'), theConnection.identity('sessionID'));
    t.equal(theConnection.validateIdentity('sessionID', '123456789'), true);

    t.equal(identityList.list.sessionID['123456789'].value, '123456789');
    t.equal(identityList.list.sessionID['123456789'], theConnection.identity('sessionID'));

    t.end();
});

test('Unidentify Connection', function(t) {

    theConnection.unidentify('sessionID');

    t.equal(theConnection.identity('sessionID'), undefined);
    t.equal(theConnection.validateIdentity('sessionID', '123456789'), false);
    t.equal(theConnection.identities['sessionID'], undefined);
    t.equal(typeof samsaara.identity('sessionID', '123456789'), 'object');

    theConnection.identifyAs('sessionID', '123456789');
    theConnection.unidentify('sessionID', true);

    t.equal(identityList.list['sessionID']['123456789'], undefined);
    t.equal(samsaara.identity('sessionID', '123456789'), null);

    t.end();
});

test('Add Subidentity', function(t) {

    samsaara.createIdentityType('userID');
    theConnection.identifyAs('sessionID', '123456789');
    samsaara.identity('sessionID', '123456789').identifyAs('userID', 'jambalaya');

    t.equal(theConnection.identity('userID').value, 'jambalaya');
    t.equal(samsaara.identity('userID', 'jambalaya'), theConnection.identity('userID'));
    t.equal(theConnection.validateIdentity('userID', 'jambalaya'), true);

    t.equal(identityList.list['userID']['jambalaya'], theConnection.identity('userID'));

    t.end();
});

test('Connection Lists', function(t) {
    t.equal(identityList.list['userID']['jambalaya'].connections[0], theConnection);
    t.equal(identityList.list['userID']['jambalaya'].connectionMembers[theConnection.id], true);
    t.equal(identityList.list['userID']['jambalaya'].count, 1);

    t.end();
});

test('Unidentify Subidentity', function(t) {

    samsaara.identity('sessionID', '123456789').unidentify('userID');

    t.equal(theConnection.identity('userID'), undefined);
    t.equal(samsaara.identity('userID', 'jambalaya').connections.length, 0);
    t.equal(theConnection.validateIdentity('userID', 'jambalaya'), false);

    t.equal(theConnection.identities['userID'], undefined);
    t.equal(theConnection.identities['sessionID'].value, '123456789');

    t.equal(identityList.list['userID']['jambalaya'].connections[0], undefined);
    t.equal(identityList.list['userID']['jambalaya'].connectionMembers[theConnection.id], undefined);
    t.equal(identityList.list['userID']['jambalaya'].count, 0);

    t.end();
});

test('Hold Test', function(t) {
    setTimeout(function() {
        samsaara.connection('connection0').execute('continueTest')();
    }, 500);
    t.end();
});

test('Close Test', function(t) {
    fences['Done Test'] = new TapeFence(1, function() {
        wss.close();
        t.end();
    });
});
<|endoftext|>


<commit_before>(function($) {
	/*
		======== A Handy Little QUnit Reference ========
		http://api.qunitjs.com/

		Test methods:
			module(name, {[setup][ ,teardown]})
			test(name, callback)
			expect(numberOfAssertions)
			stop(increment)
			start(decrement)
		Test assertions:
			ok(value, [message])
			equal(actual, expected, [message])
			notEqual(actual, expected, [message])
			deepEqual(actual, expected, [message])
			notDeepEqual(actual, expected, [message])
			strictEqual(actual, expected, [message])
			notStrictEqual(actual, expected, [message])
			throws(block, [expected], [message])
	*/

	module( "Default", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.collapsible' ).collapsible();
		}
	});

	test( "Global Initialization", function() {
		ok( $( "html" ).is( ".enhanced" ), "Has global initialization class." );
	});

	test( "Initialization", function() {
		ok( $( "#default.collapsible" ).is( ".collapsible-enhanced" ), "Has individual initialization class." );
		ok( $( "#default .collapsible-content" ).not( ":hidden" ).length, "Content is visible by default." );
	});

	test( "Header content order", function() {
		ok( !$( "#outoforder .collapsible-content" ).is( ".collapsible-header" ), "Content can come first in child order, if classes are preset" );
		ok( !$( "#outoforder .collapsible-header" ).is( ".collapsible-content" ), "header can come second in child order, if classes are preset" );
	});

	test( "a11y", function() {
		ok( $( "#default .collapsible-header" ).is( "[tabindex='0']" ), "Tabindex added." );
		ok( $( "#default .collapsible-header" ).is( "[role=button]" ), "Role added." );
	});

	test( "inner button", function() {
		ok( $( "#innerButton .collapsible-header button" ).length, "button exists" );
		ok( $( "#innerButton .collapsible-header button" ).is( "[aria-expanded='false']" ), "aria-expanded attr (false) is on the button" );
		ok( $( "#innerButton .collapsible-header button" ).text() === "Toggle collapsible content", "button content is correct" );
		$( "#innerButton .collapsible-header button" ).trigger( "click" );
		ok( $( "#innerButton .collapsible-header button" ).is( "[aria-expanded='true']" ), "aria-expanded attr (true) is on the button" );

	});

	test( "Click the header", function() {
		$( "#default .collapsible-header" ).trigger( "click" );
		ok( $( "#default .collapsible-content" ).is( ":hidden" ), "Content is hidden after header click." );

		$( "#default .collapsible-header" ).trigger( "click" );
		ok( $( "#default .collapsible-content" ).is( ":visible" ), "Content is visible after header second click." );

	});

	module( "Collapsed Initialization", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.collapsible' ).collapsible();
		}
	});

	test( "Initialization", function() {
		ok( $( "#collapsed .collapsible-content" ).is( ":hidden" ), "Content is hidden by default." );
	});

	test( "Click the header", function() {
		$( "#collapsed .collapsible-header" ).trigger( "click" );
		ok( !$( "#collapsed .collapsible-content" ).is( ":hidden" ), "Content is visible after header click." );

		$( "#collapsed .collapsible-header" ).trigger( "click" );
		ok( $( "#collapsed .collapsible-content" ).is( ":hidden" ), "Content is hidden after header second click." );
	});

	module( "Accordion Plugin", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.collapsible' ).removeData( 'collapsible' ).collapsible();
		}
	});

	test( "Click the header", function() {
		ok( $( "#accordion-c .collapsible-content" ).is( ":hidden" ), "Third unrelated collapsible content initial state." );

		$( "#accordion-a .collapsible-header" ).trigger( "click" );
		ok( !$( "#accordion-a .collapsible-content" ).is( ":hidden" ), "First accordion collapsible content is visible after header click." );
		ok( $( "#accordion-c .collapsible-content" ).is( ":hidden" ), "Third unrelated collapsible content is still hidden after header click." );

		$( "#accordion-b .collapsible-header" ).trigger( "click" );
		ok( !$( "#accordion-b .collapsible-content" ).is( ":hidden" ), "Second accordion collapsible content is visible after header click." );
		ok( $( "#accordion-a .collapsible-content" ).is( ":hidden" ), "First accordion collapsible content is visible after second collapsible header click." );
		ok( $( "#accordion-c .collapsible-content" ).is( ":hidden" ), "Third unrelated collapsible content is still hidden after header click." );
	});

	module( "Tabs Plugin", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.tabnav' ).remove();
			$( '#qunit-fixture' ).find( '.collapsible' ).removeData( 'collapsible' ).collapsible();
		}
	});

	test( "Click the header", function() {
		ok( !$( "#tabs-a .collapsible-content" ).is( ":hidden" ), "Initial state of first tab: visible" );
		ok( $( "#tabs-b .collapsible-content" ).is( ":hidden" ), "Initial state of second tab: hidden" );

		$( "#tabs .tabnav a" ).eq( 1 ).trigger( "click" );
		ok( $( "#tabs-a .collapsible-content" ).is( ":hidden" ), "Initial state of first tab: hidden" );
		ok( !$( "#tabs-b .collapsible-content" ).is( ":hidden" ), "Initial state of second tab: visible" );
	});

	module( "Menu Plugin", {
		setup: function(){
				$( '#qunit-fixture' ).find( '.collapsible' ).collapsible();
		}
	});

	test( "Hover header", function() {
		ok( $( "#menu .collapsible-content" ).is( ":hidden" ), "Menu collapsible content initial state." );

		$( "#menu" ).trigger( "mouseenter" );
		ok( !$( "#menu .collapsible-content" ).is( ":visible" ), "Menu collapsible content visible after mouseenter." );

		$( "#menu" ).trigger( "mouseleave" );
		ok( $( "#menu .collapsible-content" ).is( ":hidden" ), "Menu collapsible content hidden after mouseleave." );
	});
}(jQuery));
<commit_msg>whitespace, collapse retest<commit_after>(function($) {
	/*
		======== A Handy Little QUnit Reference ========
		http://api.qunitjs.com/

		Test methods:
			module(name, {[setup][ ,teardown]})
			test(name, callback)
			expect(numberOfAssertions)
			stop(increment)
			start(decrement)
		Test assertions:
			ok(value, [message])
			equal(actual, expected, [message])
			notEqual(actual, expected, [message])
			deepEqual(actual, expected, [message])
			notDeepEqual(actual, expected, [message])
			strictEqual(actual, expected, [message])
			notStrictEqual(actual, expected, [message])
			throws(block, [expected], [message])
	*/

	module( "Default", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.collapsible' ).collapsible();
		}
	});

	test( "Global Initialization", function() {
		ok( $( "html" ).is( ".enhanced" ), "Has global initialization class." );
	});

	test( "Initialization", function() {
		ok( $( "#default.collapsible" ).is( ".collapsible-enhanced" ), "Has individual initialization class." );
		ok( $( "#default .collapsible-content" ).not( ":hidden" ).length, "Content is visible by default." );
	});

	test( "Header content order", function() {
		ok( !$( "#outoforder .collapsible-content" ).is( ".collapsible-header" ), "Content can come first in child order, if classes are preset" );
		ok( !$( "#outoforder .collapsible-header" ).is( ".collapsible-content" ), "header can come second in child order, if classes are preset" );
	});

	test( "a11y", function() {
		ok( $( "#default .collapsible-header" ).is( "[tabindex='0']" ), "Tabindex added." );
		ok( $( "#default .collapsible-header" ).is( "[role=button]" ), "Role added." );
	});

	test( "inner button", function() {
		ok( $( "#innerButton .collapsible-header button" ).length, "button exists" );
		ok( $( "#innerButton .collapsible-header button" ).is( "[aria-expanded='false']" ), "aria-expanded attr (false) is on the button" );
		ok( $( "#innerButton .collapsible-header button" ).text() === "Toggle collapsible content", "button content is correct" );
		$( "#innerButton .collapsible-header button" ).trigger( "click" );
		ok( $( "#innerButton .collapsible-header button" ).is( "[aria-expanded='true']" ), "aria-expanded attr (true) is on the button" );
		$( "#innerButton .collapsible-header button" ).trigger( "click" );
		ok( $( "#innerButton .collapsible-header button" ).is( "[aria-expanded='false']" ), "aria-expanded attr (false) is on the button" );
	});

	test( "Click the header", function() {
		$( "#default .collapsible-header" ).trigger( "click" );
		ok( $( "#default .collapsible-content" ).is( ":hidden" ), "Content is hidden after header click." );

		$( "#default .collapsible-header" ).trigger( "click" );
		ok( $( "#default .collapsible-content" ).is( ":visible" ), "Content is visible after header second click." );

	});

	module( "Collapsed Initialization", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.collapsible' ).collapsible();
		}
	});

	test( "Initialization", function() {
		ok( $( "#collapsed .collapsible-content" ).is( ":hidden" ), "Content is hidden by default." );
	});

	test( "Click the header", function() {
		$( "#collapsed .collapsible-header" ).trigger( "click" );
		ok( !$( "#collapsed .collapsible-content" ).is( ":hidden" ), "Content is visible after header click." );

		$( "#collapsed .collapsible-header" ).trigger( "click" );
		ok( $( "#collapsed .collapsible-content" ).is( ":hidden" ), "Content is hidden after header second click." );
	});

	module( "Accordion Plugin", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.collapsible' ).removeData( 'collapsible' ).collapsible();
		}
	});

	test( "Click the header", function() {
		ok( $( "#accordion-c .collapsible-content" ).is( ":hidden" ), "Third unrelated collapsible content initial state." );

		$( "#accordion-a .collapsible-header" ).trigger( "click" );
		ok( !$( "#accordion-a .collapsible-content" ).is( ":hidden" ), "First accordion collapsible content is visible after header click." );
		ok( $( "#accordion-c .collapsible-content" ).is( ":hidden" ), "Third unrelated collapsible content is still hidden after header click." );

		$( "#accordion-b .collapsible-header" ).trigger( "click" );
		ok( !$( "#accordion-b .collapsible-content" ).is( ":hidden" ), "Second accordion collapsible content is visible after header click." );
		ok( $( "#accordion-a .collapsible-content" ).is( ":hidden" ), "First accordion collapsible content is visible after second collapsible header click." );
		ok( $( "#accordion-c .collapsible-content" ).is( ":hidden" ), "Third unrelated collapsible content is still hidden after header click." );
	});

	module( "Tabs Plugin", {
		setup: function(){
			$( '#qunit-fixture' ).find( '.tabnav' ).remove();
			$( '#qunit-fixture' ).find( '.collapsible' ).removeData( 'collapsible' ).collapsible();
		}
	});

	test( "Click the header", function() {
		ok( !$( "#tabs-a .collapsible-content" ).is( ":hidden" ), "Initial state of first tab: visible" );
		ok( $( "#tabs-b .collapsible-content" ).is( ":hidden" ), "Initial state of second tab: hidden" );

		$( "#tabs .tabnav a" ).eq( 1 ).trigger( "click" );
		ok( $( "#tabs-a .collapsible-content" ).is( ":hidden" ), "Initial state of first tab: hidden" );
		ok( !$( "#tabs-b .collapsible-content" ).is( ":hidden" ), "Initial state of second tab: visible" );
	});

	module( "Menu Plugin", {
		setup: function(){
				$( '#qunit-fixture' ).find( '.collapsible' ).collapsible();
		}
	});

	test( "Hover header", function() {
		ok( $( "#menu .collapsible-content" ).is( ":hidden" ), "Menu collapsible content initial state." );

		$( "#menu" ).trigger( "mouseenter" );
		ok( !$( "#menu .collapsible-content" ).is( ":visible" ), "Menu collapsible content visible after mouseenter." );

		$( "#menu" ).trigger( "mouseleave" );
		ok( $( "#menu .collapsible-content" ).is( ":hidden" ), "Menu collapsible content hidden after mouseleave." );
	});
}(jQuery));
<|endoftext|>


<commit_before>const puppeteer = require('puppeteer');
const assert = require("assert");

let browser;

describe('Test Puppeteer', async () => {
  before(async () => {
    browser = await puppeteer.launch({
      timeout: 0,
      headless: true
    });
  });

  describe('Open Google', () => {
    it('Should done open Google site with Search result', async () => {
      const page = await browser.newPage();
      await page.setViewport({
        width: 1280,
        height: 720
      });
      await page.goto('https://www.google.com', { waitUntil: 'networkidle' });
      await page.type('input[id="lst-ib"]', 'TakeMeTour');
      await page.click('input[name="btnK"]');
      await page.waitForSelector('#resultStats');
      const results = await page.$eval('#resultStats', div => div.innerHTML);
      assert.equal(0, results.indexOf('ผลการค้นหา'));
      return page.close();
    })
  })

  after(async () => browser.close())
});
<commit_msg>Before and After global browser<commit_after>const puppeteer = require('puppeteer');
const assert = require("assert");

let browser;

before(async () => {
  global.browser = await puppeteer.launch({
    timeout: 0,
    headless: true
  });
});

describe('Test Puppeteer', async () => {
  describe('Open Google', () => {
    it('Should done open Google site with Search result', async () => {
      const page = await global.browser.newPage();
      await page.setViewport({
        width: 1280,
        height: 720
      });
      await page.goto('https://www.google.com', { waitUntil: 'networkidle' });
      await page.type('input[id="lst-ib"]', 'TakeMeTour');
      await page.click('input[name="btnK"]');
      await page.waitForSelector('#resultStats');
      const results = await page.$eval('#resultStats', div => div.innerHTML);
      assert.equal(0, results.indexOf('ผลการค้นหา'));
      return page.close();
    })
  })
});

after(async () => global.browser.close());
<|endoftext|>


<commit_before>'use strict';

// https://github.com/websockets/ws/
const WebSocketServer = require('ws').Server;
const log = require('./log');

export class WebAPI {
  constructor (cdb, port) {
    this.cdb = cdb;
    this.clientId = 0;
    this.wss = new WebSocketServer({ port: port });

    this.wss.broadcast = (data, clientList) => {
      if (clientList === undefined) {
        clientList = this.wss.clients;
      }

      clientList.forEach(function each(client) {
        client.send(data);
      });
    };

    this.wss.on('connection', (client) => {
      // increment id counter
      const thisId = ++this.clientId;

      // we accepted message from user!
      client.on('message', (rawMessage) => {
        this.cdb.processUserActivity(JSON.parse(rawMessage), client);
      });

      client.on('close', () => {
        log.warn(`Client disconnected: ${thisId}`);
      });

      client.on('error', (e) => {
        log.error(`Client ${thisId} error: ${e.message}`);
      });
    });

    log.info('Web API started');
  }

  static getChangePosition(login, x, y, direction) {
    let ret = {};

    ret.login = login;
    ret.x = x;
    ret.y = y;

    if (direction) {
      ret.direction = direction;
    }

    return ret;
  }

  static sendInitialResponse(client, login, locationMap, x, y) {
    let resp = {'changePosition': WebAPI.getChangePosition(login, x, y)};
    resp.allMap = locationMap;

    client.send(JSON.stringify(resp));
  }

  sendChangePositionBroadcast(clientList, login, direction, x, y) {
    let resp = {'changePosition': WebAPI.getChangePosition(login, x, y, direction)};

    this.wss.broadcast(JSON.stringify(resp), clientList);
  }
}
<commit_msg>new method sendRemoveUserBroadcast<commit_after>'use strict';

// https://github.com/websockets/ws/
const WebSocketServer = require('ws').Server;
const log = require('./log');

export class WebAPI {
  constructor (cdb, port) {
    this.cdb = cdb;
    this.clientId = 0;
    this.wss = new WebSocketServer({ port: port });

    this.wss.broadcast = (data, clientList) => {
      if (clientList === undefined) {
        clientList = this.wss.clients;
      }

      clientList.forEach(function each(client) {
        client.send(data);
      });
    };

    this.wss.on('connection', (client) => {
      // increment id counter
      const thisId = ++this.clientId;

      // we accepted message from user!
      client.on('message', (rawMessage) => {
        this.cdb.processUserActivity(JSON.parse(rawMessage), client);
      });

      client.on('close', () => {
        log.warn(`Client disconnected: ${thisId}`);
      });

      client.on('error', (e) => {
        log.error(`Client ${thisId} error: ${e.message}`);
      });
    });

    log.info('Web API started');
  }

  static getChangePosition(login, x, y, direction) {
    let ret = {};

    ret.login = login;
    ret.x = x;
    ret.y = y;

    if (direction) {
      ret.direction = direction;
    }

    return ret;
  }

  static sendInitialResponse(client, login, locationMap, x, y) {
    const resp = {'changePosition': WebAPI.getChangePosition(login, x, y)};
    resp.allMap = locationMap;

    client.send(JSON.stringify(resp));
  }

  sendRemoveUserBroadcast(clientList, login) {
    const resp = {'removeFromLocation': login};

    this.wss.broadcast(JSON.stringify(resp), clientList);
  }

  sendChangePositionBroadcast(clientList, login, direction, x, y) {
    const resp = {'changePosition': WebAPI.getChangePosition(login, x, y, direction)};

    this.wss.broadcast(JSON.stringify(resp), clientList);
  }
}
<|endoftext|>


<commit_before>/*
//
// FROM functions Alasql.js
// Date: 11.12.2014
// (c) 2014, Andrey Gershun
//
*/

/**
   Meteor
*/

alasql.from.METEOR = function(filename, opts, cb, idx, query) {
	var res = filename.find(opts).fetch();
	if(cb){
		res = cb(res, idx, query);
	}
	return res;
 };

/**
	Google Spreadsheet reader
 */
alasql.from.TABLETOP = function(key, opts, cb, idx, query) {
	var res = [];

	var opt = {headers:true, simpleSheet:true, key:key};
	alasql.utils.extend(opt, opts);
	opt.callback = function(data){
		res = data;
		if(cb){
			res = cb(res, idx, query);
		}
	};

	Tabletop.init(opt);
	return res;
};

alasql.from.HTML = function(selector, opts, cb, idx, query) {
	var opt = {};
	alasql.utils.extend(opt, opts);

	var sel = document.querySelector(selector);
	if(!sel && sel.tagName !== "TABLE") {
		throw new Error('Selected HTML element is not a TABLE');
	}

	var res = [];
	var headers = opt.headers;

	if(headers && !(headers instanceof Array)) {
		headers = [];
		var ths = sel.querySelector("thead tr").children;
		for(var i=0;i<ths.length;i++){
			if(!(ths.item(i).style && ths.item(i).style.display === "none" && opt.skipdisplaynone)) {
				headers.push(ths.item(i).textContent);
			} else {
				headers.push(undefined);
			}
		}
	}
//	console.log(headers);

	var trs = sel.querySelectorAll("tbody tr");

	for(var j=0;j<trs.length;j++) {
		var tds = trs.item(j).children;
		var r = {};
		for(var i=0;i<tds.length;i++){
			if(!(tds.item(i).style && tds.item(i).style.display === "none" && opt.skipdisplaynone)) {
				if(headers) {
					r[headers[i]] = tds.item(i).textContent;
				} else {
					r[i] = tds.item(i).textContent;
	//				console.log(r);
				}
			}
		}
		res.push(r);
	}
//console.log(res);
	if(cb){
		res = cb(res, idx, query);
	}
	return res;
}

alasql.from.RANGE = function(start, finish, cb, idx, query) {
	var res = [];
	for(var i=start;i<=finish;i++){
		res.push(i);
	}
//	res = new alasql.Recordset({data:res,columns:{columnid:'_'}});
	if(cb){
		res = cb(res, idx, query);
	}
	return res;
}

// Read data from any file
alasql.from.FILE = function(filename, opts, cb, idx, query) {
	var fname;
	if(typeof filename === 'string') {
		fname = filename;

	} else if(filename instanceof Event) {
		fname = filename.target.files[0].name;

	} else {
		throw new Error("Wrong usage of FILE() function");
	}

	var parts = fname.split('.');
//	console.log("parts",parts,parts[parts.length-1]);
	var ext = parts[parts.length-1].toUpperCase();
//	console.log("ext",ext);
	if(alasql.from[ext]) {
//		console.log(ext);
		return alasql.from[ext](filename, opts, cb, idx, query);
	} else {
		throw new Error('Cannot recognize file type for loading');
	}
};

// Read JSON file

alasql.from.JSON = function(filename, opts, cb, idx, query) {
	var res;
	//console.log('cb',cb);
//console.log('JSON');
	alasql.utils.loadFile(filename,!!cb,function(data){
//		console.log('DATA:'+data);
//		res = [{a:1}];
		res = JSON.parse(data);
		if(cb){
			res = cb(res, idx, query);
		}
	});
	return res;
};

alasql.from.TXT = function(filename, opts, cb, idx, query) {
	var res;
	alasql.utils.loadFile(filename,!!cb,function(data){
		res = data.split(/\r?\n/);
		if(res[res.length-1] === '') res.pop(); // Remove last line if empty
		for(var i=0, ilen=res.length; i<ilen;i++) {
			// Please avoid '===' here
			if(res[i] == +res[i]){	// jshint ignore:line
				res[i] = +res[i];
			}
			res[i] = [res[i]];
		}
		if(cb){
			res = cb(res, idx, query);
		}
	});
	return res;
};

alasql.from.TAB = alasql.from.TSV = function(filename, opts, cb, idx, query) {
	opts = opts || {};
	opts.separator = '\t';
	return alasql.from.CSV(filename, opts, cb, idx, query);
};

alasql.from.CSV = function(filename, opts, cb, idx, query) {
	var opt = {
		separator: ',',
		quote: '"',
		headers:true
	};
	alasql.utils.extend(opt, opts);
	var res, hs;
	alasql.utils.loadFile(filename,!!cb,function(text){

		var delimiterCode = opt.separator.charCodeAt(0);
		var quoteCode = opt.quote.charCodeAt(0);

      	var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
			function token() {
			if (I >= N){
				return EOF;
			}
			if (eol){
				return eol = false, EOL;
			}
			var j = I;
			if (text.charCodeAt(j) === quoteCode) {
				var i = j;
				while (i++ < N) {
					if (text.charCodeAt(i) === quoteCode) {
						if (text.charCodeAt(i + 1) !== quoteCode){
							break;
						}
						++i;
					}
				}
				I = i + 2;
				var c = text.charCodeAt(i + 1);
				if (c === 13) {
					eol = true;
					if (text.charCodeAt(i + 2) === 10){
						++I;
					}
				} else if (c === 10) {
					eol = true;
				}
				return text.substring(j + 1, i).replace(/""/g, '"');
			}
			while (I < N) {
				var c = text.charCodeAt(I++), k = 1;
				if(c === 10){
					eol = true;
				} else if (c === 13) {
					eol = true;
					if (text.charCodeAt(I) === 10){
						++I;
						++k;
					}
				} else if(c !== delimiterCode){
					continue;
				}
				return text.substring(j, I - k);
			}
			return text.substring(j);
		}

		while ((t = token()) !== EOF) {
		var a = [];
		while (t !== EOL && t !== EOF) {
		a.push(t);
		t = token();
		}

        if(opt.headers) {
        	if(n === 0) {
				if(typeof opt.headers === 'boolean') {
	        		hs = a;
				} else if(opt.headers instanceof Array) {
					hs = opt.headers;
	        		var r = {};
	        		hs.forEach(function(h,idx){
	        			r[h] = a[idx];
	        			// Please avoid === here
						if((typeof r[h] !== 'undefined') && r[h].length !== 0 && (r[h]).trim() == +r[h]){ // jshint ignore:line
							r[h] = +r[h];
						}
	        		});
					rows.push(r);
				}

        	} else {
        		var r = {};
        		hs.forEach(function(h,idx){
        			r[h] = a[idx];
					if((typeof r[h] !== 'undefined') && r[h].length !== 0 && r[h].trim() == +r[h]){ // jshint ignore:line
						r[h] = +r[h];
					}
        		});
        		rows.push(r);
        	}
        	n++;
        } else {
    	    rows.push(a);
    	}
      }

      res = rows;

	if(opt.headers) {
		if(query && query.sources && query.sources[idx]) {
			var columns = query.sources[idx].columns = [];
			hs.forEach(function(h){
				columns.push({columnid:h});
			});
		}
	}

/*/*
if(false) {
		res = data.split(/\r?\n/);
		if(opt.headers) {
			if(query && query.sources && query.sources[idx]) {
				var hh = [];
				if(typeof opt.headers == 'boolean') {
					hh = res.shift().split(opt.separator);
				} else if(opt.headers instanceof Array) {
					hh = opt.headers;
				}
				var columns = query.sources[idx].columns = [];
				hh.forEach(function(h){
					columns.push({columnid:h});
				});
				for(var i=0, ilen=res.length; i<ilen;i++) {
					var a = res[i].split(opt.separator);
					var b = {};
					hh.forEach(function(h,j){
						b[h] = a[j];
					});
					res[i] = b;
				}
//				console.log(res[0]);
			}
		} else {
			for(var i=0, ilen=res.length; i<ilen;i++) {
				res[i] = res[i].split(opt.separator);
			}
		}

};
*/
		if(cb){
			res = cb(res, idx, query);
		}
	});
	return res;
};

function XLSXLSX(X,filename, opts, cb, idx, query) {
	var opt = {};
	opts = opts || {};
	alasql.utils.extend(opt, opts);
	if(typeof opt.headers == 'undefined') opt.headers = true;
	var res;

	alasql.utils.loadBinaryFile(filename,!!cb,function(data){

//	function processData(data) {
		var workbook = X.read(data,{type:'binary'});
//		console.log(workbook);
		var sheetid;
		if(typeof opt.sheetid === 'undefined') {
			sheetid = workbook.SheetNames[0];
		} else {
			sheetid = opt.sheetid;
		}
		var range;
		if(typeof opt.range === 'undefined') {
			range = workbook.Sheets[sheetid]['!ref'];
		} else {
			range = opt.range;
			if(workbook.Sheets[sheetid][range]){
				range = workbook.Sheets[sheetid][range];
			}
		}
		var rg = range.split(':');
		var col0 = rg[0].match(/[A-Z]+/)[0];
		var row0 = +rg[0].match(/[0-9]+/)[0];
		var col1 = rg[1].match(/[A-Z]+/)[0];
		var row1 = +rg[1].match(/[0-9]+/)[0];
//		console.log(114,rg,col0,col1,row0,row1);
//		console.log(114,rg,alasql.utils.xlscn(col0),alasql.utils.xlscn(col1));

		var hh = {};
		for(var j=alasql.utils.xlscn(col0);j<=alasql.utils.xlscn(col1);j++){
			var col = alasql.utils.xlsnc(j);
			if(opt.headers) {
				if(workbook.Sheets[sheetid][col+""+row0]) {
					hh[col] = workbook.Sheets[sheetid][col+""+row0].v;
				} else {
					hh[col] = col;
				}
			} else {
				hh[col] = col;
			}
		}
		var res = [];
		if(opt.headers){
			row0++;
		}
		for(var i=row0;i<=row1;i++) {
			var row = {};
			for(var j=alasql.utils.xlscn(col0);j<=alasql.utils.xlscn(col1);j++){
				var col = alasql.utils.xlsnc(j);
				if(workbook.Sheets[sheetid][col+""+i]) {
					row[hh[col]] = workbook.Sheets[sheetid][col+""+i].v;
				}
			}
			res.push(row);
		}

		// Remove last empty line (issue #548)
		if(res.length > 0 && res[res.length-1] && Object.keys(res[res.length-1]).length == 0) {
			res.pop();
		}

		if(cb){
			res = cb(res, idx, query);
		}
	}, function(err){
		throw err;
	});

	return res;
}

alasql.from.XLS = function(filename, opts, cb, idx, query) {
	var X;
	if(utils.isNode) {
		X = require('xlsjs');
	} else {
		X = utils.global.XLS;
		if(!X) {
			throw new Error('XLS library is not attached');
		}
	}
	return XLSXLSX(X,filename, opts, cb, idx, query);
}

alasql.from.XLSX = function(filename, opts, cb, idx, query) {
	var X;
	if(utils.isNode) {
		X = require('xlsx');
	} else {
		X = utils.global.XLSX;
		if(!X) {
			throw new Error('XLSX library is not attached');
		}
	}
	return XLSXLSX(X,filename, opts, cb, idx, query);
};

<commit_msg>Better error text<commit_after>/*
//
// FROM functions Alasql.js
// Date: 11.12.2014
// (c) 2014, Andrey Gershun
//
*/

/**
   Meteor
*/

alasql.from.METEOR = function(filename, opts, cb, idx, query) {
	var res = filename.find(opts).fetch();
	if(cb){
		res = cb(res, idx, query);
	}
	return res;
 };

/**
	Google Spreadsheet reader
 */
alasql.from.TABLETOP = function(key, opts, cb, idx, query) {
	var res = [];

	var opt = {headers:true, simpleSheet:true, key:key};
	alasql.utils.extend(opt, opts);
	opt.callback = function(data){
		res = data;
		if(cb){
			res = cb(res, idx, query);
		}
	};

	Tabletop.init(opt);
	return res;
};

alasql.from.HTML = function(selector, opts, cb, idx, query) {
	var opt = {};
	alasql.utils.extend(opt, opts);

	var sel = document.querySelector(selector);
	if(!sel && sel.tagName !== "TABLE") {
		throw new Error('Selected HTML element is not a TABLE');
	}

	var res = [];
	var headers = opt.headers;

	if(headers && !(headers instanceof Array)) {
		headers = [];
		var ths = sel.querySelector("thead tr").children;
		for(var i=0;i<ths.length;i++){
			if(!(ths.item(i).style && ths.item(i).style.display === "none" && opt.skipdisplaynone)) {
				headers.push(ths.item(i).textContent);
			} else {
				headers.push(undefined);
			}
		}
	}
//	console.log(headers);

	var trs = sel.querySelectorAll("tbody tr");

	for(var j=0;j<trs.length;j++) {
		var tds = trs.item(j).children;
		var r = {};
		for(var i=0;i<tds.length;i++){
			if(!(tds.item(i).style && tds.item(i).style.display === "none" && opt.skipdisplaynone)) {
				if(headers) {
					r[headers[i]] = tds.item(i).textContent;
				} else {
					r[i] = tds.item(i).textContent;
	//				console.log(r);
				}
			}
		}
		res.push(r);
	}
//console.log(res);
	if(cb){
		res = cb(res, idx, query);
	}
	return res;
}

alasql.from.RANGE = function(start, finish, cb, idx, query) {
	var res = [];
	for(var i=start;i<=finish;i++){
		res.push(i);
	}
//	res = new alasql.Recordset({data:res,columns:{columnid:'_'}});
	if(cb){
		res = cb(res, idx, query);
	}
	return res;
}

// Read data from any file
alasql.from.FILE = function(filename, opts, cb, idx, query) {
	var fname;
	if(typeof filename === 'string') {
		fname = filename;

	} else if(filename instanceof Event) {
		fname = filename.target.files[0].name;

	} else {
		throw new Error("Wrong usage of FILE() function");
	}

	var parts = fname.split('.');
//	console.log("parts",parts,parts[parts.length-1]);
	var ext = parts[parts.length-1].toUpperCase();
//	console.log("ext",ext);
	if(alasql.from[ext]) {
//		console.log(ext);
		return alasql.from[ext](filename, opts, cb, idx, query);
	} else {
		throw new Error('Cannot recognize file type for loading');
	}
};

// Read JSON file

alasql.from.JSON = function(filename, opts, cb, idx, query) {
	var res;
	//console.log('cb',cb);
//console.log('JSON');
	alasql.utils.loadFile(filename,!!cb,function(data){
//		console.log('DATA:'+data);
//		res = [{a:1}];
		res = JSON.parse(data);
		if(cb){
			res = cb(res, idx, query);
		}
	});
	return res;
};

alasql.from.TXT = function(filename, opts, cb, idx, query) {
	var res;
	alasql.utils.loadFile(filename,!!cb,function(data){
		res = data.split(/\r?\n/);
		if(res[res.length-1] === '') res.pop(); // Remove last line if empty
		for(var i=0, ilen=res.length; i<ilen;i++) {
			// Please avoid '===' here
			if(res[i] == +res[i]){	// jshint ignore:line
				res[i] = +res[i];
			}
			res[i] = [res[i]];
		}
		if(cb){
			res = cb(res, idx, query);
		}
	});
	return res;
};

alasql.from.TAB = alasql.from.TSV = function(filename, opts, cb, idx, query) {
	opts = opts || {};
	opts.separator = '\t';
	return alasql.from.CSV(filename, opts, cb, idx, query);
};

alasql.from.CSV = function(filename, opts, cb, idx, query) {
	var opt = {
		separator: ',',
		quote: '"',
		headers:true
	};
	alasql.utils.extend(opt, opts);
	var res, hs;
	alasql.utils.loadFile(filename,!!cb,function(text){

		var delimiterCode = opt.separator.charCodeAt(0);
		var quoteCode = opt.quote.charCodeAt(0);

      	var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
			function token() {
			if (I >= N){
				return EOF;
			}
			if (eol){
				return eol = false, EOL;
			}
			var j = I;
			if (text.charCodeAt(j) === quoteCode) {
				var i = j;
				while (i++ < N) {
					if (text.charCodeAt(i) === quoteCode) {
						if (text.charCodeAt(i + 1) !== quoteCode){
							break;
						}
						++i;
					}
				}
				I = i + 2;
				var c = text.charCodeAt(i + 1);
				if (c === 13) {
					eol = true;
					if (text.charCodeAt(i + 2) === 10){
						++I;
					}
				} else if (c === 10) {
					eol = true;
				}
				return text.substring(j + 1, i).replace(/""/g, '"');
			}
			while (I < N) {
				var c = text.charCodeAt(I++), k = 1;
				if(c === 10){
					eol = true;
				} else if (c === 13) {
					eol = true;
					if (text.charCodeAt(I) === 10){
						++I;
						++k;
					}
				} else if(c !== delimiterCode){
					continue;
				}
				return text.substring(j, I - k);
			}
			return text.substring(j);
		}

		while ((t = token()) !== EOF) {
		var a = [];
		while (t !== EOL && t !== EOF) {
		a.push(t);
		t = token();
		}

        if(opt.headers) {
        	if(n === 0) {
				if(typeof opt.headers === 'boolean') {
	        		hs = a;
				} else if(opt.headers instanceof Array) {
					hs = opt.headers;
	        		var r = {};
	        		hs.forEach(function(h,idx){
	        			r[h] = a[idx];
	        			// Please avoid === here
						if((typeof r[h] !== 'undefined') && r[h].length !== 0 && (r[h]).trim() == +r[h]){ // jshint ignore:line
							r[h] = +r[h];
						}
	        		});
					rows.push(r);
				}

        	} else {
        		var r = {};
        		hs.forEach(function(h,idx){
        			r[h] = a[idx];
					if((typeof r[h] !== 'undefined') && r[h].length !== 0 && r[h].trim() == +r[h]){ // jshint ignore:line
						r[h] = +r[h];
					}
        		});
        		rows.push(r);
        	}
        	n++;
        } else {
    	    rows.push(a);
    	}
      }

      res = rows;

	if(opt.headers) {
		if(query && query.sources && query.sources[idx]) {
			var columns = query.sources[idx].columns = [];
			hs.forEach(function(h){
				columns.push({columnid:h});
			});
		}
	}

/*/*
if(false) {
		res = data.split(/\r?\n/);
		if(opt.headers) {
			if(query && query.sources && query.sources[idx]) {
				var hh = [];
				if(typeof opt.headers == 'boolean') {
					hh = res.shift().split(opt.separator);
				} else if(opt.headers instanceof Array) {
					hh = opt.headers;
				}
				var columns = query.sources[idx].columns = [];
				hh.forEach(function(h){
					columns.push({columnid:h});
				});
				for(var i=0, ilen=res.length; i<ilen;i++) {
					var a = res[i].split(opt.separator);
					var b = {};
					hh.forEach(function(h,j){
						b[h] = a[j];
					});
					res[i] = b;
				}
//				console.log(res[0]);
			}
		} else {
			for(var i=0, ilen=res.length; i<ilen;i++) {
				res[i] = res[i].split(opt.separator);
			}
		}

};
*/
		if(cb){
			res = cb(res, idx, query);
		}
	});
	return res;
};

function XLSXLSX(X,filename, opts, cb, idx, query) {
	var opt = {};
	opts = opts || {};
	alasql.utils.extend(opt, opts);
	if(typeof opt.headers == 'undefined') opt.headers = true;
	var res;

	alasql.utils.loadBinaryFile(filename,!!cb,function(data){

//	function processData(data) {
		var workbook = X.read(data,{type:'binary'});
//		console.log(workbook);
		var sheetid;
		if(typeof opt.sheetid === 'undefined') {
			sheetid = workbook.SheetNames[0];
		} else {
			sheetid = opt.sheetid;
		}
		var range;
		if(typeof opt.range === 'undefined') {
			range = workbook.Sheets[sheetid]['!ref'];
		} else {
			range = opt.range;
			if(workbook.Sheets[sheetid][range]){
				range = workbook.Sheets[sheetid][range];
			}
		}
		var rg = range.split(':');
		var col0 = rg[0].match(/[A-Z]+/)[0];
		var row0 = +rg[0].match(/[0-9]+/)[0];
		var col1 = rg[1].match(/[A-Z]+/)[0];
		var row1 = +rg[1].match(/[0-9]+/)[0];
//		console.log(114,rg,col0,col1,row0,row1);
//		console.log(114,rg,alasql.utils.xlscn(col0),alasql.utils.xlscn(col1));

		var hh = {};
		for(var j=alasql.utils.xlscn(col0);j<=alasql.utils.xlscn(col1);j++){
			var col = alasql.utils.xlsnc(j);
			if(opt.headers) {
				if(workbook.Sheets[sheetid][col+""+row0]) {
					hh[col] = workbook.Sheets[sheetid][col+""+row0].v;
				} else {
					hh[col] = col;
				}
			} else {
				hh[col] = col;
			}
		}
		var res = [];
		if(opt.headers){
			row0++;
		}
		for(var i=row0;i<=row1;i++) {
			var row = {};
			for(var j=alasql.utils.xlscn(col0);j<=alasql.utils.xlscn(col1);j++){
				var col = alasql.utils.xlsnc(j);
				if(workbook.Sheets[sheetid][col+""+i]) {
					row[hh[col]] = workbook.Sheets[sheetid][col+""+i].v;
				}
			}
			res.push(row);
		}

		// Remove last empty line (issue #548)
		if(res.length > 0 && res[res.length-1] && Object.keys(res[res.length-1]).length == 0) {
			res.pop();
		}

		if(cb){
			res = cb(res, idx, query);
		}
	}, function(err){
		throw err;
	});

	return res;
}

alasql.from.XLS = function(filename, opts, cb, idx, query) {
	var X;
	if(utils.isNode) {
		X = require('xlsjs');
	} else {
		X = utils.global.XLS;
		if(!X) {
			throw new Error('XLS library is not attached');
		}
	}
	return XLSXLSX(X,filename, opts, cb, idx, query);
}

alasql.from.XLSX = function(filename, opts, cb, idx, query) {
	var X;
	if(utils.isNode) {
		X = require('xlsx');
	} else {
		X = utils.global.XLSX;
		if(!X) {
			throw new Error('XLSX library not found');
		}
	}
	return XLSXLSX(X,filename, opts, cb, idx, query);
};

<|endoftext|>


<commit_before>(function(){
  'use strict';

  var should = require("chai").should();
  var codes = require("../dist-node/index.js");

  describe('switzerland-postal-code', function(){
    it("should return a location", function(){
      var cologny = codes['1223'];
      cologny.should.equal('Cologny');
    });

    it("should return a composed location", function(){
      var cologny = codes['1295'];
      cologny.should.equal('Mies - Tannay');
    });

    it("should contains at least 650 items", function(){
      var enoughLocation = Object.keys(codes).length > 650;
      enoughLocation.should.equal(true);
    });
  });
})();
<commit_msg>update unit tests<commit_after>(function(){
  'use strict';

  var should = require("chai").should();
  var codes = require("../dist-node/index.js");

  describe('switzerland-postal-code', function(){
    it("should return a location", function(){
      var cologny = codes['1223'];
      cologny.should.equal('Cologny');
    });

    it("should return a composed location", function(){
      var cologny = codes['1295'];
      cologny.should.equal('Mies - Tannay');
    });

    it("should contains at least 1500 items", function(){
      var enoughLocation = Object.keys(codes).length > 1500;
      enoughLocation.should.equal(true);
    });
  });
})();
<|endoftext|>


<commit_before>'use strict';

// https://github.com/websockets/ws/
const WebSocketServer = require('ws').Server;
const log = require('./log');

export class WebAPI {
  constructor (cdb, port) {
    this.cdb = cdb;
    this.clientId = 0;
    this.wss = new WebSocketServer({ port: port });

    this.wss.broadcast = (data, clientList) => {
      if (clientList === undefined) {
        clientList = this.wss.clients;
      }

      clientList.forEach(function each(client) {
        client.send(data);
      });
    };

    this.wss.on('connection', (client) => {
      // increment id counter
      const thisId = ++this.clientId;

      // we accepted message from user!
      client.on('message', (rawMessage) => {
        this.cdb.processUserActivity(JSON.parse(rawMessage), client, thisId);
      });

      client.on('close', () => {
        log.warn(`Client disconnected: ${thisId}`);
        this.cdb.switchOffline(thisId);
      });

      client.on('error', (e) => {
        log.error(`Client ${thisId} error: ${e.message}`);
        this.cdb.switchOffline(thisId);
      });
    });

    log.info('Web API started');
  }

  static getChangePosition(login, x, y, direction) {
    let ret = {};

    ret.login = login;
    ret.x = x;
    ret.y = y;

    if (direction) {
      ret.direction = direction;
    }

    return ret;
  }

  static sendInitialResponse(client, login, locationId, locationMap, x, y) {
    const resp = {'changePosition': WebAPI.getChangePosition(login, x, y)};
    resp.allMap = locationMap;
    resp.locationId = locationId;

    client.send(JSON.stringify(resp));
  }

  sendRemoveUserBroadcast(clientList, login) {
    const resp = {'removeFromLocation': login};

    this.wss.broadcast(JSON.stringify(resp), clientList);
  }

  sendChangePositionBroadcast(clientList, login, direction, x, y) {
    const resp = {'changePosition': WebAPI.getChangePosition(login, x, y, direction)};

    this.wss.broadcast(JSON.stringify(resp), clientList);
  }
}
<commit_msg>add spriteConf to initial response<commit_after>'use strict';

// https://github.com/websockets/ws/
const WebSocketServer = require('ws').Server;
const log = require('./log');

export class WebAPI {
  constructor (cdb, port) {
    this.cdb = cdb;
    this.clientId = 0;
    this.wss = new WebSocketServer({ port: port });

    this.wss.broadcast = (data, clientList) => {
      if (clientList === undefined) {
        clientList = this.wss.clients;
      }

      clientList.forEach(function each(client) {
        client.send(data);
      });
    };

    this.wss.on('connection', (client) => {
      // increment id counter
      const thisId = ++this.clientId;

      // we accepted message from user!
      client.on('message', (rawMessage) => {
        this.cdb.processUserActivity(JSON.parse(rawMessage), client, thisId);
      });

      client.on('close', () => {
        log.warn(`Client disconnected: ${thisId}`);
        this.cdb.switchOffline(thisId);
      });

      client.on('error', (e) => {
        log.error(`Client ${thisId} error: ${e.message}`);
        this.cdb.switchOffline(thisId);
      });
    });

    log.info('Web API started');
  }

  static getChangePosition(login, x, y, direction) {
    let ret = {};

    ret.login = login;
    ret.x = x;
    ret.y = y;

    if (direction) {
      ret.direction = direction;
    }

    return ret;
  }

  static sendInitialResponse(client, login, locationId, locationMap, x, y, spriteConf) {
    const resp = {'changePosition': WebAPI.getChangePosition(login, x, y)};
    resp.allMap = locationMap;
    resp.locationId = locationId;
    resp.spriteConf = spriteConf;

    client.send(JSON.stringify(resp));
  }

  sendRemoveUserBroadcast(clientList, login) {
    const resp = {'removeFromLocation': login};

    this.wss.broadcast(JSON.stringify(resp), clientList);
  }

  sendChangePositionBroadcast(clientList, login, direction, x, y) {
    const resp = {'changePosition': WebAPI.getChangePosition(login, x, y, direction)};

    this.wss.broadcast(JSON.stringify(resp), clientList);
  }
}
<|endoftext|>


<commit_before>
"use strict";

class Model {

    constructor(data = {}) {
        this._data = new Map();
        for (let key in data) {
            this._data.set(key, data[key]);
            Object.defineProperty(this, key, {
                get: function() {
                    return this._data[key];
                },
                set: function(value) {
                    this._data[key] = value;
                }
            });
        }
    }

};

export {Model};

<commit_msg>handle these better<commit_after>
"use strict";

class Model {

    constructor(data = {}) {
        this._data = {};
        for (let key in data) {
            this._data[key] = data[key];
            if (!this.hasOwnProperty(key)) {
                this[key] = data[key];
            }
        }
    }

};

export {Model};

<|endoftext|>