<commit_before>var editorDetails = {};

function plugin_init(info, attribs){
	var resultDeferred = new Divmod.Defer.Deferred();
	var window_name = 'editor-plugin-' + info['kind'] + '-' + info['id'];
	var type = info['kind'];

	var editorWindow = window.open('/plugin/editor/' + type, window_name, buildWindowString(attribs));

	editorDetails[window_name] = {
		info			: info,
		resultDeferred	: resultDeferred,
	};

	// this 'thread' waits for the editor window to
	// close before cancelling the waiting deferred
	var spyID = setInterval(function(){
		return function(){
			if(editorWindow && editorWindow.closed && ! resultDeferred._called){
				resultDeferred.callback(null);
				delete editorDetails[window_name];
				clearInterval(spyID);
			}
		}
	}(), 100);

	return resultDeferred;
}

function editor_plugin_init(info){
	if(info['kind'] == 'object'){
		return plugin_init(info, {
			scrollbars:	'no',
			width:		'465',
			height:		'535',
		});
	}
	else if(info['kind'] == 'property'){
		return plugin_init(info, {
			scrollbars:	'no',
			width:		'630',
			height:		'525',
		});
	}
	else if(info['kind'] == 'verb'){
		return plugin_init(info, {
			scrollbars:	'no',
			width:		'970',
			height:		'600',
		});
	}
}

function access_plugin_init(info){
	info['kind'] = 'access';
	return plugin_init(info, {
		scrollbars:	'auto',
		width:		'750',
		height:		'295',
	});
}
<commit_msg>fixed editor window widths on firefox<commit_after>var editorDetails = {};

function plugin_init(info, attribs){
	var resultDeferred = new Divmod.Defer.Deferred();
	var window_name = 'editor-plugin-' + info['kind'] + '-' + info['id'];
	var type = info['kind'];

	var editorWindow = window.open('/plugin/editor/' + type, window_name, buildWindowString(attribs));

	editorDetails[window_name] = {
		info			: info,
		resultDeferred	: resultDeferred,
	};

	// this 'thread' waits for the editor window to
	// close before cancelling the waiting deferred
	var spyID = setInterval(function(){
		return function(){
			if(editorWindow && editorWindow.closed && ! resultDeferred._called){
				resultDeferred.callback(null);
				delete editorDetails[window_name];
				clearInterval(spyID);
			}
		}
	}(), 100);

	return resultDeferred;
}

function editor_plugin_init(info){
	if(info['kind'] == 'object'){
		return plugin_init(info, {
			scrollbars:	'no',
			width:		'500',
			height:		'535',
		});
	}
	else if(info['kind'] == 'property'){
		return plugin_init(info, {
			scrollbars:	'no',
			width:		'690',
			height:		'525',
		});
	}
	else if(info['kind'] == 'verb'){
		return plugin_init(info, {
			scrollbars:	'no',
			width:		'1000',
			height:		'600',
		});
	}
}

function access_plugin_init(info){
	info['kind'] = 'access';
	return plugin_init(info, {
		scrollbars:	'auto',
		width:		'770',
		height:		'295',
	});
}
<|endoftext|>


<commit_before>/**
 * Created by zhangpoor on 16/7/21.
 */
import React, { Component, PropTypes } from 'react';
import {
Animated,
    StyleSheet,
    View,
    Text,
    TouchableHighlight
} from 'react-native';

import UIFactory from './UIFactory'
import Item from './Game001/Item'

let _cannonWidth        = 40;
let _cannonHeight       = 60;
let _cannonBgColor      = 'orange';
let _cannonBasicSpeed   = 0.7;

let _enemyWidth         = 34;
let _enemyHeight        = _enemyWidth;
let _enemyBgColor       = 'red';
let _enemySpeed         = 1.1;
let _countOfEnemyPath   = 8;

let _pageHeight         = UIFactory.winHeight - UIFactory.navHeight - UIFactory.tabBarHeight;

function getGap(){

    let _a = UIFactory.winWidth - _enemyWidth * _countOfEnemyPath;
    let _c = _a / 10;

    return _c;
}

let _gap            = getGap();
let _roomSpace      = _gap + _enemyWidth;
let _fireTime       = 20;
let _enemyTimeCount = 800 / _fireTime ;

class MyView extends Component{

    constructor()
    {
        super();

        this.state      = {
            enemyViews:     PropTypes.array
        };

        this.timeCount          = 0;
        this.timer              = null;

        this.enemys             = [];
        this.state.enemyViews   = [];
        this.enemyCount         = this.enemys.length;
        this.lastPathNo         = 0;
        this.cannon             = this.createCannon();
        this.cannonSpeed        = 0;

        this.btnAdd             = UIFactory.createBtn(
            {backgroundColor:'yellow',width:70,height:30,left:210,top:5},
            'red',
            //this.addEnemy.bind(this)
            this.startTimer.bind(this)
        );
        this.btnMove            = UIFactory.createBtn(
            {backgroundColor:'blue',width:70,height:30,left:285,top:5},
            'red',
            this.stopTimer.bind(this)
        );

        this.btnLeft            = UIFactory.createBtn(
            {backgroundColor:'yellow',width:60,height:40,left:0,top:_pageHeight - 40},
            'red',

            this.speedBtnAciotn.bind(this)
        );
        this.btnRight           = UIFactory.createBtn(
            {backgroundColor:'blue',width:60,height:40,left:UIFactory.winWidth - 60,top:_pageHeight - 40},
            'red',
            this.speedBtnAciotn.bind(this)
        );

        //this.createEnemy();

    }

    info(){
        return ('现在敌人数量:'+this.enemyCount+'\n'+'当前屏幕宽度:'+UIFactory.winWidth);
    }

    render() {
        //alert('cannon:'+this.cannon+'\n'+
        //      'cannonView:'+this.cannon.getItemView());
        return (

            <View style={MyViewStyle.RootPageStyle}>
                {this.cannon.getItemView()}
                {this.state.enemyViews}
                <View style={MyViewStyle.InfoBarStyle}>
                    <Text style={MyViewStyle.InfoStyle}>
                        {this.info()}
                    </Text>
                    {this.btnAdd}
                    {this.btnMove}
                </View>
                {this.btnLeft}
                {this.btnRight}
            </View>

        );
    }

    /*
     *  Timer
     *
     */
    startTimer(){

        if(this.timer == null){

            this.timer = setInterval(
                () => this.timeFire(),
                _fireTime
            );
        }

    }

    stopTimer(){

        this.timer && clearInterval(this.timer);

        this.timer = null;
    }

    timeFire(){
        /// do bussiness
        this.enemyBussiness();

        this.moveEnemys();
        this.moveCannon();

        this.setState(this.state);
    }

/*
 *  EnemyBlock
 *
 */
    enemyBussiness(){

        this.timeCount++;
        if(this.timeCount >= _enemyTimeCount)
        {
            this.addEnemy();
            this.timeCount = 0;
        }

    }

    enemyXY(itemId){

        return({

            top:    40,
            left:   _gap + itemId * _roomSpace
        });

    }

    createEnemy(){

        let _pathNo     = Math.ceil(_countOfEnemyPath * Math.random()) - 1;

        var _pathFinal  = _pathNo;
        if(this.lastPathNo == _pathFinal){
            //如果是奇数,中间那个可能会重复
            _pathFinal = _countOfEnemyPath - 1 - _pathFinal;
        }

        this.lastPathNo = _pathFinal;

        var _e = new Item(
            MyViewStyle.EnemyBasicStyle,
            this.enemyXY(_pathFinal)
        );

        this.state.enemyViews.push(_e.view);
        this.enemys.push(_e);
        this.enemyCount = this.enemys.length;

    }

    addEnemy(){

        this.createEnemy();
        //this.setState(this.state);
    }

    moveEnemys() {

        this.state.enemyViews = [];
        var _es = this.enemys;
        this.enemys = [];
        for(var i = 0 ; i < this.enemyCount ;i++){
            var _e = _es[i];
            var _v = _e.moveY(_enemySpeed);

            if(_e.state.mTop < _pageHeight){
                this.enemys.push(_e);
                this.state.enemyViews.push(_v);

            }
        }

        this.enemyCount         = this.enemys.length;

        //this.setState(this.state);
    }

/*
 *  Cannon
 *
 */
    createCannon(){
        var _c = new Item(
            MyViewStyle.CannonBasicStyle,
            {
                left:(UIFactory.winWidth - _cannonWidth)/2.0,
                top:_pageHeight - _cannonHeight - 10,

            }
        );

        return _c;

    }

    moveCannon() {
        let _rxBoundle =  UIFactory.winWidth - this.cannon.mWidth;
        let _lxBoundle =  0;

        this.cannon.moveX(this.cannonSpeed);
        if(this.cannon.state.mLeft > _rxBoundle)
        {
            this.cannon.state.mLeft = _rxBoundle;
            this.cannonSpeed = 0;
        }
        if(this.cannon.state.mLeft < 0)
        {
            this.cannon.state.mLeft = 0;
            this.cannonSpeed = 0;
        }
        //this.setState(this.state);
    }

/*
 *  SpeedButtonAction
 */
    speedBtnAciotn(e){

        alert(Object.keys(e));
    }

}

const MyViewStyle = StyleSheet.create({
    RootPageStyle:
    {
        position:'absolute',
        width: UIFactory.winWidth,
        height:_pageHeight,
        top: UIFactory.navHeight,
        backgroundColor: 'gray'
    },
    InfoStyle:{
        position:'absolute',
        width: 200,
        height:35,
        top: 0,
        left:0,
        backgroundColor: 'black',
        color:'white',
        fontSize:10
    },
    InfoBarStyle:{
        position:'absolute',
        width: UIFactory.winWidth,
        height:35,
        top: 0,
        left:0,
        backgroundColor: '#218141'
    },
    EnemyBasicStyle:{
        position:'absolute',
        width: _enemyWidth,
        height:_enemyHeight,
        backgroundColor: _enemyBgColor,
        borderRadius:_enemyWidth/2.0

    },
    CannonBasicStyle:{
        position:'absolute',
        width: _cannonWidth,
        height:_cannonHeight,
        backgroundColor: _cannonBgColor

    },

});

export default MyView;

/*

 this.state      = {
 fadeAnim:(new Animated.Value(0)), //设置初始值
 viewAStyle:MyViewStyle.A,
 viewStyle:MyViewStyle.Bg_A
 };

 this.flag       = true;

 this.aaa        = new UIFactory().aFun();
 this.anim=this.anim.bind(this);
 //this.BtnAClick=this.BtnAClick.bind(this);

 this.viewA      = UIFactory.createView(this.state.viewAStyle);
 this.btnA       = UIFactory.createBtn(
 {backgroundColor:'yellow',width:120,height:50,left:100,top:100},
 'red',()=>this.BtnAClick()
 );
 this.aniView    = UIFactory.createAnimatedView(
 {backgroundColor:'pink',width:50,height:50,left:50,top:120},
 this.state.fadeAnim
 );
 anim(p0)
 {

 //console.log('p0:'+p0);
 //alert('p0:'+_abc.ppp);

 Animated.timing(
 this.state.fadeAnim,//初始值
 {
 toValue: p0,    //结束值
 duration:2000   //持续时间
 }
 ).start(

 ()=>this.anim(100 - p0) // fun
 //this.anim(100 - p0)   // void

 );
 }
 {this.eView}
 <View style={[
 MyViewStyle.EnemyBasicStyle,
 {top:this.state.eTop}
 ]} />
 {this.enemyViews}
 <View style={[
 MyViewStyle.EnemyBasicStyle,
 {top:this.state.eTop}]}/>
 {this.state.enemyViews}

 shouldComponentUpdate(nextProps, nextState)
 {
 alert('old'+ this.state.viewASheet);
 alert('next'+ nextState.viewASheet);

 return this.state.viewASheet !== nextState.viewASheet;
 }

 Red: {
 backgroundColor:'red',
 width:  200,
 height: 100
 },
 Brown: {
 backgroundColor:'brown',
 width:  200,
 height: 100
 },
 A: {
 left:10,
 top:10,
 width:  200,
 height: 100,
 backgroundColor:'green'
 },

 Bg_A:{
 left:0,
 marginTop:64,
 width:  320,
 height: 600,
 opacity: 0.5,
 backgroundColor:'#112233'
 },
 Bg_B:{
 width:  320,
 height: 600,
 backgroundColor:'#332211'
 },

 */

<commit_msg>jshint test001<commit_after>/**
 * Created by zhangpoor on 16/7/21.
 */
import React, { Component, PropTypes } from 'react';
import {
Animated,
    StyleSheet,
    View,
    Text,
    TouchableHighlight
} from 'react-native';

import UIFactory from './UIFactory'
import Item from './Game001/Item'

let _cannonWidth        = 40;
let _cannonHeight       = 60;
let _cannonBgColor      = 'orange';
let _cannonBasicSpeed   = 0.7;

let _enemyWidth         = 34;
let _enemyHeight        = _enemyWidth;
let _enemyBgColor       = 'red';
let _enemySpeed         = 1.1;
let _countOfEnemyPath   = 8;

let _pageHeight         = UIFactory.winHeight - UIFactory.navHeight - UIFactory.tabBarHeight;

function getGap(){

    let _a = UIFactory.winWidth - _enemyWidth * _countOfEnemyPath;
    let _c = _a / 10;

    return _c;
}

let _gap            = getGap();
let _roomSpace      = _gap + _enemyWidth;
let _fireTime       = 20;
let _enemyTimeCount = 800 / _fireTime ;

class MyView extends Component{

    constructor()
    {
        super();

        this.state      = {
            enemyViews:     PropTypes.array
        };

        this.timeCount          = 0;
        this.timer              = null;

        this.enemys             = [];
        this.state.enemyViews   = [];
        this.enemyCount         = this.enemys.length;
        this.lastPathNo         = 0;
        this.cannon             = this.createCannon();
        this.cannonSpeed        = 0;

        this.btnAdd             = UIFactory.createBtn(
            {backgroundColor:'yellow',width:70,height:30,left:210,top:5},
            'red',
            //this.addEnemy.bind(this)
            this.startTimer.bind(this)
        );
        this.btnMove            = UIFactory.createBtn(
            {backgroundColor:'blue',width:70,height:30,left:285,top:5},
            'red',
            this.stopTimer.bind(this)
        );

        this.btnLeft            = UIFactory.createBtn(
            {backgroundColor:'yellow',width:60,height:40,left:0,top:_pageHeight - 40},
            'red',

            this.speedBtnAciotn.bind(this)
        );
        this.btnRight           = UIFactory.createBtn(
            {backgroundColor:'blue',width:60,height:40,left:UIFactory.winWidth - 60,top:_pageHeight - 40},
            'red',
            this.speedBtnAciotn.bind(this)
        );

        //this.createEnemy();

    }

    info(){
        return ('现在敌人数量:'+this.enemyCount+'\n'+'当前屏幕宽度:'+UIFactory.winWidth);
    }

    render() {
        //alert('cannon:'+this.cannon+'\n'+
        //      'cannonView:'+this.cannon.getItemView());
        return (

            <View style={MyViewStyle.RootPageStyle}>
                {this.cannon.getItemView()}
                {this.state.enemyViews}
                <View style={MyViewStyle.InfoBarStyle}>
                    <Text style={MyViewStyle.InfoStyle}>
                        {this.info()}
                    </Text>
                    {this.btnAdd}
                    {this.btnMove}
                </View>
                {this.btnLeft}
                {this.btnRight}
            </View>

        );
    }

    /*
     *  Timer
     *
     */
    startTimer(){

        if(this.timer == null){

            this.timer = setInterval(
                () => this.timeFire(),
                _fireTime
            );
        }

    }

    stopTimer(){

        this.timer && clearInterval(this.timer);

        this.timer = null;
    }

    timeFire(){
        /// do bussiness
        this.enemyBussiness();

        this.moveEnemys();
        this.moveCannon();

        this.setState(this.state);
    }

/*
 *  EnemyBlock
 *
 */
    enemyBussiness(){

        this.timeCount++;
        if(this.timeCount >= _enemyTimeCount)
        {
            this.addEnemy();
            this.timeCount = 0;
        }

    }

    enemyXY(itemId){

        return({

            top:    40,
            left:   _gap + itemId * _roomSpace
        });

    }

    createEnemy(){

        let _pathNo     = Math.ceil(_countOfEnemyPath * Math.random()) - 1;

        var _pathFinal  = _pathNo;
        if(this.lastPathNo == _pathFinal){
            //如果是奇数,中间那个可能会重复
            _pathFinal = _countOfEnemyPath - 1 - _pathFinal;
        }

        this.lastPathNo = _pathFinal;

        var _e = new Item(
            MyViewStyle.EnemyBasicStyle,
            this.enemyXY(_pathFinal)
        );

        this.state.enemyViews.push(_e.view);
        this.enemys.push(_e);
        this.enemyCount = this.enemys.length;

    }

    addEnemy(){

        this.createEnemy();
        //this.setState(this.state);
    }

    moveEnemys() {

        this.state.enemyViews = [];
        var _es = this.enemys;
        this.enemys = [];
        for(var i = 0 ; i < this.enemyCount ;i++){
            var _e = _es[i];
            var _v = _e.moveY(_enemySpeed);

            if(_e.state.mTop < _pageHeight){
                this.enemys.push(_e);
                this.state.enemyViews.push(_v);

            }
        }

        this.enemyCount         = this.enemys.length;

        //this.setState(this.state);
    }

/*
 *  Cannon
 *
 */
    createCannon(){
        var _c = new Item(
            MyViewStyle.CannonBasicStyle,
            {
                left:(UIFactory.winWidth - _cannonWidth)/2.0,
                top:_pageHeight - _cannonHeight - 10,

            }
        );

        return _c;

    }

    moveCannon() {
        let _rxBoundle =  UIFactory.winWidth - this.cannon.mWidth;
        let _lxBoundle =  0;

        this.cannon.moveX(this.cannonSpeed);
        if(this.cannon.state.mLeft > _rxBoundle)
        {
            this.cannon.state.mLeft = _rxBoundle;
            this.cannonSpeed = 0;
        }
        if(this.cannon.state.mLeft < 0)
        {
            this.cannon.state.mLeft = 0;
            this.cannonSpeed = 0;
        }
        //this.setState(this.state);
    }

/*
 *  SpeedButtonAction
 */
    speedBtnAciotn(e){

        adfadfsfasf
        alert(Object.keys(e));
    }

}

const MyViewStyle = StyleSheet.create({
    RootPageStyle:
    {
        position:'absolute',
        width: UIFactory.winWidth,
        height:_pageHeight,
        top: UIFactory.navHeight,
        backgroundColor: 'gray'
    },
    InfoStyle:{
        position:'absolute',
        width: 200,
        height:35,
        top: 0,
        left:0,
        backgroundColor: 'black',
        color:'white',
        fontSize:10
    },
    InfoBarStyle:{
        position:'absolute',
        width: UIFactory.winWidth,
        height:35,
        top: 0,
        left:0,
        backgroundColor: '#218141'
    },
    EnemyBasicStyle:{
        position:'absolute',
        width: _enemyWidth,
        height:_enemyHeight,
        backgroundColor: _enemyBgColor,
        borderRadius:_enemyWidth/2.0

    },
    CannonBasicStyle:{
        position:'absolute',
        width: _cannonWidth,
        height:_cannonHeight,
        backgroundColor: _cannonBgColor

    },

});

export default MyView;

/*

 this.state      = {
 fadeAnim:(new Animated.Value(0)), //设置初始值
 viewAStyle:MyViewStyle.A,
 viewStyle:MyViewStyle.Bg_A
 };

 this.flag       = true;

 this.aaa        = new UIFactory().aFun();
 this.anim=this.anim.bind(this);
 //this.BtnAClick=this.BtnAClick.bind(this);

 this.viewA      = UIFactory.createView(this.state.viewAStyle);
 this.btnA       = UIFactory.createBtn(
 {backgroundColor:'yellow',width:120,height:50,left:100,top:100},
 'red',()=>this.BtnAClick()
 );
 this.aniView    = UIFactory.createAnimatedView(
 {backgroundColor:'pink',width:50,height:50,left:50,top:120},
 this.state.fadeAnim
 );
 anim(p0)
 {

 //console.log('p0:'+p0);
 //alert('p0:'+_abc.ppp);

 Animated.timing(
 this.state.fadeAnim,//初始值
 {
 toValue: p0,    //结束值
 duration:2000   //持续时间
 }
 ).start(

 ()=>this.anim(100 - p0) // fun
 //this.anim(100 - p0)   // void

 );
 }
 {this.eView}
 <View style={[
 MyViewStyle.EnemyBasicStyle,
 {top:this.state.eTop}
 ]} />
 {this.enemyViews}
 <View style={[
 MyViewStyle.EnemyBasicStyle,
 {top:this.state.eTop}]}/>
 {this.state.enemyViews}

 shouldComponentUpdate(nextProps, nextState)
 {
 alert('old'+ this.state.viewASheet);
 alert('next'+ nextState.viewASheet);

 return this.state.viewASheet !== nextState.viewASheet;
 }

 Red: {
 backgroundColor:'red',
 width:  200,
 height: 100
 },
 Brown: {
 backgroundColor:'brown',
 width:  200,
 height: 100
 },
 A: {
 left:10,
 top:10,
 width:  200,
 height: 100,
 backgroundColor:'green'
 },

 Bg_A:{
 left:0,
 marginTop:64,
 width:  320,
 height: 600,
 opacity: 0.5,
 backgroundColor:'#112233'
 },
 Bg_B:{
 width:  320,
 height: 600,
 backgroundColor:'#332211'
 },

 */

<|endoftext|>


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

const expandUriTemplate = require('../../../lib/compile-uri/expand-uri-template');

describe('expandUriTemplate()', () => {
  let data = null;
  let uriTemplate = '';
  let parameters = '';

  before(() => {
    uriTemplate = '/machines{/name}';
    parameters = {
      name: {
        description: 'Machine name',
        type: 'string',
        required: true,
        example: 'waldo',
        default: ''
      }
    };

    data = expandUriTemplate(uriTemplate, parameters);
  });

  it('should return an object', () => assert.isObject(data));

  describe('returned obejct', () => {
    [
      'errors',
      'warnings',
      'uri'
    ].forEach(key =>
      it(`should have key "${key}"`, () => assert.include(Object.keys(data), key))
    );

    describe('when not parseable uri templeate privided', () => {
      before(() => {
        uriTemplate = '/machines{{/name}';
        parameters = {
          name: {
            description: 'Machine name',
            type: 'string',
            required: true,
            example: 'waldo',
            default: ''
          }
        };

        data = expandUriTemplate(uriTemplate, parameters);
      });

      it('it should return some errror', () => assert.notEqual(data.errors.length, 0));
    });

    describe('when "example" is zero', () => {
      before(() => {
        uriTemplate = '/machines{/id}';
        parameters = {
          id: {
            description: 'Machine id',
            type: 'number',
            required: true,
            example: 0
          }
        };

        data = expandUriTemplate(uriTemplate, parameters);
      });

      it('should return expandend URI', () => assert.equal(data.uri, '/machines/0'));
    });

    describe('when "default" is zero', () => {
      before(() => {
        uriTemplate = '/machines{/id}';
        parameters = {
          id: {
            description: 'Machine id',
            type: 'number',
            required: true,
            default: 0
          }
        };

        data = expandUriTemplate(uriTemplate, parameters);
      });

      it('should return expandend URI', () => assert.equal(data.uri, '/machines/0'));
    });

    describe('when URI with no URI template expression given', () => {
      before(() => {
        uriTemplate = '/machines/waldo';
        parameters = {};
        data = expandUriTemplate(uriTemplate, parameters);
      });

      describe('with no parameters given', () => {
        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () => assert.equal(data.warnings.length, 0));

        it('should return URI as it is', () => assert.equal(data.uri, uriTemplate));
      });

      describe('with some parameters given', () => {
        before(() => {
          uriTemplate = '/machines/waldo';
          parameters = {
            name: {
              description: 'Machine name',
              type: 'string',
              required: true,
              example: 'waldo',
              default: ''
            }
          };

          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () =>
          // The warning was removed as parser started to provide its own
          // warning for the very same thing.
          assert.equal(data.warnings.length, 0)
        );

        it('should return URI as it is', () => assert.equal(data.uri, uriTemplate));
      });
    });

    describe('when UriTemplate with some URI template expression given', () => {
      describe('when no matching parameters provided', () => {
        before(() => {
          uriTemplate = '/machines/{name}';
          parameters = {};
          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return some warning', () => assert.notEqual(data.warnings.length, 0));

        describe('returned warning', () => {
          let warning = '';
          before(() => { warning = data.warnings[data.warnings.length - 1]; });

          it('should contain proper text', () => {
            const text = 'Parameter not defined';
            assert.include(warning, text);
          });
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no URI', () => assert.equal(data.uri, null));
      });

      describe('with defined some parameters not matching any expression', () => {
        before(() => {
          uriTemplate = '/machines/{name}';
          parameters = {
            name: {
              description: 'Machine name',
              type: 'string',
              required: true,
              example: 'waldo',
              default: ''
            },
            fanny: {
              description: 'Machine fanny',
              type: 'string',
              required: true,
              example: 'wild',
              default: ''
            }
          };

          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () =>
          // The warning was removed as parser started to provide its own
          // warning for the very same thing.
          assert.equal(data.warnings.length, 0)
        );

        it('should return expandend URI', () => assert.equal(data.uri, '/machines/waldo'));
      });

      describe('when expression parameter is required', () => {
        describe('when example is not given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: '',
                default: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return some warning', () => assert.equal(data.warnings.length, 1));

          it('should return no URI', () => assert.isNull(data.uri));

          describe('returned warning', () => {
            let warning = '';
            before(() => { warning = data.warnings[data.warnings.length - 1]; });

            it('should contain proper text', () => {
              const text = 'No example value for required parameter';
              assert.include(warning, text);
            });
          });
        });

        describe('when example value is given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: 'example-one',
                default: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

          it('should return URI', () => assert.isNotNull(data.uri));
        });

        describe('when default value is given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: '',
                default: 'example-one'
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return one warning', () => assert.equal(data.warnings.length, 1));

          it('should return warning about pointlessness of default value of a required parameter', () => assert.include(data.warnings[0], 'Default value for a required parameter'));

          it('should use default value to URI parameter expansion', () => assert.include(data.uri, parameters.name.default));

          it('should return URI', () => assert.isNotNull(data.uri));
        });

        describe('when example and default values are given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: 'example-one',
                default: 'default-one'
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return one warning', () => assert.equal(data.warnings.length, 1));

          it('should return warning about pointlessness of default value of a required parameter', () => assert.include(data.warnings[0], 'Default value for a required parameter'));

          it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

          it('should return URI', () => assert.isNotNull(data.uri));
        });
      });

      describe('when expression parameter is optional', () => {
        before(() => {
          uriTemplate = '/machines/{name}';
          parameters = {
            name: {
              description: 'Machine name',
              type: 'string',
              required: false,
              example: 'example-one',
              default: ''
            }
          };

          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () => assert.equal(data.warnings.length, 0));

        it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

        it('should return URI', () => assert.isNotNull(data.uri));

        describe('when default value is given and example is empty', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: false,
                default: 'default-one',
                example: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should use default value to URI parameter expansion', () => assert.include(data.uri, parameters.name.default));

          it('should return URI', () => assert.isNotNull(data.uri));
        });

        describe('when example and default values are given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: false,
                example: 'example-one',
                default: 'default-one'
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

          it('should return some URI', () => assert.isNotNull(data.uri));
        });

        describe('when example and default values are not given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: false,
                default: '',
                example: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should return some URI', () => assert.isNotNull(data.uri));
        });
      });
    });
  });
});
<commit_msg>style: prevent eslint --fix from crashing on the codebase<commit_after>const { assert } = require('chai');

const expandUriTemplate = require('../../../lib/compile-uri/expand-uri-template');

describe('expandUriTemplate()', () => {
  let data = null;
  let uriTemplate = '';
  let parameters = '';

  before(() => {
    uriTemplate = '/machines{/name}';
    parameters = {
      name: {
        description: 'Machine name',
        type: 'string',
        required: true,
        example: 'waldo',
        default: ''
      }
    };

    data = expandUriTemplate(uriTemplate, parameters);
  });

  it('should return an object', () => assert.isObject(data));

  describe('returned obejct', () => {
    [
      'errors',
      'warnings',
      'uri'
    ].forEach(key =>
      it(`should have key "${key}"`, () => assert.include(Object.keys(data), key))
    );

    describe('when not parseable uri templeate privided', () => {
      before(() => {
        uriTemplate = '/machines{{/name}';
        parameters = {
          name: {
            description: 'Machine name',
            type: 'string',
            required: true,
            example: 'waldo',
            default: ''
          }
        };

        data = expandUriTemplate(uriTemplate, parameters);
      });

      it('it should return some errror', () => assert.notEqual(data.errors.length, 0));
    });

    describe('when "example" is zero', () => {
      before(() => {
        uriTemplate = '/machines{/id}';
        parameters = {
          id: {
            description: 'Machine id',
            type: 'number',
            required: true,
            example: 0
          }
        };

        data = expandUriTemplate(uriTemplate, parameters);
      });

      it('should return expandend URI', () => assert.equal(data.uri, '/machines/0'));
    });

    describe('when "default" is zero', () => {
      before(() => {
        uriTemplate = '/machines{/id}';
        parameters = {
          id: {
            description: 'Machine id',
            type: 'number',
            required: true,
            default: 0
          }
        };

        data = expandUriTemplate(uriTemplate, parameters);
      });

      it('should return expandend URI', () => assert.equal(data.uri, '/machines/0'));
    });

    describe('when URI with no URI template expression given', () => {
      before(() => {
        uriTemplate = '/machines/waldo';
        parameters = {};
        data = expandUriTemplate(uriTemplate, parameters);
      });

      describe('with no parameters given', () => {
        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () => assert.equal(data.warnings.length, 0));

        it('should return URI as it is', () => assert.equal(data.uri, uriTemplate));
      });

      describe('with some parameters given', () => {
        before(() => {
          uriTemplate = '/machines/waldo';
          parameters = {
            name: {
              description: 'Machine name',
              type: 'string',
              required: true,
              example: 'waldo',
              default: ''
            }
          };

          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () => {
          // The warning was removed as parser started to provide its own
          // warning for the very same thing.
          assert.equal(data.warnings.length, 0);
        });

        it('should return URI as it is', () => assert.equal(data.uri, uriTemplate));
      });
    });

    describe('when UriTemplate with some URI template expression given', () => {
      describe('when no matching parameters provided', () => {
        before(() => {
          uriTemplate = '/machines/{name}';
          parameters = {};
          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return some warning', () => assert.notEqual(data.warnings.length, 0));

        describe('returned warning', () => {
          let warning = '';
          before(() => { warning = data.warnings[data.warnings.length - 1]; });

          it('should contain proper text', () => {
            const text = 'Parameter not defined';
            assert.include(warning, text);
          });
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no URI', () => assert.equal(data.uri, null));
      });

      describe('with defined some parameters not matching any expression', () => {
        before(() => {
          uriTemplate = '/machines/{name}';
          parameters = {
            name: {
              description: 'Machine name',
              type: 'string',
              required: true,
              example: 'waldo',
              default: ''
            },
            fanny: {
              description: 'Machine fanny',
              type: 'string',
              required: true,
              example: 'wild',
              default: ''
            }
          };

          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () => {
          // The warning was removed as parser started to provide its own
          // warning for the very same thing.
          assert.equal(data.warnings.length, 0);
        });

        it('should return expandend URI', () => assert.equal(data.uri, '/machines/waldo'));
      });

      describe('when expression parameter is required', () => {
        describe('when example is not given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: '',
                default: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return some warning', () => assert.equal(data.warnings.length, 1));

          it('should return no URI', () => assert.isNull(data.uri));

          describe('returned warning', () => {
            let warning = '';
            before(() => { warning = data.warnings[data.warnings.length - 1]; });

            it('should contain proper text', () => {
              const text = 'No example value for required parameter';
              assert.include(warning, text);
            });
          });
        });

        describe('when example value is given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: 'example-one',
                default: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

          it('should return URI', () => assert.isNotNull(data.uri));
        });

        describe('when default value is given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: '',
                default: 'example-one'
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return one warning', () => assert.equal(data.warnings.length, 1));

          it('should return warning about pointlessness of default value of a required parameter', () => assert.include(data.warnings[0], 'Default value for a required parameter'));

          it('should use default value to URI parameter expansion', () => assert.include(data.uri, parameters.name.default));

          it('should return URI', () => assert.isNotNull(data.uri));
        });

        describe('when example and default values are given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: true,
                example: 'example-one',
                default: 'default-one'
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return one warning', () => assert.equal(data.warnings.length, 1));

          it('should return warning about pointlessness of default value of a required parameter', () => assert.include(data.warnings[0], 'Default value for a required parameter'));

          it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

          it('should return URI', () => assert.isNotNull(data.uri));
        });
      });

      describe('when expression parameter is optional', () => {
        before(() => {
          uriTemplate = '/machines/{name}';
          parameters = {
            name: {
              description: 'Machine name',
              type: 'string',
              required: false,
              example: 'example-one',
              default: ''
            }
          };

          data = expandUriTemplate(uriTemplate, parameters);
        });

        it('should return no error', () => assert.equal(data.errors.length, 0));

        it('should return no warning', () => assert.equal(data.warnings.length, 0));

        it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

        it('should return URI', () => assert.isNotNull(data.uri));

        describe('when default value is given and example is empty', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: false,
                default: 'default-one',
                example: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should use default value to URI parameter expansion', () => assert.include(data.uri, parameters.name.default));

          it('should return URI', () => assert.isNotNull(data.uri));
        });

        describe('when example and default values are given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: false,
                example: 'example-one',
                default: 'default-one'
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should use example value to URI parameter expansion', () => assert.include(data.uri, parameters.name.example));

          it('should return some URI', () => assert.isNotNull(data.uri));
        });

        describe('when example and default values are not given', () => {
          before(() => {
            uriTemplate = '/machines/{name}';
            parameters = {
              name: {
                description: 'Machine name',
                type: 'string',
                required: false,
                default: '',
                example: ''
              }
            };

            data = expandUriTemplate(uriTemplate, parameters);
          });

          it('should return no error', () => assert.equal(data.errors.length, 0));

          it('should return no warning', () => assert.equal(data.warnings.length, 0));

          it('should return some URI', () => assert.isNotNull(data.uri));
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

const { expect } = require('chai');
const { execSync } = require('child_process');
const { createMonth } = require('../lib/months.js');

describe('cal', () => {
  describe('CLI', () => {
    it('should handle the current month', () => {
      // const month = require('../lib/months.js');
     let goal = execSync('cal').toString();
     let actual = execSync('./cal.js').toString();
      expect(actual).to.equal(goal);
    });
     it('should handle jan 1999', () => {
     let goal = execSync('cal 1 1999').toString();
     let actual = execSync('./cal.js 1 1999').toString();
      expect(actual).to.equal(goal);
    });
    //  it('should handle april 1800', () => {
    //  let goal = execSync('cal 4 1800').toString();
    //  let actual = execSync('./cal.js 4 1800').toString();
    //   expect(actual).to.equal(goal);
    // });
     //it('should handle all the months in a year', () => {
       //let goal = execSync('cal 2012').toString();
      //expect(year.grabYear(2012)).to.equal(goal);
     //});

  });

  describe("Zeller's congruence", () => {
    var zellers = require('../lib/zellers.js');
     //const zellers = require('../lib/zellers.js');

    describe('.modifiedMonth', () => {
      it('return 13 for January', () => {
        expect(zellers.modifiedMonth(1)).to.equal(13);
      });
      it('return 2 for February', () =>{
        expect(zellers.modifiedMonth(2)).to.equal(14);
      });
       it('return 3 for March', () =>{
        expect(zellers.modifiedMonth(3)).to.equal(3);
      });
    });

    describe('.modifiedYear', () => {
      it('returns 2015 for Jan 2015', () => {
        expect(zellers.modifiedYear(2015, 1)).to.equal(2014);
      });
      it('returns 2015 for Feb 2016', () => {
        expect(zellers.modifiedYear(2016, 2)).to.equal(2015);
      });
      it('returns 2017 for Mar 2017', () => {
        expect(zellers.modifiedYear(2017, 3)).to.equal(2017);
      });
    });

    describe('.getDay', () => {
      it('returns 5 (Friday) for Jan 1, 2016', () => {
        expect(zellers.getDay(2016, 1, 1)).to.equal(5);
      });
      it('returns 2 (Tuesday) for March 1, 2016', () => {
        expect(zellers.getDay(2016, 3, 1)).to.equal(2);
      });
      it('returns 3 (Wed) for March 1, 2000', () => {
        expect(zellers.getDay(2000, 3, 1)).to.equal(3);
      });
      it('returns 1 (Mon) for March 1, 2100', () => {
        expect(zellers.getDay(2100, 3, 1)).to.equal(1);
      });
      it('returns 0 (Sunday) for March 2, 2200', () => {
        expect(zellers.getDay(2200, 3, 2)).to.equal(0);
      });
      it('returns 4 (Thurs) for March 1, 2300', () => {
        expect(zellers.getDay(2300, 3, 1)).to.equal(4);
      });
    });
  });
});

  describe('months.js', () => {
    const {makeMonth, checkLeapYear, firstLine, secondLine, numberOfLines} = require('../lib/months.js');

    it('should create top line for month and year', () => {
      expect(firstLine(1, 2016)).to.equal("    January 2016");
      });
    it('should create second line', () => {
      expect(secondLine()).to.equal('Su Mo Tu We Th Fr Sa');
      });

    // it("should print the days relative to 20 spaces", ()=>{
    //   expect(makeMonth(3, 2016)).to.equal("       1  2  3  4  5 \n 6  7  8  9 10 11 12 \n13 14 15 16 17 18 19 \n20 21 22 23 24 25 26 \n27 28 29 30");
    // });

     //it('should print a full calendar', () => {
       //expect(makeMonth(3, 2016)).to.equal("    March 2016\nSu Mo Tu We Th Fr Sa\n       1  2  3  4  5 \n 6  7  8  9 10 11 12 \n13 14 15 16 17 18 19 \n20 21 22 23 24 25 26 \n27 28 29 30");
     //});

    describe('leap year', () => {
      it('checks to see if Feb 2012 is a leap year', () =>{
        expect(checkLeapYear(2012, 2)).to.equal(true);
      });
      it('checks to see if Feb 2014 is a leap year',() => {
        expect(checkLeapYear(2014, 2)).to.equal(false);
      });
    });

    //describe('30 day or 31 day' () => {
      //it('checks to see if Nov 2015 has 30 days', (){
        //expect(cal.finalCalDays(2015, 11)).to.equal(30);
    //});
      //it('checks to see if Dec 2015 has 31 days', (){
        //expect(numberOfDays(2015,12)).to.equal(31);
      //});
    //});

    //describe('number of weeks in month'() => {
      //it('checks number of weeks in Feb 2015', (){
        //expect(numberOfWeeks(2015, 2)).to.equal(4);
      //});
     //it('checks number of weeks in Oct 2015', (){
        //expect(numberOfWeeks(2015, 10)).to.equal(5);
      //});
     //it('checks number of weeks in August 2015', (){
        //expect(numberOfWeeks(2015, 8)).to.equal(6);
      //});

    });

<commit_msg>refactored code and added tests for number of lines<commit_after>'use strict';

const { expect } = require('chai');
const { execSync } = require('child_process');
const { createMonth } = require('../lib/months.js');

describe('cal', () => {
  describe('CLI', () => {
    it('should handle the current month', () => {
      // const month = require('../lib/months.js');
     let goal = execSync('cal').toString();
     let actual = execSync('./cal.js').toString();
      expect(actual).to.equal(goal);
    });
     it('should handle jan 1999', () => {
     let goal = execSync('cal 1 1999').toString();
     let actual = execSync('./cal.js 1 1999').toString();
      expect(actual).to.equal(goal);
    });
     it('should handle april 1800', () => {
     let goal = execSync('cal 4 1800').toString();
     let actual = execSync('./cal.js 4 1800').toString();
      expect(actual).to.equal(goal);
    });
     //it('should handle all the months in a year', () => {
       //let goal = execSync('cal 2012').toString();
      //expect(year.grabYear(2012)).to.equal(goal);
     //});

  });
  describe('Correct number of lines', () => {
     it('should handle aug 2015, a six week month ', () => {
     let goal = execSync('cal 8 2015').toString();
     let actual = execSync('./cal.js 8 2015').toString();
      expect(actual).to.equal(goal);
    });
     it('should handle october 2015, a 5 week month', () => {
      let goal = execSync('cal 10 2015').toString();
      let actual = execSync('./cal.js 10 2015').toString();
      expect(actual).to.equal(goal);
    });
     it('should handle feb 2015, a 4 week month', () => {
      let goal = execSync('cal 2 2015').toString();
      let actual = execSync('./cal.js 2 2015').toString();
      expect(actual).to.equal(goal);
    });
  });

  describe('months.js', () => {
    const {makeMonth, checkLeapYear, firstLine, secondLine, numberOfLines} = require('../lib/months.js');

    it('should create top line for month and year', () => {
      expect(firstLine(1, 2016)).to.equal("    January 2016");
      });
    it('should create second line', () => {
      expect(secondLine()).to.equal('Su Mo Tu We Th Fr Sa');
      });

    describe('leap year', () => {
      it('checks to see if Feb 2012 is a leap year', () =>{
        expect(checkLeapYear(2012, 2)).to.equal(true);
      });
      it('checks to see if Feb 2014 is a leap year',() => {
        expect(checkLeapYear(2014, 2)).to.equal(false);
      });
    });
  });
  describe("Zeller's congruence", () => {
    var zellers = require('../lib/zellers.js');
     //const zellers = require('../lib/zellers.js');

    describe('.modifiedMonth', () => {
      it('return 13 for January', () => {
        expect(zellers.modifiedMonth(1)).to.equal(13);
      });
      it('return 2 for February', () =>{
        expect(zellers.modifiedMonth(2)).to.equal(14);
      });
       it('return 3 for March', () =>{
        expect(zellers.modifiedMonth(3)).to.equal(3);
      });
    });

    describe('.modifiedYear', () => {
      it('returns 2015 for Jan 2015', () => {
        expect(zellers.modifiedYear(2015, 1)).to.equal(2014);
      });
      it('returns 2015 for Feb 2016', () => {
        expect(zellers.modifiedYear(2016, 2)).to.equal(2015);
      });
      it('returns 2017 for Mar 2017', () => {
        expect(zellers.modifiedYear(2017, 3)).to.equal(2017);
      });
    });

    describe('.getDay', () => {
      it('returns 5 (Friday) for Jan 1, 2016', () => {
        expect(zellers.getDay(2016, 1, 1)).to.equal(5);
      });
      it('returns 2 (Tuesday) for March 1, 2016', () => {
        expect(zellers.getDay(2016, 3, 1)).to.equal(2);
      });
      it('returns 3 (Wed) for March 1, 2000', () => {
        expect(zellers.getDay(2000, 3, 1)).to.equal(3);
      });
      it('returns 1 (Mon) for March 1, 2100', () => {
        expect(zellers.getDay(2100, 3, 1)).to.equal(1);
      });
      it('returns 0 (Sunday) for March 2, 2200', () => {
        expect(zellers.getDay(2200, 3, 2)).to.equal(0);
      });
      it('returns 4 (Thurs) for March 1, 2300', () => {
        expect(zellers.getDay(2300, 3, 1)).to.equal(4);
      });
    });
  });
});

    //describe('30 day or 31 day' () => {
      //it('checks to see if Nov 2015 has 30 days', (){
        //expect(cal.finalCalDays(2015, 11)).to.equal(30);
    //});
      //it('checks to see if Dec 2015 has 31 days', (){
        //expect(numberOfDays(2015,12)).to.equal(31);
      //});
    //});

<|endoftext|>


<commit_before>var session     = require("./lib/session-handler");
var user        = require("./routes/userController.js");

var redirectAuth = function(req,res, next) {
	if(! (req.body.token || req.query.token || req.headers['x-access-token'])  )
		return next()

	res.status(403);
	res.json({ "error": "Forbidden Request"  });
}

module.exports = function(express, app) {

	// =============================================
	// ========== INDEX ROUTER =====================
	// =============================================

	var indexRouter = express.Router();

	indexRouter.get('/ping', function(req,res) {
		res.send({
			status: "success",
			msg   : "pong"
		});
	});

	app.use('/', indexRouter);

	// =============================================
	// ========== USER ROUTER =====================
	// =============================================

	var userRouter = express.Router();

	userRouter.get('/', session.isAuthenticated, user.getUserDetails);

	app.use('/user', userRouter);

}

<commit_msg>Updated Router<commit_after>var session     = require("./lib/session-handler");
var user        = require("./routes/userController.js");

var redirectAuth = function(req,res, next) {
	if(! (req.body.token || req.query.token || req.headers['x-access-token'])  )
		return next()

	res.status(403);
	res.json({ "error": "Forbidden Request"  });
}

module.exports = function(express, app) {

	// =============================================
	// ========== INDEX ROUTER =====================
	// =============================================

	var indexRouter = express.Router();

	indexRouter.get('/ping', function(req,res) {
		res.send({
			status: "success",
			msg   : "pong"
		});
	});

	app.use('/', indexRouter);

	// =============================================
	// ========== USER ROUTER =====================
	// =============================================

	var userRouter = express.Router();

	userRouter.get('/', session.isAuthenticated);
	//userRouter.post('/create');

	app.use('/user', userRouter);

}

<|endoftext|>


<commit_before>export default {
  color: 0x243465,
  darkerColor: 0x121a32,
  density: 0.0015
};<commit_msg>Experience - Adjust fog density<commit_after>export default {
  color: 0x243465,
  darkerColor: 0x121a32,
  density: 0.0012
};<|endoftext|>


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

/**
 * @fileoverview
 * Determine if a file (string) is a font by its extension
 */

const fontExtensions = [
  '###',
  '#gf',
  '$on',
  '$tf',
  '0b',
  '8m',
  '8u',
  '12u',
  '15u',
  '64c',
  '075',
  '75',
  '085',
  '85',
  '91',
  '091',
  '096',
  '96',
  'abf',
  'acfm',
  'acs',
  'afm',
  'afn',
  'afs',
  'all',
  'amfm',
  'apf',
  'asf',
  'aspf',
  'atm',
  'auf',
  'b30',
  'bco',
  'bdf',
  'bepf',
  'bez',
  'bfn',
  'bmap',
  'bmf',
  'bx',
  'bzr',
  'cbtf',
  'cct',
  'cef',
  'cff',
  'cfn',
  'cga',
  'ch4',
  'cha',
  'chm',
  'chr',
  'chx',
  'claf',
  'collection',
  'compositefont',
  'dfont',
  'dus',
  'dzk',
  'eft',
  'eot',
  'etx',
  'euf',
  'f00',
  'f06',
  'f08',
  'f09',
  'f3f',
  'f10',
  'f11',
  'f12',
  'f13',
  'f16',
  'fd',
  'fdb',
  'ff',
  'ffil',
  'flf',
  'fli',
  'fn3',
  'fnb',
  'fnn',
  'fnt',
  'fnta',
  'fo1',
  'fo2',
  'fog',
  'fon',
  'font',
  'fonts',
  'fot',
  'frf',
  'frs',
  'ftm',
  'fxr',
  'fyi',
  'gdr',
  'gf',
  'gft',
  'glf',
  'glif',
  'glyphs',
  'gsf',
  'gxf',
  'hbf',
  'ice',
  'intellifont',
  'lepf',
  'lft',
  'lwfn',
  'mcf',
  'mcf',
  'mfd',
  'mfm',
  'mft',
  'mgf',
  'mmm',
  'mrf',
  'mtf',
  'mvec',
  'nlq',
  'ntf',
  'odttf',
  'ofm',
  'okf',
  'otf',
  'pcf',
  'pcf',
  'pfa',
  'pfb',
  'pfm',
  'pft',
  'phf',
  'pk',
  'pkt',
  'prs',
  'pss',
  'qbf',
  'qfn',
  'r8?',
  'scr',
  'sfd',
  'sff',
  'sfi',
  'sfl',
  'sfn',
  'sfo',
  'sfp',
  'sfs',
  'sif',
  'snf',
  'spd',
  'spritefont',
  'sui',
  'suit',
  'svg',
  'sxs',
  't1c',
  't2',
  'tb1',
  'tb2',
  'tdf',
  'tfm',
  'tmf',
  'tpf',
  'ttc',
  'tte',
  'ttf',
  'type',
  'ufm',
  'ufo',
  'usl',
  'usp',
  'us?',
  'vf',
  'vf1',
  'vf3',
  'vfb',
  'vfm',
  'vfont',
  'vlw',
  'vmf',
  'vnf',
  'w30',
  'wfn',
  'wnf',
  'woff',
  'woff2',
  'xfc',
  'xfn',
  'xfr',
  'xft',
  'zfi',
  'zsu',
  '_v',
];

const exports = {
  isPathNameAFont: (filePath) => {
    return fontExtensions.some((extension) => {
      if (filePath.endsWith(extension)) {
        return true;
      }
      return false;
    });
  },
};

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

/**
 * @fileoverview
 * Determine if a file (string) is a font by its extension
 */

const fontExtensions = [
  '###',
  '#gf',
  '$on',
  '$tf',
  '0b',
  '8m',
  '8u',
  '12u',
  '15u',
  '64c',
  '075',
  '75',
  '085',
  '85',
  '91',
  '091',
  '096',
  '96',
  'abf',
  'acfm',
  'acs',
  'afm',
  'afn',
  'afs',
  'all',
  'amfm',
  'apf',
  'asf',
  'aspf',
  'atm',
  'auf',
  'b30',
  'bco',
  'bdf',
  'bepf',
  'bez',
  'bfn',
  'bmap',
  'bmf',
  'bx',
  'bzr',
  'cbtf',
  'cct',
  'cef',
  'cff',
  'cfn',
  'cga',
  'ch4',
  'cha',
  'chm',
  'chr',
  'chx',
  'claf',
  'collection',
  'compositefont',
  'dfont',
  'dus',
  'dzk',
  'eft',
  'eot',
  'etx',
  'euf',
  'f00',
  'f06',
  'f08',
  'f09',
  'f3f',
  'f10',
  'f11',
  'f12',
  'f13',
  'f16',
  'fd',
  'fdb',
  'ff',
  'ffil',
  'flf',
  'fli',
  'fn3',
  'fnb',
  'fnn',
  'fnt',
  'fnta',
  'fo1',
  'fo2',
  'fog',
  'fon',
  'font',
  'fonts',
  'fot',
  'frf',
  'frs',
  'ftm',
  'fxr',
  'fyi',
  'gdr',
  'gf',
  'gft',
  'glf',
  'glif',
  'glyphs',
  'gsf',
  'gxf',
  'hbf',
  'ice',
  'intellifont',
  'lepf',
  'lft',
  'lwfn',
  'mcf',
  'mcf',
  'mfd',
  'mfm',
  'mft',
  'mgf',
  'mmm',
  'mrf',
  'mtf',
  'mvec',
  'nlq',
  'ntf',
  'odttf',
  'ofm',
  'okf',
  'otf',
  'pcf',
  'pcf',
  'pfa',
  'pfb',
  'pfm',
  'pft',
  'phf',
  'pk',
  'pkt',
  'prs',
  'pss',
  'qbf',
  'qfn',
  'r8?',
  'scr',
  'sfd',
  'sff',
  'sfi',
  'sfl',
  'sfn',
  'sfo',
  'sfp',
  'sfs',
  'sif',
  'snf',
  'spd',
  'spritefont',
  'sui',
  'suit',
  'svg',
  'sxs',
  't1c',
  't2',
  'tb1',
  'tb2',
  'tdf',
  'tfm',
  'tmf',
  'tpf',
  'ttc',
  'tte',
  'ttf',
  'type',
  'ufm',
  'ufo',
  'usl',
  'usp',
  'us?',
  'vf',
  'vf1',
  'vf3',
  'vfb',
  'vfm',
  'vfont',
  'vlw',
  'vmf',
  'vnf',
  'w30',
  'wfn',
  'wnf',
  'woff',
  'woff2',
  'xfc',
  'xfn',
  'xfr',
  'xft',
  'zfi',
  'zsu',
  '_v',
];

const exports = {
  isPathNameAFont: (filePath) => {
    return fontExtensions.some((extension) => {
      if (filePath.endsWith(`.${extension}`)) {
        return true;
      }
      return false;
    });
  },
};

export default exports;
<|endoftext|>


<commit_before>'use strict';

function create_gates(new_gates){
    new_gates = new_gates || [{}];
    for(var gate in new_gates){
        gates.push({
          'color': new_gates[gate]['color'] || '#fff',
          'destroy': new_gates[gate]['destroy'] !== void 0
            ? new_gates[gate]['destroy']
            : false,
          'dx': new_gates[gate]['dx'] || false,
          'dy': new_gates[gate]['dy'] || false,
          'event': new_gates[gate]['event'] || function(){},
          'height': new_gates[gate]['height'] || 40,
          'interval': new_gates[gate]['interval'] || 0,
          'x': x + new_gates[gate]['x'] || x,
          'y': y + new_gates[gate]['y'] || y,
          'width': new_gates[gate]['width'] || 40,
        });
    }
}

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    buffer.save();
    buffer.translate(
      -camera_x,
      -camera_y
    );

    // Draw gates.
    for(var gate in gates){
        buffer.fillStyle = gates[gate]['color'];
        buffer.fillRect(
          gates[gate]['x'],
          gates[gate]['y'],
          gates[gate]['width'],
          gates[gate]['height']
       );
    }

    // Draw particles.
    buffer.fillStyle = '#fff';
    for(var particle in particles){
        buffer.fillRect(
          particles[particle]['x'],
          particles[particle]['y'],
          5,
          5
        );
    };

    buffer.restore();

    buffer.fillStyle = '#fff';
    // Draw camera position.
    buffer.fillText(
      camera_x + 'x ' + camera_y + 'y',
      5,
      25
    );

    // Draw number of particles
    //   and max-particles.
    buffer.fillText(
      particles.length
        + ' / '
        + settings['max-particles'],
      5,
      50
    );

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    animationFrame = window.requestAnimationFrame(draw);
}

function logic(){
    if(key_left){
        camera_x -= settings['scroll-speed'];
    }

    if(key_right){
        camera_x += settings['scroll-speed'];
    }

    if(key_down){
        camera_y += settings['scroll-speed'];
    }

    if(key_up){
        camera_y -= settings['scroll-speed'];
    }

    frame_counter += 1;
    if(frame_counter > 99){
        frame_counter = 0;
    }

    for(var particle in particles){
        particles[particle]['x'] += particles[particle]['dx'];
        particles[particle]['y'] += particles[particle]['dy'];

        if(particles[particle]['x'] > boundaries['right']
          || particles[particle]['x'] < boundaries['left']
          || particles[particle]['y'] > boundaries['bottom']
          || particles[particle]['y'] < boundaries['top']){
            particles.splice(
              particle,
              1
            );
        }
    }

    for(var gate in gates){
        if(gates[gate]['interval'] > 0
          && frame_counter % gates[gate]['interval'] === 0){
            gates[gate]['event']();
        }

        for(var particle in particles){
            if(particles[particle]['x'] > gates[gate]['x']
              && particles[particle]['x'] < gates[gate]['x'] + gates[gate]['width']
              && particles[particle]['y'] > gates[gate]['y']
              && particles[particle]['y'] < gates[gate]['y'] + gates[gate]['height']){
                if(gates[gate]['destroy']){
                    particles.splice(
                      particle,
                      1
                    );
                    continue;
                }

                if(gates[gate]['dx'] !== false){
                    particles[particle]['dx'] = gates[gate]['dx'];
                }
                if(gates[gate]['dy'] !== false){
                    particles[particle]['dy'] = gates[gate]['dy'];
                }
            }
        }
    }
}

function play_audio(id){
    if(settings['audio-volume'] <= 0){
        return;
    }

    document.getElementById(id).currentTime = 0;
    document.getElementById(id).play();
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    document.getElementById('audio-volume').value = 1;
    document.getElementById('movement-keys').value = 'WASD';
    document.getElementById('max-particles').value = 1000;
    document.getElementById('ms-per-frame').value = 25;
    document.getElementById('reset-camera-key').value = 'H';
    document.getElementById('scroll-speed').value = 5;

    save();
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

    buffer.font = '23pt sans-serif';
}

// Save settings into window.localStorage if they differ from default.
function save(){
    var ids = {
      'audio-volume': 1,
      'max-particles': 1000,
      'ms-per-frame': 25,
      'scroll-speed': 5,
    };
    for(var id in ids){
        var value = document.getElementById(id).value;
        if(value == ids[id]
          || isNaN(value)){
            window.localStorage.removeItem('ParticleRun-2D.htm-' + id);
            settings[id] = ids[id];

        }else{
            settings[id] = parseFloat(value);
            window.localStorage.setItem(
              'ParticleRun-2D.htm-' + id,
              settings[id]
            );
        }
    }

    ids = {
      'movement-keys': 'WASD',
      'reset-camera-key': 'H',
    };
    for(id in ids){
        value = document.getElementById(id).value;
        if(value === ids[id]){
            window.localStorage.removeItem('ParticleRun-2D.htm-' + id);
            settings[id] = ids[id];

        }else{
            settings[id] = value;
            window.localStorage.setItem(
              'ParticleRun-2D.htm-' + id,
              settings[id]
            );
        }
    }
}

function setmode(newmode, newgame){
    window.cancelAnimationFrame(animationFrame);
    window.clearInterval(interval);

    gates = [];
    particles = [];

    mode = newmode;

    // New game mode.
    if(mode > 0){
        // If it's a newgame from the main menu, save settings.
        if(newgame){
            save();
        }

        // Reset.
        camera_x = 0;
        camera_y = 0;
        frame_counter = 0;
        key_left = false;
        key_right = false;

        // If it's a newgame from the main menu, setup canvas and buffers.
        if(newgame){
            document.body.innerHTML =
              '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

            var contextAttributes = {
              'alpha': false,
            };
            buffer = document.getElementById('buffer').getContext(
              '2d',
              contextAttributes
            );
            canvas = document.getElementById('canvas').getContext(
              '2d',
              contextAttributes
            );

            resize();
        }

        load_level(mode);

        animationFrame = window.requestAnimationFrame(draw);
        interval = window.setInterval(
          'logic()',
          settings['ms-per-frame']
        );

        return;
    }

    // Main menu mode.
    buffer = 0;
    canvas = 0;

    document.body.innerHTML = '

Test Level

<input disabled value=ESC>Main Menu
<input id=movement-keys maxlength=4 value='
      + settings['movement-keys'] + '>Camera ↑←↓→
<input id=reset-camera-key maxlength=1 value='
      + settings['reset-camera-key'] + '>Reset Camera

<input id=audio-volume max=1 min=0 step=0.01 type=range value='
      + settings['audio-volume'] + '>Audio
<input id=max-particles value='
      + settings['max-particles'] + '>Max Particles
<input id=ms-per-frame value='
      + settings['ms-per-frame'] + '>ms/Frame
<input id=scroll-speed value='
      + settings['scroll-speed'] + '>Scroll Speed
Reset Settings

';
}

var animationFrame = 0;
var boundaries = {};
var buffer = 0;
var camera_x = 0;
var camera_y = 0;
var canvas = 0;
var drag = false;
var drag_x = 0;
var drag_y = 0;
var frame_counter = 0;
var gates = [];
var height = 0;
var interval = 0;
var key_down = false;
var key_left = false;
var key_right = false;
var key_up = false;
var mode = 0;
var particles = [];
var settings = {
  'audio-volume': window.localStorage.getItem('ParticleRun-2D.htm-audio-volume') !== null
    ? parseFloat(window.localStorage.getItem('ParticleRun-2D.htm-audio-volume'))
    : 1,
  'movement-keys': window.localStorage.getItem('ParticleRun-2D.htm-movement-keys') || 'WASD',
  'max-particles': parseInt(window.localStorage.getItem('ParticleRun-2D.htm-max-particles')) || 1000,
  'ms-per-frame': parseInt(window.localStorage.getItem('ParticleRun-2D.htm-ms-per-frame')) || 25,
  'reset-camera-key': window.localStorage.getItem('ParticleRun-2D.htm-reset-camera-key') || 'H',
  'scroll-speed': window.localStorage.getItem('ParticleRun-2D.htm-scroll-speed') || 5,
};
var x = 0;
var width = 0;
var y = 0;

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // ESC: return to main menu.
    if(key === 27){
        setmode(
          0,
          true
        );
        return;
    }

    key = String.fromCharCode(key);

    if(key === settings['movement-keys'][0]){
        key_up = true;

    }else if(key === settings['movement-keys'][1]){
        key_left = true;

    }else if(key === settings['movement-keys'][2]){
        key_down = true;

    }else if(key === settings['movement-keys'][3]){
        key_right = true;

    }else if(key === settings['reset-camera-key']){
        camera_x = 0;
        camera_y = 0;
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === settings['movement-keys'][0]){
        key_up = false;

    }else if(key === settings['movement-keys'][1]){
        key_left = false;

    }else if(key === settings['movement-keys'][2]){
        key_down = false;

    }else if(key === settings['movement-keys'][3]){
        key_right = false;
    }
};

window.onload = function(e){
    setmode(
      0,
      true
    );
};

window.onmousedown =
  window.ontouchstart = function(e){
    drag = true;
    drag_x = e.pageX;
    drag_y = e.pageY;
};

window.onmousemove =
  window.ontouchmove = function(e){
    if(!drag){
        return;
    }

    camera_x += drag_x - e.pageX;
    camera_y += drag_y - e.pageY;
    drag_x = e.pageX;
    drag_y = e.pageY;
};

window.onmouseup =
  window.ontouchend = function(e){
    drag = false;
};

window.onresize = resize;
<commit_msg>simplified reset()<commit_after>'use strict';

function create_gates(new_gates){
    new_gates = new_gates || [{}];
    for(var gate in new_gates){
        gates.push({
          'color': new_gates[gate]['color'] || '#fff',
          'destroy': new_gates[gate]['destroy'] !== void 0
            ? new_gates[gate]['destroy']
            : false,
          'dx': new_gates[gate]['dx'] || false,
          'dy': new_gates[gate]['dy'] || false,
          'event': new_gates[gate]['event'] || function(){},
          'height': new_gates[gate]['height'] || 40,
          'interval': new_gates[gate]['interval'] || 0,
          'x': x + new_gates[gate]['x'] || x,
          'y': y + new_gates[gate]['y'] || y,
          'width': new_gates[gate]['width'] || 40,
        });
    }
}

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    buffer.save();
    buffer.translate(
      -camera_x,
      -camera_y
    );

    // Draw gates.
    for(var gate in gates){
        buffer.fillStyle = gates[gate]['color'];
        buffer.fillRect(
          gates[gate]['x'],
          gates[gate]['y'],
          gates[gate]['width'],
          gates[gate]['height']
       );
    }

    // Draw particles.
    buffer.fillStyle = '#fff';
    for(var particle in particles){
        buffer.fillRect(
          particles[particle]['x'],
          particles[particle]['y'],
          5,
          5
        );
    };

    buffer.restore();

    buffer.fillStyle = '#fff';
    // Draw camera position.
    buffer.fillText(
      camera_x + 'x ' + camera_y + 'y',
      5,
      25
    );

    // Draw number of particles
    //   and max-particles.
    buffer.fillText(
      particles.length
        + ' / '
        + settings['max-particles'],
      5,
      50
    );

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    animationFrame = window.requestAnimationFrame(draw);
}

function logic(){
    if(key_left){
        camera_x -= settings['scroll-speed'];
    }

    if(key_right){
        camera_x += settings['scroll-speed'];
    }

    if(key_down){
        camera_y += settings['scroll-speed'];
    }

    if(key_up){
        camera_y -= settings['scroll-speed'];
    }

    frame_counter += 1;
    if(frame_counter > 99){
        frame_counter = 0;
    }

    for(var particle in particles){
        particles[particle]['x'] += particles[particle]['dx'];
        particles[particle]['y'] += particles[particle]['dy'];

        if(particles[particle]['x'] > boundaries['right']
          || particles[particle]['x'] < boundaries['left']
          || particles[particle]['y'] > boundaries['bottom']
          || particles[particle]['y'] < boundaries['top']){
            particles.splice(
              particle,
              1
            );
        }
    }

    for(var gate in gates){
        if(gates[gate]['interval'] > 0
          && frame_counter % gates[gate]['interval'] === 0){
            gates[gate]['event']();
        }

        for(var particle in particles){
            if(particles[particle]['x'] > gates[gate]['x']
              && particles[particle]['x'] < gates[gate]['x'] + gates[gate]['width']
              && particles[particle]['y'] > gates[gate]['y']
              && particles[particle]['y'] < gates[gate]['y'] + gates[gate]['height']){
                if(gates[gate]['destroy']){
                    particles.splice(
                      particle,
                      1
                    );
                    continue;
                }

                if(gates[gate]['dx'] !== false){
                    particles[particle]['dx'] = gates[gate]['dx'];
                }
                if(gates[gate]['dy'] !== false){
                    particles[particle]['dy'] = gates[gate]['dy'];
                }
            }
        }
    }
}

function play_audio(id){
    if(settings['audio-volume'] <= 0){
        return;
    }

    document.getElementById(id).currentTime = 0;
    document.getElementById(id).play();
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    var ids = {
      'audio-volume': 1,
      'movement-keys': 'WASD',
      'max-particles': 1000,
      'ms-per-frame': 25,
      'reset-camera-key': 'H',
      'scroll-speed': 5,
    };
    for(var id in ids){
        document.getElementById(id).value = ids[id];
    }

    save();
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

    buffer.font = '23pt sans-serif';
}

// Save settings into window.localStorage if they differ from default.
function save(){
    var ids = {
      'audio-volume': 1,
      'max-particles': 1000,
      'ms-per-frame': 25,
      'scroll-speed': 5,
    };
    for(var id in ids){
        var value = document.getElementById(id).value;
        if(value == ids[id]
          || isNaN(value)){
            window.localStorage.removeItem('ParticleRun-2D.htm-' + id);
            settings[id] = ids[id];

        }else{
            settings[id] = parseFloat(value);
            window.localStorage.setItem(
              'ParticleRun-2D.htm-' + id,
              settings[id]
            );
        }
    }

    ids = {
      'movement-keys': 'WASD',
      'reset-camera-key': 'H',
    };
    for(id in ids){
        value = document.getElementById(id).value;
        if(value === ids[id]){
            window.localStorage.removeItem('ParticleRun-2D.htm-' + id);
            settings[id] = ids[id];

        }else{
            settings[id] = value;
            window.localStorage.setItem(
              'ParticleRun-2D.htm-' + id,
              settings[id]
            );
        }
    }
}

function setmode(newmode, newgame){
    window.cancelAnimationFrame(animationFrame);
    window.clearInterval(interval);

    gates = [];
    particles = [];

    mode = newmode;

    // New game mode.
    if(mode > 0){
        // If it's a newgame from the main menu, save settings.
        if(newgame){
            save();
        }

        // Reset.
        camera_x = 0;
        camera_y = 0;
        frame_counter = 0;
        key_left = false;
        key_right = false;

        // If it's a newgame from the main menu, setup canvas and buffers.
        if(newgame){
            document.body.innerHTML =
              '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

            var contextAttributes = {
              'alpha': false,
            };
            buffer = document.getElementById('buffer').getContext(
              '2d',
              contextAttributes
            );
            canvas = document.getElementById('canvas').getContext(
              '2d',
              contextAttributes
            );

            resize();
        }

        load_level(mode);

        animationFrame = window.requestAnimationFrame(draw);
        interval = window.setInterval(
          'logic()',
          settings['ms-per-frame']
        );

        return;
    }

    // Main menu mode.
    buffer = 0;
    canvas = 0;

    document.body.innerHTML = '

Test Level

<input disabled value=ESC>Main Menu
<input id=movement-keys maxlength=4 value='
      + settings['movement-keys'] + '>Camera ↑←↓→
<input id=reset-camera-key maxlength=1 value='
      + settings['reset-camera-key'] + '>Reset Camera

<input id=audio-volume max=1 min=0 step=0.01 type=range value='
      + settings['audio-volume'] + '>Audio
<input id=max-particles value='
      + settings['max-particles'] + '>Max Particles
<input id=ms-per-frame value='
      + settings['ms-per-frame'] + '>ms/Frame
<input id=scroll-speed value='
      + settings['scroll-speed'] + '>Scroll Speed
Reset Settings

';
}

var animationFrame = 0;
var boundaries = {};
var buffer = 0;
var camera_x = 0;
var camera_y = 0;
var canvas = 0;
var drag = false;
var drag_x = 0;
var drag_y = 0;
var frame_counter = 0;
var gates = [];
var height = 0;
var interval = 0;
var key_down = false;
var key_left = false;
var key_right = false;
var key_up = false;
var mode = 0;
var particles = [];
var settings = {
  'audio-volume': window.localStorage.getItem('ParticleRun-2D.htm-audio-volume') !== null
    ? parseFloat(window.localStorage.getItem('ParticleRun-2D.htm-audio-volume'))
    : 1,
  'movement-keys': window.localStorage.getItem('ParticleRun-2D.htm-movement-keys') || 'WASD',
  'max-particles': parseInt(window.localStorage.getItem('ParticleRun-2D.htm-max-particles')) || 1000,
  'ms-per-frame': parseInt(window.localStorage.getItem('ParticleRun-2D.htm-ms-per-frame')) || 25,
  'reset-camera-key': window.localStorage.getItem('ParticleRun-2D.htm-reset-camera-key') || 'H',
  'scroll-speed': window.localStorage.getItem('ParticleRun-2D.htm-scroll-speed') || 5,
};
var x = 0;
var width = 0;
var y = 0;

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // ESC: return to main menu.
    if(key === 27){
        setmode(
          0,
          true
        );
        return;
    }

    key = String.fromCharCode(key);

    if(key === settings['movement-keys'][0]){
        key_up = true;

    }else if(key === settings['movement-keys'][1]){
        key_left = true;

    }else if(key === settings['movement-keys'][2]){
        key_down = true;

    }else if(key === settings['movement-keys'][3]){
        key_right = true;

    }else if(key === settings['reset-camera-key']){
        camera_x = 0;
        camera_y = 0;
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === settings['movement-keys'][0]){
        key_up = false;

    }else if(key === settings['movement-keys'][1]){
        key_left = false;

    }else if(key === settings['movement-keys'][2]){
        key_down = false;

    }else if(key === settings['movement-keys'][3]){
        key_right = false;
    }
};

window.onload = function(e){
    setmode(
      0,
      true
    );
};

window.onmousedown =
  window.ontouchstart = function(e){
    drag = true;
    drag_x = e.pageX;
    drag_y = e.pageY;
};

window.onmousemove =
  window.ontouchmove = function(e){
    if(!drag){
        return;
    }

    camera_x += drag_x - e.pageX;
    camera_y += drag_y - e.pageY;
    drag_x = e.pageX;
    drag_y = e.pageY;
};

window.onmouseup =
  window.ontouchend = function(e){
    drag = false;
};

window.onresize = resize;
<|endoftext|>


<commit_before>window.Browse = Ember.Application.create({
    LOG_TRANSITIONS: true,
    LOG_TRANSITIONS_INTERNAL: false,
    LOG_ACTIVE_GENERATION: false,
    LOG_RESOLVER: false
});

/* Router */
Browse.Router.reopen({
    rootURL: '/browse/',
    location: 'history'
});

Browse.Router.map(function() {
    this.resource('browsers');
    this.resource('browser', {path: '/browsers/:browser_id'});
});

/* Serializer - JsonApiSerializer with modifictions */
DS.JsonApiNamespacedSerializer = DS.JsonApiSerializer.extend({
    namespace: 'api',
    extractLinks: function(links) {
        // Modifications:
        // Strip the namespace from links as well
        // Camelize linkKeys
        var link, key, value, route;
        var extracted = [], linkEntry, linkKey;

        for (link in links) {
            key = link.split('.').pop();
            value = links[link];
            if (typeof value === 'string') {
                route = value;
            } else {
                key = value.type || key;
                route = value.href;
            }

            // strip base url
            if (route.substr(0, 4).toLowerCase() === 'http') {
                route = route.split('//').pop().split('/').slice(1).join('/');
            }

            // strip prefix slash
            if (route.charAt(0) === '/') {
                route = route.substr(1);
            }

            // strip namespace
            if (route.indexOf(this.namespace) == 0) {
                route = route.substr(this.namespace.length);
                if (route.charAt(0) === '/') {
                    route = route.substr(1);
                }
            }

            linkEntry = { };
            linkKey = Ember.String.singularize(key);
            linkKey = Ember.String.camelize(linkKey);
            linkEntry[linkKey] = route;
            extracted.push(linkEntry);
            DS._routes[linkKey] = route;
        }

        return extracted;
    }
})

/* Adapter - JsonApiAdapter with modifictions */
Browse.ApplicationAdapter = DS.JsonApiAdapter.extend({
    namespace: 'api',
    defaultSerializer: 'DS/jsonApiNamespaced'
/*
    buildURL: function(typeName, id) {
        var x = this._super(typeName, id);
        //debugger;
        return x;
    }
*/
});
//DS._routes['browserVersion'] = "versions/{browsers.versions}"

/* Routes */
Browse.BrowsersRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('browser');
    }
});

/* Models */
var attr = DS.attr;

Browse.Browser = DS.Model.extend({
    slug: attr('string'),
    icon: attr(),
    name: attr(),
    note: attr(),
    versions: DS.hasMany('version', {async: true}),
});

Browse.Version = DS.Model.extend({
    browser: DS.belongsTo('browser'),
    version: attr('string'),
    release_day: attr('date'),
    retirement_day: attr('date'),
    status: attr('string'),
    release_notes_uri: attr(),
    note: attr(),
    order: attr('number')
});

/* Controllers */
Browse.BrowserController = Ember.ObjectController.extend({
    versionInflection: function() {
        var versions = this.get('model.versions');
        var count = versions.get('length');
        if (count === 1) {
            return 'Version';
        } else {
            return 'Versions';
        }
    }.property('model.versions.@each')
});
<commit_msg>Fix browse app for v1<commit_after>window.Browse = Ember.Application.create({
    LOG_TRANSITIONS: true,
    LOG_TRANSITIONS_INTERNAL: false,
    LOG_ACTIVE_GENERATION: false,
    LOG_RESOLVER: false
});

/* Router */
Browse.Router.reopen({
    rootURL: '/browse/',
    location: 'history'
});

Browse.Router.map(function() {
    this.resource('browsers');
    this.resource('browser', {path: '/browsers/:browser_id'});
});

/* Serializer - JsonApiSerializer with modifictions */
DS.JsonApiNamespacedSerializer = DS.JsonApiSerializer.extend({
    namespace: 'api/v1',
    extractLinks: function(links) {
        // Modifications:
        // Strip the namespace from links as well
        // Camelize linkKeys
        var link, key, value, route;
        var extracted = [], linkEntry, linkKey;

        for (link in links) {
            key = link.split('.').pop();
            value = links[link];
            if (typeof value === 'string') {
                route = value;
            } else {
                key = value.type || key;
                route = value.href;
            }

            // strip base url
            if (route.substr(0, 4).toLowerCase() === 'http') {
                route = route.split('//').pop().split('/').slice(1).join('/');
            }

            // strip prefix slash
            if (route.charAt(0) === '/') {
                route = route.substr(1);
            }

            // strip namespace
            if (route.indexOf(this.namespace) == 0) {
                route = route.substr(this.namespace.length);
                if (route.charAt(0) === '/') {
                    route = route.substr(1);
                }
            }

            linkEntry = { };
            linkKey = Ember.String.singularize(key);
            linkKey = Ember.String.camelize(linkKey);
            linkEntry[linkKey] = route;
            extracted.push(linkEntry);
            DS._routes[linkKey] = route;
        }

        return extracted;
    }
})

/* Adapter - JsonApiAdapter with modifictions */
Browse.ApplicationAdapter = DS.JsonApiAdapter.extend({
    namespace: 'api/v1',
    defaultSerializer: 'DS/jsonApiNamespaced'
/*
    buildURL: function(typeName, id) {
        var x = this._super(typeName, id);
        //debugger;
        return x;
    }
*/
});
//DS._routes['browserVersion'] = "versions/{browsers.versions}"

/* Routes */
Browse.BrowsersRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('browser');
    }
});

/* Models */
var attr = DS.attr;

Browse.Browser = DS.Model.extend({
    slug: attr('string'),
    icon: attr(),
    name: attr(),
    note: attr(),
    versions: DS.hasMany('version', {async: true}),
});

Browse.Version = DS.Model.extend({
    browser: DS.belongsTo('browser'),
    version: attr('string'),
    release_day: attr('date'),
    retirement_day: attr('date'),
    status: attr('string'),
    release_notes_uri: attr(),
    note: attr(),
    order: attr('number')
});

/* Controllers */
Browse.BrowserController = Ember.ObjectController.extend({
    versionInflection: function() {
        var versions = this.get('model.versions');
        var count = versions.get('length');
        if (count === 1) {
            return 'Version';
        } else {
            return 'Versions';
        }
    }.property('model.versions.@each')
});
<|endoftext|>