<commit_before>/** @jsx jsx */
import { jsx } from '@emotion/core';

import { H5, Html } from '../primitives';
import { AvatarStack } from '../primitives/Avatar';
import { mq } from '../helpers/media';

const Talks = ({ talks }) => {
  return (
    <Wrapper>
      {talks.map(talk => {
        const hasSpeakers = Boolean(talk.speakers && talk.speakers.length);

        return (
          <Talk key={talk.id}>

              {hasSpeakers && (
                <AvatarStack
                  users={talk.speakers}
                  size="large"
                  css={{
                    marginRight: CONTENT_GUTTER,
                  }}
                />
              )}
              {talk.isLightningTalk && <Bolt />}

                {talk.name}

            <Content>
              {talk.description ?  : null}
              {hasSpeakers && <Byline speakers={talk.speakers} />}
            </Content>
          </Talk>
        );
      })}
    </Wrapper>
  );
};

export default Talks;

// ==============================
// Styled Components
// ==============================

const CONTENT_GUTTER = 16;

const Wrapper = props => (

);
const Talk = props => (

);
const Content = props => (

);
const Bolt = props => {
  const size = 32;
  const offset = size / 4;

  return (

      ⚡

  );
};
const Byline = ({ speakers, ...props }) => (

    by{' '}
    {speakers.map((speaker, idx) => {
      let separator;
      if (idx) separator = ', ';
      if (idx + 1 === speakers.length && speakers.length !== 1) separator = ' and ';

      return (

          {separator}
          {speaker.name}

      );
    })}

);
<commit_msg>Apply suggestions from code review<commit_after>/** @jsx jsx */
import { jsx } from '@emotion/core';

import { H5, Html } from '../primitives';
import { AvatarStack } from '../primitives/Avatar';
import { mq } from '../helpers/media';

const Talks = ({ talks }) => {
  return (
    <Wrapper>
      {talks.map(talk => {
        const hasSpeakers = Boolean(talk.speakers && talk.speakers.length);

        return (
          <Talk key={talk.id}>

              {hasSpeakers && (
                <AvatarStack
                  users={talk.speakers}
                  size="large"
                  css={{
                    marginRight: CONTENT_GUTTER,
                  }}
                />
              )}
              {talk.isLightningTalk && <Bolt />}

                {talk.name}

            <Content>
              {talk.description ?  : null}
              {hasSpeakers && <Byline speakers={talk.speakers} />}
            </Content>
          </Talk>
        );
      })}
    </Wrapper>
  );
};

export default Talks;

// ==============================
// Styled Components
// ==============================

const CONTENT_GUTTER = 16;

const Wrapper = props => (

);
const Talk = props => (

);
const Content = props => (

);
const Bolt = props => {
  const size = 32;
  const offset = size / 4;

  return (

      ⚡

  );
};
const Byline = ({ speakers, ...props }) => (

    by{' '}
    {speakers.map((speaker, idx) => {
      let separator;
      if (idx) separator = ', ';
      if (idx + 1 === speakers.length && speakers.length !== 1) separator = ' and ';

      return (

          {separator}
          {speaker.name}

      );
    })}

);
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	port: 443,
	db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/northwindnode',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.min.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.min.js',
				'public/lib/angular-animate/angular-animate.min.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: 'https://localhost:443/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/linkedin/callback'
	},
	github: {
		clientID: process.env.GITHUB_ID || 'APP_ID',
		clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/github/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};<commit_msg>modified<commit_after>'use strict';

module.exports = {
	port: 443,
	db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/simpledb',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.min.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.min.js',
				'public/lib/angular-animate/angular-animate.min.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: 'https://localhost:443/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/linkedin/callback'
	},
	github: {
		clientID: process.env.GITHUB_ID || 'APP_ID',
		clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
		callbackURL: 'https://localhost:443/auth/github/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};<|endoftext|>


<commit_before>new require('styles/dark')
let audio = require('services/audio')
let socket = require('services/socket')
let wav = require('parsers/wav')
module.exports = class extends require('base/drawapp'){ //top
	prototype() {
		this.props = {
			winner: - 1,
			page:0
		}
		this.tools = {
			Splash:require('base/view').extend({
				props:{text:'HI'},
				tools:{
					Bg:require('shaders/quad').extend({
						padding:130,
						fillColor:'orange',
						pixel:function() {$
							this.viewport(this.mesh.xy)
							this.translate(.5, .5)
							this.circle(0., 0., .35) //+sin(this.time*8))
							let p = this.pos
							this.shape += 0.05 * abs(sin(atan(p.y, p.x) * 8 + this.time * 8))
							this.fillKeep(this.fillColor)
							this.strokeKeep('#44ffff', .02)
							this.shape += 0.08
							this.strokeKeep('red', .03)
							this.blur = 0.2
							this.glow('white', 0.1)
							return this.result
						}
					}),
					Text:require('shaders/text').extend({
						fontSize:32,
						align:[0.5, 0.5],
						boldness:3.,
						outlineWidth:0.04,
						shadowColor:'#0009',
						shadowBlur:0.01,
						shadowOffset:[2., 2],
						dy: - 4.1,
						lineSpacing:0.9,
						outlineColor:'black',
						vertexStyle:function() {
							let b = this.bouncy = abs(sin(this.time))
							this.shadowOffset = vec2(b * 10, b * 10)
						},
						vertexPos:function(pos) {
							//return pos
							this.pos = pos
							let cen = vec2(this.viewSpace.x * .5, this.viewSpace.y * .53)
							this.scale((this.bouncy * 0.8 + 1.5), cen.x, cen.y)
							this.rotate(this.bouncy * .25, cen.x, cen.y)
							return this.pos
						},
					}),
				},
				onDraw:function() {
					this.beginBg({fillColor:this.color})
					this.drawText({text:this.text})
					this.endBg()
				}
			}),

		}
	}

	constructor() {
		super()
		audio.reset()

		this.coinUp = new audio.Flow({buffer1:{data:require('/examples/cash.wav', wav.parse)}})
		this.coinDown = new audio.Flow({buffer1:{data:require('/examples/cow.wav', wav.parse)}})
		this.snds = [
			new audio.Flow({buffer1:{data:require('/examples/horn.wav', wav.parse)}}),
			new audio.Flow({buffer1:{data:require('/examples/baby.wav', wav.parse)}}),
			new audio.Flow({buffer1:{data:require('/examples/bicycle.wav', wav.parse)}}),
			new audio.Flow({buffer1:{data:require('/examples/chicken.wav', wav.parse)}}),

		]

		var flen = .1 * 44100
		var freqUp = new Float32Array(flen)
		for(let i = 0;i < flen;i ++ ){
			freqUp[i] = ((flen - i) / flen * 0.05)
		}
		// lets set up microphones

		this.recFlow = new audio.Flow({
			delay1:{
				to:'output'
			},
			gain1:{
				to:'output',
				gain:1.0,
			},
			gain2:{
				to:'delay1.delayTime',
			},
			buffer1:{
				to:'gain2',
				data:[freqUp],
				loop:true
			},
			input1:{
				to:'gain1',
				device:'Mic1'
			},
			input2:{
				to:'gain1',
				device:'Mic2'
			},
			input3:{
				to:'gain1',
				device:'Mic3'
			}
		})

		this.players = [
			{name:"Player1", ctrl:0, buzzer:2, button:1, sound:0, score:0, color:'#c33'},
			{name:"Player2", ctrl:0, buzzer:2, button:2, sound:1, score:0, color:'#3c3'},
			{name:"Player3", ctrl:0, buzzer:2, button:3, sound:2, score:0, color:'#33c'},
			{name:"Player4", ctrl:0, buzzer:2, button:4, sound:3, score:0, color:'#cc3'}
		]

		this.questions = [
			{h:"Syntax", q:"Why is null an object"},
			{h:"Promises", q:"What is christmas tree\nprogramming?"},
			{h:"Promises", q:"Why do promises\neat exceptions?"},
			{h:"Generators", q:"What happens if you combine\na generator and a promise?"},
			{h:"Generators", q:"What do generators generate?"},
			{h:"Iterators", q:"Enact iterators with your team"},
			{h:"Iterators", q:"Why are iterators a protocol?"},
			{h:"Arrow functions", q:"Say lambda 5 times real fast"},
			{h:"Arrow functions", q:"What is this?"},
			{h:"Classes", q:"Explain prototypes\nin 2 sentences"},
			{h:"Classes", q:"Are classes prototypes?"},
			{h:"Template literals", q:"Whats literal about\na template literal?"},
			{h:"Template literals", q:"Whats the next biggest\nuse of the backtick"},
			{h:"Modules", q:"What does static analysis mean"},
			{h:"Final Score", q:""},
		]

		this.recFlow.start()
		//socket.postMessage({controller:0,buzzer:0,led:true})
		this.show = ""

		this.winner =  - 1

		socket.onMessage = msg=>{
			if( ! msg.state) return
			// fix player selector based on buzzer
			for(let i = 0;i < this.players.length;i ++ ){
				let player = this.players[i]
				if(player.ctrl == msg.controller && player.buzzer == msg.buzzer && player.button == msg.button) {
					this.playerWin(i)
					break
				}
			}

		}

		this.page = 0
	}

	playerWin(id) {
		if(this.winner !==  - 1) return

		this.winner = id

		let player = this.players[this.winner]

		this.snds[player.sound].play()

		socket.postMessage({
			controller:player.ctrl,
			buzzer:player.buzzer,
			led:true
		})
	}

	lightsOff() {
		this.winner =  - 1
		for(let i = 0;i < 4;i ++ ){
			socket.postMessage({
				controller:0,
				buzzer:i,
				led:false
			})
		}
	}

	playerScore(index, add) {
		if(add > 0) this.coinUp.play()
		else this.coinDown.play()
		let player = this.players[index]
		if(player) player.score += add
		this.redraw()
	}

	onKeyDown(e) {

		var fake = {q:0, w:1, e:2, r:3}
		if(fake[e.name] !== undefined) {
			return this.playerWin(fake[e.name])
		}
		this.lightsOff()
		if(e.name.indexOf('num') === 0) {
			console.log(e.name, e.name.slice(2))
			this.playerScore(parseInt(e.name.slice(3)) - 1, e.shift? - 1:1)
		}
		if(e.name === 'leftArrow') {
			this.page = max(0, this.page - 1)
		}
		if(e.name === 'rightArrow') {
			this.page = min(this.questions.length, this.page + 1)
		}
	}

	onDraw() {
		//for(var i=0;i<1;i++)
		if(this.page == 0) {
			this.drawSplash({id:0, text:'Never mind the\n   Buzzwords'})
		}
		else {

			for(let i = 0;i < this.players.length;i ++ ){
				let player = this.players[i]
				this.beginBg({
					align:[0., 1],
					color:player.color,
					margin:5,
					padding:15,
					w:'200'
				})
				this.drawText({
					align:[1, 0],
					fontSize:20,
					order:1,
					text:'' + player.score
				})
				this.drawText({
					fontSize:20,
					align:[0, 0],
					order:1,
					text:player.name
				})

				this.endBg()
			}
			this.drawText({
				fontSize:50,
				margin:[0, 0, 0, 40],
				align:[0., 0],
				text:this.questions[this.page - 1].h
			})
			this.lineBreak()
			this.turtle.wy += 40
			this.drawText({
				fontSize:32,
				margin:[0, 0, 0, 40],
				text:this.questions[this.page - 1].q
			})

			// draw players points
			let winner = this.players[this.winner]
			if(winner) {
				this.drawSplash({id:1, x:100, y:120, color:winner.color, text:winner.name})
			}
		}
		//this.drawSplash({id:0,text:'hi'+this.show})
	}
}<commit_msg>gameshow<commit_after>new require('styles/dark')
let audio = require('services/audio')
let socket = require('services/socket')
let wav = require('parsers/wav')
module.exports = class extends require('base/drawapp'){ //top
	prototype() {
		this.props = {
			winner: - 1,
			page:0
		}
		this.tools = {
			Splash:require('base/view').extend({
				props:{text:'HI'},
				tools:{
					Bg:require('shaders/quad').extend({
						padding:130,
						fillColor:'orange',
						pixel:function() {$
							this.viewport(this.mesh.xy)
							this.translate(.5, .5)
							this.circle(0., 0., .35) //+sin(this.time*8))
							let p = this.pos
							this.shape += 0.05 * abs(sin(atan(p.y, p.x) * 8 + this.time * 8))
							this.fillKeep(this.fillColor)
							this.strokeKeep('#44ffff', .02)
							this.shape += 0.08
							this.strokeKeep('red', .03)
							this.blur = 0.2
							this.glow('white', 0.1)
							return this.result
						}
					}),
					Text:require('shaders/text').extend({
						fontSize:32,
						align:[0.5, 0.5],
						boldness:3.,
						outlineWidth:0.04,
						shadowColor:'#0009',
						shadowBlur:0.01,
						shadowOffset:[2., 2],
						dy: - 4.1,
						lineSpacing:0.9,
						outlineColor:'black',
						vertexStyle:function() {
							let b = this.bouncy = abs(sin(this.time))
							this.shadowOffset = vec2(b * 10, b * 10)
						},
						vertexPos:function(pos) {
							//return pos
							this.pos = pos
							let cen = vec2(this.viewSpace.x * .5, this.viewSpace.y * .53)
							this.scale((this.bouncy * 0.8 + 1.5), cen.x, cen.y)
							this.rotate(this.bouncy * .25, cen.x, cen.y)
							return this.pos
						},
					}),
				},
				onDraw:function() {
					this.beginBg({fillColor:this.color})
					this.drawText({text:this.text})
					this.endBg()
				}
			}),

		}
	}

	constructor() {
		super()
		audio.reset()

		this.coinUp = new audio.Flow({buffer1:{data:require('/examples/cash.wav', wav.parse)}})
		this.coinDown = new audio.Flow({buffer1:{data:require('/examples/cow.wav', wav.parse)}})
		this.snds = [
			new audio.Flow({buffer1:{data:require('/examples/horn.wav', wav.parse)}}),
			new audio.Flow({buffer1:{data:require('/examples/baby.wav', wav.parse)}}),
			new audio.Flow({buffer1:{data:require('/examples/bicycle.wav', wav.parse)}}),
			new audio.Flow({buffer1:{data:require('/examples/chicken.wav', wav.parse)}}),

		]

		var flen = .1 * 44100
		var freqUp = new Float32Array(flen)
		for(let i = 0;i < flen;i ++ ){
			freqUp[i] = ((flen - i) / flen * 0.05)
		}
		// lets set up microphones

		this.recFlow = new audio.Flow({
			delay1:{
				to:'output'
			},
			gain1:{
				to:'output',
				gain:1.0,
			},
			gain2:{
				to:'delay1.delayTime',
			},
			buffer1:{
				to:'gain2',
				data:[freqUp],
				loop:true
			},
			input1:{
				to:'gain1',
				device:'Mic1'
			},
			input2:{
				to:'gain1',
				device:'Mic2'
			},
			input3:{
				to:'gain1',
				device:'Mic3'
			}
		})

		this.players = [
			{name:"Player1", ctrl:0, buzzer:2, button:1, sound:0, score:0, color:'#c33'},
			{name:"Player2", ctrl:0, buzzer:2, button:2, sound:1, score:0, color:'#3c3'},
			{name:"Player3", ctrl:0, buzzer:2, button:3, sound:2, score:0, color:'#33c'},
			{name:"Player4", ctrl:0, buzzer:2, button:4, sound:3, score:0, color:'#cc3'}
		]

		this.questions = [
			{h:"Syntax", q:"Why is null an object"},
			{h:"Promises", q:"What is christmas tree\nprogramming?"},
			{h:"Promises", q:"Why do promises\neat exceptions?"},
			{h:"Generators", q:"What happens if you combine\na generator and a promise?"},
			{h:"Generators", q:"What do generators generate?"},
			{h:"Iterators", q:"Enact iterators with your team"},
			{h:"Iterators", q:"Why are iterators a protocol?"},
			{h:"Arrow functions", q:"Say lambda 5 times real fast"},
			{h:"Arrow functions", q:"What is this?"},
			{h:"Classes", q:"Explain prototypes\nin 2 sentences"},
			{h:"Classes", q:"Are classes prototypes?"},
			{h:"Template literals", q:"Whats literal about\na template literal?"},
			{h:"Template literals", q:"Whats the next biggest\nuse of the backtick"},
			{h:"Modules", q:"What does static analysis mean"},
			{h:"Final Score", q:""},
		]

		this.recFlow.start()
		//socket.postMessage({controller:0,buzzer:0,led:true})
		this.show = ""

		this.winner =  - 1

		socket.onMessage = msg=>{
			if( ! msg.state) return
			// fix player selector based on buzzer
			for(let i = 0;i < this.players.length;i ++ ){
				let player = this.players[i]
				if(player.ctrl == msg.controller && player.buzzer == msg.buzzer && player.button == msg.button) {
					this.playerWin(i)
					break
				}
			}

		}

		this.page = 0
	}

	playerWin(id) {
		if(this.winner !==  - 1) return

		this.winner = id

		let player = this.players[this.winner]

		this.snds[player.sound].play()

		socket.postMessage({
			controller:player.ctrl,
			buzzer:player.buzzer,
			led:true
		})
	}

	lightsOff() {
		this.winner =  - 1
		for(let i = 0;i < 4;i ++ ){
			socket.postMessage({
				controller:0,
				buzzer:i,
				led:false
			})
		}
	}

	playerScore(index, add) {
		if(add > 0) this.coinUp.play()
		else this.coinDown.play()
		let player = this.players[index]
		if(player) player.score += add
		this.redraw()
	}

	onKeyDown(e) {

		var fake = {q:0, w:1, e:2, r:3}
		if(fake[e.name] !== undefined) {
			return this.playerWin(fake[e.name])
		}
		this.lightsOff()
		if(e.name.indexOf('num') === 0) {
			console.log(e.name, e.name.slice(2))
			this.playerScore(parseInt(e.name.slice(3)) - 1, e.shift? - 1:1)
		}
		if(e.name === 'leftArrow') {
			this.page = max(0, this.page - 1)
		}
		if(e.name === 'rightArrow') {
			this.page = min(this.questions.length, this.page + 1)
		}
	}

	onDraw() {
		//for(var i=0;i<1;i++)
		if(this.page == 0) {
			this.drawSplash({id:0, text:'Never mind the\n   Buzzwords'})
			this.drawText({
				color:'#7',
				margin:[0, 0, 0, 10],
				fontSize:16,
				text:"Arrow keys for pages\nQ W E R simulate buzzer\n1 2 3 4 add points\nOther keys reset buzzer"
			})
		}
		else {

			for(let i = 0;i < this.players.length;i ++ ){
				let player = this.players[i]
				this.beginBg({
					align:[0., 1],
					color:player.color,
					margin:5,
					padding:15,
					w:'200'
				})
				this.drawText({
					align:[1, 0],
					fontSize:20,
					order:1,
					text:'' + player.score
				})
				this.drawText({
					fontSize:20,
					align:[0, 0],
					order:1,
					text:player.name
				})

				this.endBg()
			}
			this.drawText({
				fontSize:50,
				margin:[0, 0, 0, 40],
				align:[0., 0],
				text:this.questions[this.page - 1].h
			})
			this.lineBreak()
			this.turtle.wy += 40
			this.drawText({
				fontSize:32,
				margin:[0, 0, 0, 40],
				text:this.questions[this.page - 1].q
			})

			// draw players points
			let winner = this.players[this.winner]
			if(winner) {
				this.drawSplash({id:1, x:100, y:120, color:winner.color, text:winner.name})
			}
		}
		//this.drawSplash({id:0,text:'hi'+this.show})
	}
}<|endoftext|>


<commit_before>var __window = $(window);
var follow = document.getElementById('follow');
var modal = document.getElementById('modal');
var remove = document.getElementById('remove');

function create(id, title, content, buttons) {
  return new Dialog(content, {
    id: id,
    title: title,
    buttons: buttons
  });
}

$('#button').on('click', function() {
  var popup = create('confirm', null, 'hello, world', [
    {
      which: 13,
      label: '确认',
      className: 'ui-button',
      action: function() {
        this.close();

        create('alert', '提示', '你点击了确认按钮！', [{
          which: 13,
          label: '确认',
          className: 'ui-button',
          action: function() {
            this.close();
          }
        }]).showModal();
      }
    },
    {
      which: 27,
      label: '取消',
      className: 'ui-button ui-button-white',
      action: function() {
        this.close();

        create('alert', '提示', '你点击了取消按钮！', [{
          which: 13,
          label: '确认',
          className: 'ui-button',
          action: function() {
            this.close();
          }
        }]).showModal();
      }
    }
  ]);

  if (!follow.checked) {
    if (!modal.checked) {
      popup.show();
    } else {
      popup.showModal();
    }
  } else {
    if (!modal.checked) {
      popup.show(this);
    } else {
      popup.showModal(this);
    }
  }
});
<commit_msg>update files<commit_after>var __window = $(window);
var follow = document.getElementById('follow');
var modal = document.getElementById('modal');
var remove = document.getElementById('remove');

function create(id, title, content, buttons) {
  var dialog = new Dialog(content, {
    id: id,
    title: title,
    buttons: buttons
  });

  dialog.on('close', function() {
    if (remove.checked) {
      dialog.remove();
    }
  });

  return dialog;
}

$('#button').on('click', function() {
  var popup = create('confirm', null, 'hello, world', [
    {
      which: 13,
      label: '确认',
      className: 'ui-button',
      action: function() {
        this.close();

        create('alert', '提示', '你点击了确认按钮！', [{
          which: 13,
          label: '确认',
          className: 'ui-button',
          action: function() {
            this.close();
          }
        }]).showModal();
      }
    },
    {
      which: 27,
      label: '取消',
      className: 'ui-button ui-button-white',
      action: function() {
        this.close();

        create('alert', '提示', '你点击了取消按钮！', [{
          which: 13,
          label: '确认',
          className: 'ui-button',
          action: function() {
            this.close();
          }
        }]).showModal();
      }
    }
  ]);

  if (!follow.checked) {
    if (!modal.checked) {
      popup.show();
    } else {
      popup.showModal();
    }
  } else {
    if (!modal.checked) {
      popup.show(this);
    } else {
      popup.showModal(this);
    }
  }
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Connect = require('./../../lib/connect');

var Server = module.exports = Connect.createServer(
    // No named params
    function params(){
        arguments[2]();
    },
    // Does not call next AND does not respond
    function hang(req, res, next){
        // Call foo() instead so
        // that our demo can still function.
        var foo = next;
        foo();

        // All good
        var ct = req.headers['content-type'];
    },
    function allGood(req, res, next){
        // All good
        next();
    },
    function reqHeaders(req, res, next){
        // Request headers are always normalized as
        // lowercased by ryan's http parser.
        var ct = req.headers['Content-Type'];
        next();
    },
    function methodUppercase(req, res, next){
        // req.method should be uppercase
        req.method = 'get';
        next();
    }
);

Server.use('/', Connect.lint(Server));<commit_msg>Lint app listening<commit_after>
/**
 * Module dependencies.
 */

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

var server = connect.createServer(
    // No named params
    function params(){
        arguments[2]();
    },
    // Does not call next AND does not respond
    function hang(req, res, next){
        // Call foo() instead so
        // that our demo can still function.
        var foo = next;
        foo();

        // All good
        var ct = req.headers['content-type'];
    },
    function allGood(req, res, next){
        // All good
        next();
    },
    function reqHeaders(req, res, next){
        // Request headers are always normalized as
        // lowercased by ryan's http parser.
        var ct = req.headers['Content-Type'];
        next();
    },
    function methodUppercase(req, res, next){
        // req.method should be uppercase
        req.method = 'get';
        next();
    }
);

server.use('/', connect.lint(server));
server.listen(3000);<|endoftext|>


<commit_before>(function(g){
    /*
     * LispVal = symbol | number | bool | string | list of LispVal
     *
     * 使用vm.js中的V来构造数据
     */
    var symbolChars = "!?#$%&|+-*/:<=>@^_~";
    var blankChars = " \t\n\r";

    let {stream, C, N, F} = g.parsec;

    let {V} = g.vm;

    /* util */

    function _or([f, ...fr]) {
	if(1 === fr.length) {
	    return F.try(f).or(fr[0])
	} else {
	    return F.try(f).or(_or(fr))
	}
    }

    /* definition */

    var _symbolChar = C.charIn(symbolChars)
    var symbol = F.try(C.letter).or(_symbolChar) // first
        .then(F.try(C.letter).or(F.try(N.digit).or(_symbolChar)).optrep()) // rest
	.map(([first, rest=[]]) => V.s([first, rest.join("")].join("")))

    var bool = C.char("#")
	.thenRight(C.charIn("tf"))
	.map(x => ({"t": V.TRUE, "f": V.FALSE})[x])

    var _special_char = C.char("\\")
	.thenRight(_or(
	    [C.char("n").thenReturns(V.string("\n")),
	     C.char("t").thenReturns(V.string("\t")),
	     C.char("\"").thenReturns(V.string("\"")),
	     C.char("\\").thenReturns(V.string("\\"))]))

    var string = C.char("\"")
	.thenRight(F.try(_special_char)
		   .or(C.notChar("\""))
		   .optrep()
		   .map(xs => V.string(xs.join(""))))
	.thenLeft(C.char("\""))

    var _blankChars = C.charIn(blankChars).optrep()

    /**
     * 入口parser在此处定义，并采用惰性求值的方式，
     * 使得list的定义可以向上递归使用lisp的定义，
     * 构成一个互递归的结构
     */
    var lisp = F.lazy(
	() => _blankChars
	    .thenRight(_or(
		[bool,
		 N.integer.map(i => V.int(i)),
		 // bool and integer shall be parsed
		 // in precedence of symbol
		 symbol,
		 string,
		 list]))
    )

    var _list_tail = _blankChars.then(C.char(")")).thenReturns(V.NULL)
    var _dotted_tail = _blankChars
	.then(C.char("."))
	.thenRight(lisp)
	.thenLeft(_list_tail)

    var list =
	C.char("(")
	.thenRight(
	    F.try(lisp.rep()
		  .then(F.try(_list_tail).or(_dotted_tail))
		  .map(([xs, tail]) => {xs.push(tail); return xs}))
	    // or empty list (null)
		.or(_list_tail))

    // g.lispParser = {
    // 	symbol,
    // 	bool,
    // 	string,
    // 	list,
    // 	_blankChars,
    // 	_list_tail,
    // 	_dotted_tail,
    // 	list
    // 	lisp
    // }
    g.lispParser = lisp
})(this)
<commit_msg>parser添加方括号支持<commit_after>(function(g){
    /*
     * LispVal = symbol | number | bool | string | list of LispVal
     *
     * 使用vm.js中的V来构造数据
     */
    var symbolChars = "!?#$%&|+-*/:<=>@^_~";
    var blankChars = " \t\n\r";

    let {stream, C, N, F} = g.parsec;

    let {V} = g.vm;

    /* util */

    function _or([f, ...fr]) {
	if(1 === fr.length) {
	    return F.try(f).or(fr[0])
	} else {
	    return F.try(f).or(_or(fr))
	}
    }

    /* definition */

    var _symbolChar = C.charIn(symbolChars)
    var symbol = F.try(C.letter).or(_symbolChar) // first
        .then(F.try(C.letter).or(F.try(N.digit).or(_symbolChar)).optrep()) // rest
	.map(([first, rest=[]]) => V.s([first, rest.join("")].join("")))

    var bool = C.char("#")
	.thenRight(C.charIn("tf"))
	.map(x => ({"t": V.TRUE, "f": V.FALSE})[x])

    var _special_char = C.char("\\")
	.thenRight(_or(
	    [C.char("n").thenReturns(V.string("\n")),
	     C.char("t").thenReturns(V.string("\t")),
	     C.char("\"").thenReturns(V.string("\"")),
	     C.char("\\").thenReturns(V.string("\\"))]))

    var string = C.char("\"")
	.thenRight(F.try(_special_char)
		   .or(C.notChar("\""))
		   .optrep()
		   .map(xs => V.string(xs.join(""))))
	.thenLeft(C.char("\""))

    var _blankChars = C.charIn(blankChars).optrep()

    /**
     * 入口parser在此处定义，并采用惰性求值的方式，
     * 使得list的定义可以向上递归使用lisp的定义，
     * 构成一个互递归的结构
     */
    var lisp = F.lazy(
	() => _blankChars
	    .thenRight(_or(
		[bool,
		 N.integer.map(i => V.int(i)),
		 // bool and integer shall be parsed
		 // in precedence of symbol
		 symbol,
		 string,
		 list]))
    )

    var _list_tail = _blankChars.then(C.charIn(")]")).thenReturns(V.NULL)
    var _dotted_tail = _blankChars
	.then(C.char("."))
	.thenRight(lisp)
	.thenLeft(_list_tail)

    var list =
	C.charIn("([")
	.thenRight(
	    F.try(lisp.rep()
		  .then(F.try(_list_tail).or(_dotted_tail))
		  .map(([xs, tail]) => {xs.push(tail); return xs}))
	    // or empty list (null)
		.or(_list_tail))

    // g.lispParser = {
    // 	symbol,
    // 	bool,
    // 	string,
    // 	list,
    // 	_blankChars,
    // 	_list_tail,
    // 	_dotted_tail,
    // 	list
    // 	lisp
    // }
    g.lispParser = lisp
})(this)
<|endoftext|>


<commit_before>(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory) /* global define */
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory()
  } else {
    root.moo = factory()
  }
}(this, function() {
  'use strict';

  var hasOwnProperty = Object.prototype.hasOwnProperty
  var toString = Object.prototype.toString
  var hasSticky = typeof new RegExp().sticky === 'boolean'

  /***************************************************************************/

  function isRegExp(o) { return o && toString.call(o) === '[object RegExp]' }
  function isObject(o) { return o && typeof o === 'object' && !isRegExp(o) && !Array.isArray(o) }

  function reEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  function reGroups(s) {
    var re = new RegExp('|' + s)
    return re.exec('').length - 1
  }
  function reCapture(s) {
    return '(' + s + ')'
  }
  function reUnion(regexps) {
    if (!regexps.length) return '(?!)'
    var source =  regexps.map(function(s) {
      return "(?:" + s + ")"
    }).join('|')
    return "(?:" + source + ")"
  }

  function regexpOrLiteral(obj) {
    if (typeof obj === 'string') {
      return '(?:' + reEscape(obj) + ')'

    } else if (isRegExp(obj)) {
      // TODO: consider /u support
      if (obj.ignoreCase) throw new Error('RegExp /i flag not allowed')
      if (obj.global) throw new Error('RegExp /g flag is implied')
      if (obj.sticky) throw new Error('RegExp /y flag is implied')
      if (obj.multiline) throw new Error('RegExp /m flag is implied')
      if (obj.unicode) throw new Error('RegExp /u flag is not allowed')
      return obj.source

    } else {
      throw new Error('Not a pattern: ' + obj)
    }
  }

  function objectToRules(object) {
    var keys = Object.getOwnPropertyNames(object)
    var result = []
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      var thing = object[key]
      var rules = Array.isArray(thing) ? thing : [thing]
      var match = []
      rules.forEach(function(rule) {
        if (isObject(rule)) {
          if (match.length) result.push(ruleOptions(key, match))
          result.push(ruleOptions(key, rule))
          match = []
        } else {
          match.push(rule)
        }
      })
      if (match.length) result.push(ruleOptions(key, match))
    }
    return result
  }

  function arrayToRules(array) {
    var result = []
    for (var i = 0; i < array.length; i++) {
      var obj = array[i]
      if (!obj.name) {
        throw new Error('Rule has no name: ' + JSON.stringify(obj))
      }
      result.push(ruleOptions(obj.name, obj))
    }
    return result
  }

  function ruleOptions(name, obj) {
    if (!isObject(obj)) {
      obj = { match: obj }
    }

    // nb. error and fallback imply lineBreaks
    var options = {
      tokenType: name,
      lineBreaks: !!obj.error || !!obj.fallback,
      pop: false,
      next: null,
      push: null,
      error: false,
      fallback: false,
      value: null,
      getType: null,
      shouldThrow: false,
    }

    // Avoid Object.assign(), so we support IE9+
    for (var key in obj) {
      if (hasOwnProperty.call(obj, key)) {
        options[key] = obj[key]
      }
    }

    // convert to array
    var match = options.match
    options.match = Array.isArray(match) ? match : match ? [match] : []
    options.match.sort(function(a, b) {
      return isRegExp(a) && isRegExp(b) ? 0
           : isRegExp(b) ? -1 : isRegExp(a) ? +1 : b.length - a.length
    })
    if (options.keywords) {
      options.getType = keywordTransform(options.keywords)
    }
    return options
  }

  var defaultErrorRule = ruleOptions('error', {lineBreaks: true, shouldThrow: true})
  function compileRules(rules, hasStates) {
    rules = Array.isArray(rules) ? arrayToRules(rules) : objectToRules(rules)

    var errorRule = null
    var groups = []
    var parts = []
    for (var i = 0; i < rules.length; i++) {
      var options = rules[i]

      if (options.error || options.fallback) {
        if (errorRule) {
          throw new Error((!options.fallback === !errorRule.fallback ? "Multiple " + (options.fallback ? "fallback" : "error") + " rules not allowed" : "fallback and error are mutually exclusive") + " (for token '" + options.tokenType + "')")
        }
        errorRule = options
      }

      // skip rules with no match
      if (options.match.length === 0) {
        continue
      }
      groups.push(options)

      // convert to RegExp
      var pat = reUnion(options.match.map(regexpOrLiteral))

      // validate
      var regexp = new RegExp(pat)
      if (regexp.test("")) {
        throw new Error("RegExp matches empty string: " + regexp)
      }
      var groupCount = reGroups(pat)
      if (groupCount > 0) {
        throw new Error("RegExp has capture groups: " + regexp + "\nUse (?: … ) instead")
      }
      if ((!hasStates || options.fallback) && (options.pop || options.push || options.next)) {
        throw new Error("State-switching options are not allowed in " + (options.fallback ? 'fallback tokens' : 'stateless lexers') + " (for token '" + options.tokenType + "')")
      }

      // try and detect rules matching newlines
      if (!options.lineBreaks && regexp.test('\n')) {
        throw new Error('Rule should declare lineBreaks: ' + regexp)
      }

      // store regex
      parts.push(reCapture(pat))
    }

    var fallbackRule = errorRule && errorRule.fallback
    var suffix = hasSticky || fallbackRule ? '' : '|'
    var flags = hasSticky && !fallbackRule ? 'ym' : 'gm'
    var combined = new RegExp(reUnion(parts) + suffix, flags)

    return {regexp: combined, groups: groups, error: errorRule || defaultErrorRule}
  }

  function compile(rules) {
    var result = compileRules(rules)
    return new Lexer({start: result}, 'start')
  }

  function compileStates(states, start) {
    var keys = Object.getOwnPropertyNames(states)
    if (!start) start = keys[0]

    var map = Object.create(null)
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      map[key] = compileRules(states[key], true)
    }

    for (var i = 0; i < keys.length; i++) {
      var groups = map[keys[i]].groups
      for (var j = 0; j < groups.length; j++) {
        var g = groups[j]
        var state = g && (g.push || g.next)
        if (state && !map[state]) {
          throw new Error("Missing state '" + state + "' (in token '" + g.tokenType + "' of state '" + keys[i] + "')")
        }
        if (g && g.pop && +g.pop !== 1) {
          throw new Error("pop must be 1 (in token '" + g.tokenType + "' of state '" + keys[i] + "')")
        }
      }
    }

    return new Lexer(map, start)
  }

  function keywordTransform(map) {
    var reverseMap = Object.create(null)
    var byLength = Object.create(null)
    var types = Object.getOwnPropertyNames(map)
    for (var i = 0; i < types.length; i++) {
      var tokenType = types[i]
      var item = map[tokenType]
      var keywordList = Array.isArray(item) ? item : [item]
      keywordList.forEach(function(keyword) {
        (byLength[keyword.length] = byLength[keyword.length] || []).push(keyword)
        if (typeof keyword !== 'string') {
          throw new Error("keyword must be string (in keyword '" + tokenType + "')")
        }
        reverseMap[keyword] = tokenType
      })
    }

    // fast string lookup
    // https://jsperf.com/string-lookups
    function str(x) { return JSON.stringify(x) }
    var source = ''
    source += 'switch (value.length) {\n'
    for (var length in byLength) {
      var keywords = byLength[length]
      source += 'case ' + length + ':\n'
      source += 'switch (value) {\n'
      keywords.forEach(function(keyword) {
        var tokenType = reverseMap[keyword]
        source += 'case ' + str(keyword) + ': return ' + str(tokenType) + '\n'
      })
      source += '}\n'
    }
    source += '}\n'
    return Function('value', source) // getType
  }

  /***************************************************************************/

  var Lexer = function(states, state) {
    this.startState = state
    this.states = states
    this.buffer = ''
    this.stack = []
    this.reset()
  }

  Lexer.prototype.reset = function(data, info) {
    this.buffer = data || ''
    this.index = 0
    this.line = info ? info.line : 1
    this.col = info ? info.col : 1
    this.queued = info ? info.queued : null
    this.queuedThrow = info ? info.queuedThrow : null
    this.setState(info ? info.state : this.startState)
    return this
  }

  Lexer.prototype.save = function() {
    return {
      line: this.line,
      col: this.col,
      state: this.state,
      queued: this.queued,
      queuedThrow: this.queuedThrow,
    }
  }

  Lexer.prototype.setState = function(state) {
    if (!state || this.state === state) return
    this.state = state
    var info = this.states[state]
    this.groups = info.groups
    this.error = info.error
    this.re = info.regexp
  }

  Lexer.prototype.popState = function() {
    this.setState(this.stack.pop())
  }

  Lexer.prototype.pushState = function(state) {
    this.stack.push(this.state)
    this.setState(state)
  }

  Lexer.prototype._eat = hasSticky ? function(re) { // assume re is /y
    return re.exec(this.buffer)
  } : function(re) { // assume re is /g
    var match = re.exec(this.buffer)
    // will always match, since we used the |(?:) trick
    if (match[0].length === 0) {
      return null
    }
    return match
  }

  Lexer.prototype._getGroup = function(match) {
    if (match === null) {
      return -1
    }

    var groupCount = this.groups.length
    for (var i = 0; i < groupCount; i++) {
      if (match[i + 1] !== undefined) {
        return i
      }
    }
    throw new Error('Cannot find token type for matched text')
  }

  function tokenToString() {
    return this.value
  }

  Lexer.prototype.next = function() {
    if (this.queued) {
      var queued = this.queued, queuedThrow = this.queuedThrow
      this.queued = null
      this.queuedThrow = false
      if (queuedThrow) {
        throw new Error(this.formatError(queued, "invalid syntax"))
      }
      return queued
    }
    var re = this.re
    var buffer = this.buffer

    var index = re.lastIndex = this.index
    if (index === buffer.length) {
      return // EOF
    }

    var match = this._eat(re)
    var matchIndex = match ? match.index : this.buffer.length
    var i = this._getGroup(match)

    if (this.error.fallback && matchIndex !== index || i === -1) {
      var fallbackToken = this._hadToken(this.error, buffer.slice(index, matchIndex), index)

      if (i === -1) {
        if (this.error.shouldThrow) {
          throw new Error(this.formatError(fallbackToken, "invalid syntax"))
        }
        return fallbackToken
      }
    }

    var group = this.groups[i]
    var token = this._hadToken(group, match[0], matchIndex)

    // throw, if no rule with {error: true}
    if (fallbackToken) {
      this.queued = token
      this.queuedThrow = group.shouldThrow
    } else if (group.shouldThrow) {
      throw new Error(this.formatError(token, "invalid syntax"))
    }

    if (group.pop) this.popState()
    else if (group.push) this.pushState(group.push)
    else if (group.next) this.setState(group.next)

    return fallbackToken || token
  }

  Lexer.prototype._hadToken = function(group, text, offset) {
    // count line breaks
    var lineBreaks = 0
    if (group.lineBreaks) {
      var matchNL = /\n/g
      var nl = 1
      if (text === '\n') {
        lineBreaks = 1
      } else {
        while (matchNL.exec(text)) { lineBreaks++; nl = matchNL.lastIndex }
      }
    }

    var token = {
      type: (group.getType && group.getType(text)) || group.tokenType,
      value: group.value ? group.value(text) : text,
      text: text,
      toString: tokenToString,
      offset: offset,
      lineBreaks: lineBreaks,
      line: this.line,
      col: this.col,
    }
    // nb. adding more props to token object will make V8 sad!

    var size = text.length
    this.index += size
    this.line += lineBreaks
    if (lineBreaks !== 0) {
      this.col = size - nl + 1
    } else {
      this.col += size
    }
    return token
  }

  if (typeof Symbol !== 'undefined' && Symbol.iterator) {
    var LexerIterator = function(lexer) {
      this.lexer = lexer
    }

    LexerIterator.prototype.next = function() {
      var token = this.lexer.next()
      return {value: token, done: !token}
    }

    LexerIterator.prototype[Symbol.iterator] = function() {
      return this
    }

    Lexer.prototype[Symbol.iterator] = function() {
      return new LexerIterator(this)
    }
  }

  Lexer.prototype.formatError = function(token, message) {
    var value = token.value
    var index = token.offset
    var eol = token.lineBreaks ? value.indexOf('\n') : value.length
    var start = Math.max(0, index - token.col + 1)
    var firstLine = this.buffer.substring(start, index + eol)
    message += " at line " + token.line + " col " + token.col + ":\n\n"
    message += "  " + firstLine + "\n"
    message += "  " + Array(token.col).join(" ") + "^"
    return message
  }

  Lexer.prototype.clone = function() {
    return new Lexer(this.states, this.state)
  }

  Lexer.prototype.has = function(tokenType) {
    for (var s in this.states) {
      var state = this.states[s]
      if (state.error && state.error.tokenType === tokenType) return true
      var groups = state.groups
      for (var i = 0; i < groups.length; i++) {
        var group = groups[i]
        if (group.tokenType === tokenType) return true
        if (group.keywords && hasOwnProperty.call(group.keywords, tokenType)) {
          return true
        }
      }
    }
    return false
  }

  return {
    compile: compile,
    states: compileStates,
    error: Object.freeze({error: true}),
    fallback: Object.freeze({fallback: true}),
  }

}))
<commit_msg>Rename queued{ => Token}<commit_after>(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory) /* global define */
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory()
  } else {
    root.moo = factory()
  }
}(this, function() {
  'use strict';

  var hasOwnProperty = Object.prototype.hasOwnProperty
  var toString = Object.prototype.toString
  var hasSticky = typeof new RegExp().sticky === 'boolean'

  /***************************************************************************/

  function isRegExp(o) { return o && toString.call(o) === '[object RegExp]' }
  function isObject(o) { return o && typeof o === 'object' && !isRegExp(o) && !Array.isArray(o) }

  function reEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  function reGroups(s) {
    var re = new RegExp('|' + s)
    return re.exec('').length - 1
  }
  function reCapture(s) {
    return '(' + s + ')'
  }
  function reUnion(regexps) {
    if (!regexps.length) return '(?!)'
    var source =  regexps.map(function(s) {
      return "(?:" + s + ")"
    }).join('|')
    return "(?:" + source + ")"
  }

  function regexpOrLiteral(obj) {
    if (typeof obj === 'string') {
      return '(?:' + reEscape(obj) + ')'

    } else if (isRegExp(obj)) {
      // TODO: consider /u support
      if (obj.ignoreCase) throw new Error('RegExp /i flag not allowed')
      if (obj.global) throw new Error('RegExp /g flag is implied')
      if (obj.sticky) throw new Error('RegExp /y flag is implied')
      if (obj.multiline) throw new Error('RegExp /m flag is implied')
      if (obj.unicode) throw new Error('RegExp /u flag is not allowed')
      return obj.source

    } else {
      throw new Error('Not a pattern: ' + obj)
    }
  }

  function objectToRules(object) {
    var keys = Object.getOwnPropertyNames(object)
    var result = []
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      var thing = object[key]
      var rules = Array.isArray(thing) ? thing : [thing]
      var match = []
      rules.forEach(function(rule) {
        if (isObject(rule)) {
          if (match.length) result.push(ruleOptions(key, match))
          result.push(ruleOptions(key, rule))
          match = []
        } else {
          match.push(rule)
        }
      })
      if (match.length) result.push(ruleOptions(key, match))
    }
    return result
  }

  function arrayToRules(array) {
    var result = []
    for (var i = 0; i < array.length; i++) {
      var obj = array[i]
      if (!obj.name) {
        throw new Error('Rule has no name: ' + JSON.stringify(obj))
      }
      result.push(ruleOptions(obj.name, obj))
    }
    return result
  }

  function ruleOptions(name, obj) {
    if (!isObject(obj)) {
      obj = { match: obj }
    }

    // nb. error and fallback imply lineBreaks
    var options = {
      tokenType: name,
      lineBreaks: !!obj.error || !!obj.fallback,
      pop: false,
      next: null,
      push: null,
      error: false,
      fallback: false,
      value: null,
      getType: null,
      shouldThrow: false,
    }

    // Avoid Object.assign(), so we support IE9+
    for (var key in obj) {
      if (hasOwnProperty.call(obj, key)) {
        options[key] = obj[key]
      }
    }

    // convert to array
    var match = options.match
    options.match = Array.isArray(match) ? match : match ? [match] : []
    options.match.sort(function(a, b) {
      return isRegExp(a) && isRegExp(b) ? 0
           : isRegExp(b) ? -1 : isRegExp(a) ? +1 : b.length - a.length
    })
    if (options.keywords) {
      options.getType = keywordTransform(options.keywords)
    }
    return options
  }

  var defaultErrorRule = ruleOptions('error', {lineBreaks: true, shouldThrow: true})
  function compileRules(rules, hasStates) {
    rules = Array.isArray(rules) ? arrayToRules(rules) : objectToRules(rules)

    var errorRule = null
    var groups = []
    var parts = []
    for (var i = 0; i < rules.length; i++) {
      var options = rules[i]

      if (options.error || options.fallback) {
        if (errorRule) {
          throw new Error((!options.fallback === !errorRule.fallback ? "Multiple " + (options.fallback ? "fallback" : "error") + " rules not allowed" : "fallback and error are mutually exclusive") + " (for token '" + options.tokenType + "')")
        }
        errorRule = options
      }

      // skip rules with no match
      if (options.match.length === 0) {
        continue
      }
      groups.push(options)

      // convert to RegExp
      var pat = reUnion(options.match.map(regexpOrLiteral))

      // validate
      var regexp = new RegExp(pat)
      if (regexp.test("")) {
        throw new Error("RegExp matches empty string: " + regexp)
      }
      var groupCount = reGroups(pat)
      if (groupCount > 0) {
        throw new Error("RegExp has capture groups: " + regexp + "\nUse (?: … ) instead")
      }
      if ((!hasStates || options.fallback) && (options.pop || options.push || options.next)) {
        throw new Error("State-switching options are not allowed in " + (options.fallback ? 'fallback tokens' : 'stateless lexers') + " (for token '" + options.tokenType + "')")
      }

      // try and detect rules matching newlines
      if (!options.lineBreaks && regexp.test('\n')) {
        throw new Error('Rule should declare lineBreaks: ' + regexp)
      }

      // store regex
      parts.push(reCapture(pat))
    }

    var fallbackRule = errorRule && errorRule.fallback
    var suffix = hasSticky || fallbackRule ? '' : '|'
    var flags = hasSticky && !fallbackRule ? 'ym' : 'gm'
    var combined = new RegExp(reUnion(parts) + suffix, flags)

    return {regexp: combined, groups: groups, error: errorRule || defaultErrorRule}
  }

  function compile(rules) {
    var result = compileRules(rules)
    return new Lexer({start: result}, 'start')
  }

  function compileStates(states, start) {
    var keys = Object.getOwnPropertyNames(states)
    if (!start) start = keys[0]

    var map = Object.create(null)
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      map[key] = compileRules(states[key], true)
    }

    for (var i = 0; i < keys.length; i++) {
      var groups = map[keys[i]].groups
      for (var j = 0; j < groups.length; j++) {
        var g = groups[j]
        var state = g && (g.push || g.next)
        if (state && !map[state]) {
          throw new Error("Missing state '" + state + "' (in token '" + g.tokenType + "' of state '" + keys[i] + "')")
        }
        if (g && g.pop && +g.pop !== 1) {
          throw new Error("pop must be 1 (in token '" + g.tokenType + "' of state '" + keys[i] + "')")
        }
      }
    }

    return new Lexer(map, start)
  }

  function keywordTransform(map) {
    var reverseMap = Object.create(null)
    var byLength = Object.create(null)
    var types = Object.getOwnPropertyNames(map)
    for (var i = 0; i < types.length; i++) {
      var tokenType = types[i]
      var item = map[tokenType]
      var keywordList = Array.isArray(item) ? item : [item]
      keywordList.forEach(function(keyword) {
        (byLength[keyword.length] = byLength[keyword.length] || []).push(keyword)
        if (typeof keyword !== 'string') {
          throw new Error("keyword must be string (in keyword '" + tokenType + "')")
        }
        reverseMap[keyword] = tokenType
      })
    }

    // fast string lookup
    // https://jsperf.com/string-lookups
    function str(x) { return JSON.stringify(x) }
    var source = ''
    source += 'switch (value.length) {\n'
    for (var length in byLength) {
      var keywords = byLength[length]
      source += 'case ' + length + ':\n'
      source += 'switch (value) {\n'
      keywords.forEach(function(keyword) {
        var tokenType = reverseMap[keyword]
        source += 'case ' + str(keyword) + ': return ' + str(tokenType) + '\n'
      })
      source += '}\n'
    }
    source += '}\n'
    return Function('value', source) // getType
  }

  /***************************************************************************/

  var Lexer = function(states, state) {
    this.startState = state
    this.states = states
    this.buffer = ''
    this.stack = []
    this.reset()
  }

  Lexer.prototype.reset = function(data, info) {
    this.buffer = data || ''
    this.index = 0
    this.line = info ? info.line : 1
    this.col = info ? info.col : 1
    this.queuedToken = info ? info.queuedToken : null
    this.queuedThrow = info ? info.queuedThrow : null
    this.setState(info ? info.state : this.startState)
    return this
  }

  Lexer.prototype.save = function() {
    return {
      line: this.line,
      col: this.col,
      state: this.state,
      queuedToken: this.queuedToken,
      queuedThrow: this.queuedThrow,
    }
  }

  Lexer.prototype.setState = function(state) {
    if (!state || this.state === state) return
    this.state = state
    var info = this.states[state]
    this.groups = info.groups
    this.error = info.error
    this.re = info.regexp
  }

  Lexer.prototype.popState = function() {
    this.setState(this.stack.pop())
  }

  Lexer.prototype.pushState = function(state) {
    this.stack.push(this.state)
    this.setState(state)
  }

  Lexer.prototype._eat = hasSticky ? function(re) { // assume re is /y
    return re.exec(this.buffer)
  } : function(re) { // assume re is /g
    var match = re.exec(this.buffer)
    // will always match, since we used the |(?:) trick
    if (match[0].length === 0) {
      return null
    }
    return match
  }

  Lexer.prototype._getGroup = function(match) {
    if (match === null) {
      return -1
    }

    var groupCount = this.groups.length
    for (var i = 0; i < groupCount; i++) {
      if (match[i + 1] !== undefined) {
        return i
      }
    }
    throw new Error('Cannot find token type for matched text')
  }

  function tokenToString() {
    return this.value
  }

  Lexer.prototype.next = function() {
    if (this.queuedToken) {
      var queuedToken = this.queuedToken, queuedThrow = this.queuedThrow
      this.queuedToken = null
      this.queuedThrow = false
      if (queuedThrow) {
        throw new Error(this.formatError(queuedToken, "invalid syntax"))
      }
      return queuedToken
    }
    var re = this.re
    var buffer = this.buffer

    var index = re.lastIndex = this.index
    if (index === buffer.length) {
      return // EOF
    }

    var match = this._eat(re)
    var matchIndex = match ? match.index : this.buffer.length
    var i = this._getGroup(match)

    if (this.error.fallback && matchIndex !== index || i === -1) {
      var fallbackToken = this._hadToken(this.error, buffer.slice(index, matchIndex), index)

      if (i === -1) {
        if (this.error.shouldThrow) {
          throw new Error(this.formatError(fallbackToken, "invalid syntax"))
        }
        return fallbackToken
      }
    }

    var group = this.groups[i]
    var token = this._hadToken(group, match[0], matchIndex)

    // throw, if no rule with {error: true}
    if (fallbackToken) {
      this.queuedToken = token
      this.queuedThrow = group.shouldThrow
    } else if (group.shouldThrow) {
      throw new Error(this.formatError(token, "invalid syntax"))
    }

    if (group.pop) this.popState()
    else if (group.push) this.pushState(group.push)
    else if (group.next) this.setState(group.next)

    return fallbackToken || token
  }

  Lexer.prototype._hadToken = function(group, text, offset) {
    // count line breaks
    var lineBreaks = 0
    if (group.lineBreaks) {
      var matchNL = /\n/g
      var nl = 1
      if (text === '\n') {
        lineBreaks = 1
      } else {
        while (matchNL.exec(text)) { lineBreaks++; nl = matchNL.lastIndex }
      }
    }

    var token = {
      type: (group.getType && group.getType(text)) || group.tokenType,
      value: group.value ? group.value(text) : text,
      text: text,
      toString: tokenToString,
      offset: offset,
      lineBreaks: lineBreaks,
      line: this.line,
      col: this.col,
    }
    // nb. adding more props to token object will make V8 sad!

    var size = text.length
    this.index += size
    this.line += lineBreaks
    if (lineBreaks !== 0) {
      this.col = size - nl + 1
    } else {
      this.col += size
    }
    return token
  }

  if (typeof Symbol !== 'undefined' && Symbol.iterator) {
    var LexerIterator = function(lexer) {
      this.lexer = lexer
    }

    LexerIterator.prototype.next = function() {
      var token = this.lexer.next()
      return {value: token, done: !token}
    }

    LexerIterator.prototype[Symbol.iterator] = function() {
      return this
    }

    Lexer.prototype[Symbol.iterator] = function() {
      return new LexerIterator(this)
    }
  }

  Lexer.prototype.formatError = function(token, message) {
    var value = token.value
    var index = token.offset
    var eol = token.lineBreaks ? value.indexOf('\n') : value.length
    var start = Math.max(0, index - token.col + 1)
    var firstLine = this.buffer.substring(start, index + eol)
    message += " at line " + token.line + " col " + token.col + ":\n\n"
    message += "  " + firstLine + "\n"
    message += "  " + Array(token.col).join(" ") + "^"
    return message
  }

  Lexer.prototype.clone = function() {
    return new Lexer(this.states, this.state)
  }

  Lexer.prototype.has = function(tokenType) {
    for (var s in this.states) {
      var state = this.states[s]
      if (state.error && state.error.tokenType === tokenType) return true
      var groups = state.groups
      for (var i = 0; i < groups.length; i++) {
        var group = groups[i]
        if (group.tokenType === tokenType) return true
        if (group.keywords && hasOwnProperty.call(group.keywords, tokenType)) {
          return true
        }
      }
    }
    return false
  }

  return {
    compile: compile,
    states: compileStates,
    error: Object.freeze({error: true}),
    fallback: Object.freeze({fallback: true}),
  }

}))
<|endoftext|>


<commit_before>/*!
 * mor.js v1.0.0
 * http://forchoon.com/projects/javascript/mor-js/
 *
 * Copyright 2011, Alasdair Mercer
 * Licensed under the GPL Version 3 license.
 */

var MorJS = (function () {

    var chars = [
            /* Letters */
            ['\u0041', 'SL'],      // A
            ['\u0042', 'LSSS'],    // B
            ['\u0043', 'LSLS'],    // C
            ['\u0044', 'LSS'],     // D
            ['\u0045', 'S'],       // E
            ['\u0046', 'SSLS'],    // F
            ['\u0047', 'LLS'],     // G
            ['\u0048', 'SSSS'],    // H
            ['\u0049', 'SS'],      // I
            ['\u004A', 'SLLL'],    // J
            ['\u004B', 'LSL'],     // K
            ['\u004C', 'SLSS'],    // L
            ['\u004D', 'LL'],      // M
            ['\u004E', 'LS'],      // N
            ['\u004F', 'LLL'],     // O
            ['\u0050', 'SLLS'],    // P
            ['\u0051', 'LLSL'],    // Q
            ['\u0052', 'SLS'],     // R
            ['\u0053', 'SSS'],     // S
            ['\u0054', 'L'],       // T
            ['\u0055', 'SSL'],     // U
            ['\u0056', 'SSSL'],    // V
            ['\u0057', 'SLL'],     // W
            ['\u0058', 'LSSL'],    // X
            ['\u0059', 'LSLL'],    // Y
            ['\u005A', 'LLSS'],    // Z
            /* Numbers */
            ['\u0030', 'LLLLL'],   // 0
            ['\u0031', 'SLLLL'],   // 1
            ['\u0032', 'SSLLL'],   // 2
            ['\u0033', 'SSSLL'],   // 3
            ['\u0034', 'SSSSL'],   // 4
            ['\u0035', 'SSSSS'],   // 5
            ['\u0036', 'LSSSS'],   // 6
            ['\u0037', 'LLSSS'],   // 7
            ['\u0038', 'LLLSS'],   // 8
            ['\u0039', 'LLLLS'],   // 9
            /* Punctuation */
            ['\u002E', 'SLSLSL'],  // Full stop
            ['\u002C', 'LLSSLL'],  // Comma
            ['\u003F', 'SSLLSS'],  // Question mark
            ['\u0027', 'SLLLLS'],  // Apostrophe
            ['\u0021', 'LSLSLL'],  // Exclamation mark
            ['\u002F', 'LSSLS'],   // Slash
            ['\u0028', 'LSLLS'],   // Left parenthesis
            ['\u0029', 'LSLLSL'],  // Right parenthesis
            ['\u0026', 'SLSSS'],   // Ampersand
            ['\u003A', 'LLLSSS'],  // Colon
            ['\u003B', 'LSLSLS'],  // Semicolon
            ['\u003D', 'LSSSL'],   // Equal sign
            ['\u002B', 'SLSLS'],   // Plus sign
            ['\u002D', 'LSSSSL'],  // Hyphen-minus
            ['\u005F', 'SSLLSL'],  // Low line
            ['\u0022', 'SLSSLS'],  // Quotation mark
            ['\u0024', 'SSSLSSL'], // Dollar sign
            ['\u0040', 'SLLSLS'],  // At sign
            /* Non-English extensions */
            ['\u00C4', 'SLSL'],    // A with diaeresis
            ['\u00C6', 'SLSL'],    //
            ['\u0104', 'SLSL'],    // A with ogonek
            ['\u00C0', 'SLLSL'],   // A with grave
            ['\u00C5', 'SLLSL'],   // A with ring above
            ['\u00C7', 'LSLSS'],   // C with cedilla
            ['\u0108', 'LSLSS'],   // C with circumflex
            ['\u0106', 'LSLSS'],   // C with acute
            ['\u0160', 'LLLL'],    // S with caron
            ['\u00D0', 'SSLLS'],   // Eth
            ['\u015A', 'SSSLSSS'], // S with acute
            ['\u00C8', 'SLSSL'],   // E with grave
            ['\u0141', 'SLSSL'],   // L with stroke
            ['\u00C9', 'SSLSS'],   // E with acute
            ['\u0110', 'SSLSS'],   // D with stroke
            ['\u0118', 'SSLSS'],   // E with ogonek
            ['\u011C', 'LLSLS'],   // G with circumflex
            ['\u0124', 'LLLL'],    // H with circumflex
            ['\u0134', 'SLLLS'],   // J with circumflex
            ['\u0179', 'LLSSLS'],  // Z with acute
            ['\u00D1', 'LLSLL'],   // N with tilde
            ['\u0143', 'LLSLL'],   // N with acute
            ['\u00D6', 'LLLS'],    // O with diaeresis
            ['\u00D8', 'LLLS'],    // O with stroke
            ['\u00D3', 'LLLS'],    // O with acute
            ['\u015C', 'SSSLS'],   // S with circumflex
            ['\u00DE', 'SLLSS'],   // Thorn
            ['\u00DC', 'SSLL'],    // U with diaeresis
            ['\u016C', 'SSLL'],    // U with breve
            ['\u017B', 'LLSSL']    // Z with dot above
        ],
        defaultMode = 'classic',
        /*
         * Mode array order;
         *
         * 0: Short mark (dot)
         * 1: Longer mark (dash)
         * 2: Intra-character gap (between dots and dashes within a character)
         * 3: Short gap (between letters)
         * 4: Medium gap (between words)
         */
        modes = {};

    function defineChar(value, pattern) {
        chars.push([value.toUpperCase(), pattern]);
        return true;
    }

    function defineMode(name, chars) {
        modes[name.toLowerCase()] = chars;
        return true;
    }

    function getMode(name) {
        var mode;
        if (typeof name === 'string') {
            mode = modes[name];
        }
        return mode || getMode(defaultMode);
    }

    function prepare(str) {
        var i, ret = str.trim().split(/\s+/); // Splits words
        for (i = 0; i < ret.length; i++) {
            ret[i] = ret[i].split(''); // Splits characters
        }
        // Returns multi-dimensional array ([word][char])
        return ret;
    }

    function repeat(str, repeat) {
        var i, ret = str;
        for (i = 0; i < repeat; i++) {
            ret += str;
        }
        return ret;
    }

    defineMode('classic', [
        '\u00B7',            // Middle dot
        '\u002D',            // Hyphen-minus
        '\u0020',            // Space
        repeat('\u0020', 3), // Space (x3)
        repeat('\u0020', 7)  // Space (x7)
    ]);
    defineMode('digital', [
        '\u0031',            // 1
        repeat('\u0031', 3), // 1 (x3)
        '\u0030',            // 0
        repeat('\u0030', 3), // 0 (x3)
        repeat('\u0030', 7)  // 0 (x7)
    ]);
    defineMode('simple', [
        '\u0030',            // 0
        '\u0031',            // 1
        '',                  // Nothing
        '\u002C',            // Comma
        '\u0020'             // Space
    ]);

    return {

        decode: function (str, mode) {
            var ret = '';
            mode = getMode(mode);
            // TODO
            return ret;
        },

        define: function (key, value) {
            if (typeof key === 'string') {
                switch (typeof value) {
                case 'object':
                    return defineMode(key, value);
                case 'string':
                    return defineChar(key, value);
                }
            }
            return false;
        },

        encode: function (str, mode) {
            var ret = '';
            mode = getMode(mode);
            // TODO
            return ret;
        }

    };

}());<commit_msg>encoding is now working (untested)<commit_after>/*!
 * mor.js v1.0.0
 * http://forchoon.com/projects/javascript/mor-js/
 *
 * Copyright 2011, Alasdair Mercer
 * Licensed under the GPL Version 3 license.
 */

var MorJS = (function () {

    var chars = [
            /* Letters */
            ['\u0041', 'SL'],      // A
            ['\u0042', 'LSSS'],    // B
            ['\u0043', 'LSLS'],    // C
            ['\u0044', 'LSS'],     // D
            ['\u0045', 'S'],       // E
            ['\u0046', 'SSLS'],    // F
            ['\u0047', 'LLS'],     // G
            ['\u0048', 'SSSS'],    // H
            ['\u0049', 'SS'],      // I
            ['\u004A', 'SLLL'],    // J
            ['\u004B', 'LSL'],     // K
            ['\u004C', 'SLSS'],    // L
            ['\u004D', 'LL'],      // M
            ['\u004E', 'LS'],      // N
            ['\u004F', 'LLL'],     // O
            ['\u0050', 'SLLS'],    // P
            ['\u0051', 'LLSL'],    // Q
            ['\u0052', 'SLS'],     // R
            ['\u0053', 'SSS'],     // S
            ['\u0054', 'L'],       // T
            ['\u0055', 'SSL'],     // U
            ['\u0056', 'SSSL'],    // V
            ['\u0057', 'SLL'],     // W
            ['\u0058', 'LSSL'],    // X
            ['\u0059', 'LSLL'],    // Y
            ['\u005A', 'LLSS'],    // Z
            /* Numbers */
            ['\u0030', 'LLLLL'],   // 0
            ['\u0031', 'SLLLL'],   // 1
            ['\u0032', 'SSLLL'],   // 2
            ['\u0033', 'SSSLL'],   // 3
            ['\u0034', 'SSSSL'],   // 4
            ['\u0035', 'SSSSS'],   // 5
            ['\u0036', 'LSSSS'],   // 6
            ['\u0037', 'LLSSS'],   // 7
            ['\u0038', 'LLLSS'],   // 8
            ['\u0039', 'LLLLS'],   // 9
            /* Punctuation */
            ['\u002E', 'SLSLSL'],  // Full stop
            ['\u002C', 'LLSSLL'],  // Comma
            ['\u003F', 'SSLLSS'],  // Question mark
            ['\u0027', 'SLLLLS'],  // Apostrophe
            ['\u0021', 'LSLSLL'],  // Exclamation mark
            ['\u002F', 'LSSLS'],   // Slash
            ['\u0028', 'LSLLS'],   // Left parenthesis
            ['\u0029', 'LSLLSL'],  // Right parenthesis
            ['\u0026', 'SLSSS'],   // Ampersand
            ['\u003A', 'LLLSSS'],  // Colon
            ['\u003B', 'LSLSLS'],  // Semicolon
            ['\u003D', 'LSSSL'],   // Equal sign
            ['\u002B', 'SLSLS'],   // Plus sign
            ['\u002D', 'LSSSSL'],  // Hyphen-minus
            ['\u005F', 'SSLLSL'],  // Low line
            ['\u0022', 'SLSSLS'],  // Quotation mark
            ['\u0024', 'SSSLSSL'], // Dollar sign
            ['\u0040', 'SLLSLS'],  // At sign
            /* Non-English extensions */
            ['\u00C4', 'SLSL'],    // A with diaeresis
            ['\u00C6', 'SLSL'],    //
            ['\u0104', 'SLSL'],    // A with ogonek
            ['\u00C0', 'SLLSL'],   // A with grave
            ['\u00C5', 'SLLSL'],   // A with ring above
            ['\u00C7', 'LSLSS'],   // C with cedilla
            ['\u0108', 'LSLSS'],   // C with circumflex
            ['\u0106', 'LSLSS'],   // C with acute
            ['\u0160', 'LLLL'],    // S with caron
            ['\u00D0', 'SSLLS'],   // Eth
            ['\u015A', 'SSSLSSS'], // S with acute
            ['\u00C8', 'SLSSL'],   // E with grave
            ['\u0141', 'SLSSL'],   // L with stroke
            ['\u00C9', 'SSLSS'],   // E with acute
            ['\u0110', 'SSLSS'],   // D with stroke
            ['\u0118', 'SSLSS'],   // E with ogonek
            ['\u011C', 'LLSLS'],   // G with circumflex
            ['\u0124', 'LLLL'],    // H with circumflex
            ['\u0134', 'SLLLS'],   // J with circumflex
            ['\u0179', 'LLSSLS'],  // Z with acute
            ['\u00D1', 'LLSLL'],   // N with tilde
            ['\u0143', 'LLSLL'],   // N with acute
            ['\u00D6', 'LLLS'],    // O with diaeresis
            ['\u00D8', 'LLLS'],    // O with stroke
            ['\u00D3', 'LLLS'],    // O with acute
            ['\u015C', 'SSSLS'],   // S with circumflex
            ['\u00DE', 'SLLSS'],   // Thorn
            ['\u00DC', 'SSLL'],    // U with diaeresis
            ['\u016C', 'SSLL'],    // U with breve
            ['\u017B', 'LLSSL']    // Z with dot above
        ],
        defaultMode = 'classic',
        /*
         * Mode array order;
         *
         * 0: Short mark (dot)
         * 1: Longer mark (dash)
         * 2: Intra-character gap (between dots and dashes within a character)
         * 3: Short gap (between letters)
         * 4: Medium gap (between words)
         */
        modes = {};

    function defineChar(value, pattern) {
        chars.push([value.toUpperCase(), pattern]);
        return true;
    }

    function defineMode(name, chars) {
        modes[name.toLowerCase()] = chars;
        return true;
    }

    function getChar(str) {
        var i = 0;
        for (; i < chars.length; i++) {
            if (chars[i][0] === str.toUpperCase()) {
                return chars[i];
            }
        }
    }

    function getMode(name) {
        var mode;
        if (typeof name === 'string') {
            mode = modes[name];
        }
        return mode || getMode(defaultMode);
    }

    function parsePattern(pattern, mode) {
        var i = 0,
            str = '';
        for (; i < pattern.length; i++) {
            if (i > 0) {
                str += mode[2];
            }
            switch (pattern[i]) {
            case 'S':
                str += mode[0];
                break;
            case 'L':
                str += mode[1];
                break;
            }
        }
        return str;
    }

    function prepare(str) {
        var i = 0, ret = str.trim().split(/\s+/); // Splits words
        for (; i < ret.length; i++) {
            ret[i] = ret[i].split(''); // Splits characters
        }
        // Returns multi-dimensional array ([word][char])
        return ret;
    }

    function repeat(str, repeat) {
        var i = 0, ret = '';
        for (; i < repeat; i++) {
            ret += str;
        }
        return ret;
    }

    defineMode('classic', [
        '\u00B7',            // Middle dot
        '\u002D',            // Hyphen-minus
        '\u0020',            // Space
        repeat('\u0020', 3), // Space (x3)
        repeat('\u0020', 7)  // Space (x7)
    ]);
    defineMode('digital', [
        '\u0031',            // 1
        repeat('\u0031', 3), // 1 (x3)
        '\u0030',            // 0
        repeat('\u0030', 3), // 0 (x3)
        repeat('\u0030', 7)  // 0 (x7)
    ]);
    defineMode('simple', [
        '\u0030',            // 0
        '\u0031',            // 1
        '',                  // Nothing
        '\u002C',            // Comma
        '\u0020'             // Space
    ]);

    return {

        decode: function (data) {
            var mode = getMode(data.mode),
                ret = '',
                value = data.value;
            // TODO
            return ret;
        },

        define: function (key, value) {
            if (typeof key === 'string') {
                switch (typeof value) {
                case 'object':
                    return defineMode(key, value);
                case 'string':
                    return defineChar(key, value);
                }
            }
            return false;
        },

        encode: function (data) {
            var char,
                i, j,
                mode = getMode(data.mode),
                ret = '',
                value = prepare(data.value);
            if (value.length) {
                for (i = 0; i < value.length; i++) {
                    if (i > 0) {
                        ret += mode[4];
                    }
                    for (j = 0; j < value[i].length; j++) {
                        if (j > 0) {
                            ret += mode[3];
                        }
                        char = getChar(value[i][j]);
                        if (char) {
                            ret += parsePattern(char[1], mode);
                        }
                    }
                }
            }
            return ret;
        }

    };

}());<|endoftext|>


<commit_before>function EnnemyPokemon(pkmn) {
  this.abilities = pkmn.abilities;
  this.ability = pkmn.ability;
  this.baseAbility = pkmn.baseAbility;
  this.types = pkmn.types;

  this.baseSpecies = pkmn.baseSpecies;
  this.species = pkmn.species;
  this.speciesid = pkmn.speciesid;
  this.forme = pkmn.forme;
  this.formeLetter = pkmn.formeLetter;
  this.formeid = pkmn.formeid;
  this.num = pkmn.num;

  this.baseStats = pkmn.baseStats;
  this.ev = {"hp":0,"atk":0,"def":0,"spa":0,"spd":0,"spe":0};
  this.level = pkmn.level;
  this.hp = (pkmn.hp == 1000)? 100 : pkmn.hp;
  this.maxhp = this.getMaxHP();
  this.boosts = pkmn.boosts;
  this.status = pkmn.status;
  this.statusStage = pkmn.statusStage;
  this.volatiles = pkmn.volatiles;

  this.item = pkmn.item;
  this.moveTrack = pkmn.moveTrack;
  this.moves = pkmn.moves;
  this.movestatuses = pkmn.movestatuses;

  this.lastmove = pkmn.lastmove;
  this.slot = pkmn.slot;
  this.fainted = pkmn.fainted;
  this.zerohp = pkmn.zerohp;
  this.turnstatuses = pkmn.turnstatuses;

  this.gender = pkmn.gender;
  this.heightm = pkmn.heightm;
  this.weightkg = pkmn.weightkg;
};

EnnemyPokemon.prototype.getMaxHP = function() {
  return Math.floor((31 + 2 * this.baseStats["hp"] + Math.floor(this.ev["hp"] / 4.0)) * this.level / 100.0 + 10 + this.level);
};

EnnemyPokemon.prototype.getStat = function(stat) {//updates the value of a given stat
  return Math.floor(Math.floor( 31 + 2 * this.baseStats[stat] + Math.floor(this.ev[stat] / 4.0) * this.level / 100.0 + 5) * 1.0);//replace the 1.0 with the nature
};
<commit_msg>Update EnnemyPokemon.js<commit_after>function EnnemyPokemon(pkmn) {
  this.abilities = pkmn.abilities;
  this.ability = pkmn.ability;
  this.baseAbility = pkmn.baseAbility;
  this.types = pkmn.types;
  this.name = pkmn.name;

  this.baseSpecies = pkmn.baseSpecies;
  this.species = pkmn.species;
  this.speciesid = pkmn.speciesid;
  this.forme = pkmn.forme;
  this.formeLetter = pkmn.formeLetter;
  this.formeid = pkmn.formeid;
  this.num = pkmn.num;

  this.baseStats = pkmn.baseStats;
  this.ev = {"hp":0,"atk":0,"def":0,"spa":0,"spd":0,"spe":0};
  this.level = pkmn.level;
  this.hp = (pkmn.hp == 1000)? 100 : pkmn.hp;
  this.maxhp = this.getMaxHP();
  this.boosts = pkmn.boosts;
  this.status = pkmn.status;
  this.statusStage = pkmn.statusStage;
  this.volatiles = pkmn.volatiles;

  this.item = pkmn.item;
  this.moveTrack = pkmn.moveTrack;
  this.moves = pkmn.moves;
  this.movestatuses = pkmn.movestatuses;

  this.lastmove = pkmn.lastmove;
  this.slot = pkmn.slot;
  this.fainted = pkmn.fainted;
  this.zerohp = pkmn.zerohp;
  this.turnstatuses = pkmn.turnstatuses;

  this.gender = pkmn.gender;
  this.heightm = pkmn.heightm;
  this.weightkg = pkmn.weightkg;
};

EnnemyPokemon.prototype.getMaxHP = function() {
  return Math.floor((31 + 2 * this.baseStats["hp"] + Math.floor(this.ev["hp"] / 4.0)) * this.level / 100.0 + 10 + this.level);
};

EnnemyPokemon.prototype.getStat = function(stat) {//updates the value of a given stat
  return Math.floor(Math.floor( 31 + 2 * this.baseStats[stat] + Math.floor(this.ev[stat] / 4.0) * this.level / 100.0 + 5) * 1.0);//replace the 1.0 with the nature
};
<|endoftext|>


<commit_before>/**
 * @author: tipe.io
 */

module.exports = function (config) {
  const testWebpackConfig = require('./webpack.test.js')({ env: 'test' });

  const configuration = {

    /**
     * Base path that will be used to resolve all patterns (e.g. files, exclude).
    */
    basePath: '',

    /**
     * Frameworks to use
     *
     * available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     */
    frameworks: ['jasmine'],

    /**
     * List of files to exclude.
    */
    exclude: [],

    client: {
      captureConsole: false
    },

    /**
     * List of files / patterns to load in the browser
     *
     * we are building the test environment in ./spec-bundle.js
     */
    files: [
      { pattern: './config/spec-bundle.js', watched: false },
      { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false }
    ],

    /**
     * By default all assets are served at http://localhost:[PORT]/base/
     */
    proxies: {
      "/assets/": "/base/src/assets/"
    },

    /**
     * Preprocess matching files before serving them to the browser
     * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
     */
    preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

    /**
     * Webpack Config at ./webpack.test.js
     */
    webpack: testWebpackConfig,

    coverageReporter: {
      type: 'in-memory'
    },

    remapCoverageReporter: {
      'text-summary': null,
      json: './coverage/coverage.json',
      html: './coverage/html'
    },

    /**
     * Webpack please don't spam the console when running in karma!
     */
    webpackMiddleware: {
      /**
       * webpack-dev-middleware configuration
       * i.e.
       */
      logLevel: 'warn',
      /**
       * and use stats to turn off verbose output
       */
      stats: {
        /**
         * options i.e.
         */
        chunks: false
      }
    },

    /**
     * Test results reporter to use
     *
     * possible values: 'dots', 'progress'
     * available reporters: https://npmjs.org/browse/keyword/karma-reporter
     */
    reporters: ['mocha', 'coverage', 'remap-coverage'],

    /**
     * Web server port.
     */
    port: 9876,

    /**
     * enable / disable colors in the output (reporters and logs)
     */
    colors: true,

    /**
     * Level of logging
     * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
     */
    logLevel: config.LOG_WARN,

    /**
     * enable / disable watching file and executing tests whenever any file changes
     */
    autoWatch: false,

    /**
     * start these browsers
     * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
     */
    browsers: [
      'Chrome',
      'ChromeTravisCi'
    ],

    customLaunchers: {
      ChromeTravisCi: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox', '--disable-gpu']
      }
    },

    /**
     * Continuous Integration mode
     * if true, Karma captures browsers, runs the tests and exits
     */
    singleRun: true,
    /**
     * For slower machines you may need to have a longer browser
     * wait time . Uncomment the line below if required.
     */
    // browserNoActivityTimeout: 30000

  };

  // Optional Sonar Qube Reporter
  if (process.env.SONAR_QUBE) {

    // SonarQube reporter plugin configuration
    configuration.sonarQubeUnitReporter = {
      sonarQubeVersion: '5.x',
      outputFile: 'reports/ut_report.xml',
      overrideTestDescription: true,
      testPath: 'src/app',
      testFilePattern: '.spec.ts',
      useBrowserName: false
    };

    // Additional lcov format required for
    // sonarqube
    configuration.remapCoverageReporter.lcovonly = './coverage/coverage.lcov';

    configuration.reporters.push('sonarqubeUnit');
  }

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi'
    ];
  }

  config.set(configuration);
};
<commit_msg>Fix to karma reporter reporting twice amount of executed tests (#1996)<commit_after>/**
 * @author: tipe.io
 */

module.exports = function (config) {
  const testWebpackConfig = require('./webpack.test.js')({ env: 'test' });

  const configuration = {

    /**
     * Base path that will be used to resolve all patterns (e.g. files, exclude).
    */
    basePath: '',

    /**
     * Frameworks to use
     *
     * available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     */
    frameworks: ['jasmine'],

    /**
     * List of files to exclude.
    */
    exclude: [],

    client: {
      captureConsole: false
    },

    /**
     * List of files / patterns to load in the browser
     *
     * we are building the test environment in ./spec-bundle.js
     */
    files: [
      { pattern: './config/spec-bundle.js', watched: false },
      { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false }
    ],

    /**
     * By default all assets are served at http://localhost:[PORT]/base/
     */
    proxies: {
      "/assets/": "/base/src/assets/"
    },

    /**
     * Preprocess matching files before serving them to the browser
     * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
     */
    preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] },

    /**
     * Webpack Config at ./webpack.test.js
     */
    webpack: testWebpackConfig,

    coverageReporter: {
      type: 'in-memory'
    },

    remapCoverageReporter: {
      'text-summary': null,
      json: './coverage/coverage.json',
      html: './coverage/html'
    },

    /**
     * Webpack please don't spam the console when running in karma!
     */
    webpackMiddleware: {
      /**
       * webpack-dev-middleware configuration
       * i.e.
       */
      logLevel: 'warn',
      /**
       * and use stats to turn off verbose output
       */
      stats: {
        /**
         * options i.e.
         */
        chunks: false
      }
    },

    /**
     * Test results reporter to use
     *
     * possible values: 'dots', 'progress'
     * available reporters: https://npmjs.org/browse/keyword/karma-reporter
     */
    reporters: ['mocha', 'coverage', 'remap-coverage'],

    /**
     * Web server port.
     */
    port: 9876,

    /**
     * enable / disable colors in the output (reporters and logs)
     */
    colors: true,

    /**
     * Level of logging
     * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
     */
    logLevel: config.LOG_WARN,

    /**
     * enable / disable watching file and executing tests whenever any file changes
     */
    autoWatch: false,

    /**
     * start these browsers
     * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
     */
    browsers: [
      'ChromeTravisCi'
    ],

    customLaunchers: {
      ChromeTravisCi: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox', '--disable-gpu']
      }
    },

    /**
     * Continuous Integration mode
     * if true, Karma captures browsers, runs the tests and exits
     */
    singleRun: true,
    /**
     * For slower machines you may need to have a longer browser
     * wait time . Uncomment the line below if required.
     */
    // browserNoActivityTimeout: 30000

  };

  // Optional Sonar Qube Reporter
  if (process.env.SONAR_QUBE) {

    // SonarQube reporter plugin configuration
    configuration.sonarQubeUnitReporter = {
      sonarQubeVersion: '5.x',
      outputFile: 'reports/ut_report.xml',
      overrideTestDescription: true,
      testPath: 'src/app',
      testFilePattern: '.spec.ts',
      useBrowserName: false
    };

    // Additional lcov format required for
    // sonarqube
    configuration.remapCoverageReporter.lcovonly = './coverage/coverage.lcov';

    configuration.reporters.push('sonarqubeUnit');
  }

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi'
    ];
  }

  config.set(configuration);
};
<|endoftext|>


<commit_before>const path = require('path');

// Karma configuration
module.exports = function(config) {
	config.set({
		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ['mocha', 'sinon-chai'],

		// list of files / patterns to load in the browser
		files: [
			'src/**/*__tests__*/**/*spec.browser.js',
			'src/**/*__tests__*/**/*spec.jsx.js',
			'src/**/*__tests__*/**/*spec.ssr.js',
//			'src/**/*__tests__*/**/*spec.server.js',
		],
		// list of files to exclude
		exclude: [],
		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'src/**/*__tests__*/**/*spec.browser.js': ['webpack'],
			'src/**/*__tests__*/**/*spec.jsx.js': ['webpack'],
			'src/**/*__tests__*/**/*spec.ssr.js': ['webpack'],
//			'src/**/*__tests__*/**/*spec.server.js': ['webpack'],
		},
		webpack: {
			module: {
				postLoaders: [{
					test: /\.js$/,
					exclude: /.git|packages|node_modules\/dist/,
					loader: 'isparta',
					include: path.join(__dirname, '../src')
				}],
				loaders: [{
					test: /\.js$/,
					exclude: /(src\/dist|packages|.git|node_modules)/,
					loader: 'babel-loader'
				}]
			}
		},
		webpackMiddleware: {
			noInfo: true
		},
		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['mocha', 'coverage'],
		// reporter options
		mochaReporter: {
			colors: {
				success: 'green',
				info: 'bgYellow',
				warning: 'cyan',
				error: 'bgRed'
			},
			divider: ''
		},
		coverageReporter: {
			reporters: [{
				type: 'html',
				dir: '../coverage'
			}, {
				type: 'text',
				dir: '../coverage'
			}, {
				type: 'lcov',
				dir: '../coverage'
			}]
		},

		browsers: ['Chrome'],
		// custom launchers
		customLaunchers: {
			Chrome_for_Travis_CI: {
				base: 'Chrome',
				flags: ['--no-sandbox']
			}
		},

		browserDisconnectTimeout: 10000,
		browserDisconnectTolerance: 2,
		// concurrency level how many browser should be started simultaneously
		concurrency: 4,
		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 100000,
		browserNoActivityTimeout: 30000,
		// enable / disable colors in the output (reporters and logs)
		colors: true,
		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,
		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,
		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: true
	});

	if (process.env.TRAVIS) {
		// Use Chrome as default browser for Travis CI
		config.browsers = ['Chrome_for_Travis_CI'];
		// Used by Travis to push coveralls info corretly to example coveralls.io
		config.reporters = ['mocha', 'coverage', 'coveralls'];
		// Karma (with socket.io 1.x) buffers by 50 and 50 tests can take a long time on IEs;-)
		config.browserNoActivityTimeout = 120000;
	}
};
<commit_msg>karma fixes<commit_after>const path = require('path');

// Karma configuration
module.exports = function(config) {
	config.set({
		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ['mocha', 'sinon-chai'],

		// list of files / patterns to load in the browser
		files: [
			'src/**/*__tests__*/**/*spec.browser.js',
			'src/**/*__tests__*/**/*spec.jsx.js',
			'src/**/*__tests__*/**/*spec.ssr.js'
		],
		// list of files to exclude
		exclude: [],
		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'src/**/*__tests__*/**/*spec.browser.js': ['webpack'],
			'src/**/*__tests__*/**/*spec.jsx.js': ['webpack'],
			'src/**/*__tests__*/**/*spec.ssr.js': ['webpack']
		},
		webpack: {
			module: {
				postLoaders: [{
					test: /\.js$/,
					exclude: /(src\/dist|packages|.git|node_modules)/,
					loader: 'isparta',
					include: path.join(__dirname, '../src')
				}],
				loaders: [{
					test: /\.js$/,
					exclude: /(src\/dist|packages|.git|node_modules)/,
					loader: 'babel-loader'
				}]
			}
		},
		webpackMiddleware: {
			noInfo: true
		},
		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['mocha', 'coverage'],
		// reporter options
		mochaReporter: {
			colors: {
				success: 'green',
				info: 'bgYellow',
				warning: 'cyan',
				error: 'bgRed'
			},
			divider: ''
		},
		coverageReporter: {
			reporters: [{
				type: 'html',
				dir: '../coverage'
			}, {
				type: 'text',
				dir: '../coverage'
			}, {
				type: 'lcov',
				dir: '../coverage'
			}]
		},

		browsers: ['Chrome'],
		// custom launchers
		customLaunchers: {
			Chrome_for_Travis_CI: {
				base: 'Chrome',
				flags: ['--no-sandbox']
			}
		},

		browserDisconnectTimeout: 10000,
		browserDisconnectTolerance: 2,
		// concurrency level how many browser should be started simultaneously
		concurrency: 4,
		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 100000,
		browserNoActivityTimeout: 30000,
		// enable / disable colors in the output (reporters and logs)
		colors: true,
		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,
		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,
		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: true
	});

	if (process.env.TRAVIS) {
		// Use Chrome as default browser for Travis CI
		config.browsers = ['Chrome_for_Travis_CI'];
		// Used by Travis to push coveralls info corretly to example coveralls.io
		config.reporters = ['mocha', 'coverage', 'coveralls'];
		// Karma (with socket.io 1.x) buffers by 50 and 50 tests can take a long time on IEs;-)
		config.browserNoActivityTimeout = 120000;
	}
};
<|endoftext|>


<commit_before>/*
maria-NodeModel version 1.0.0-beta.2
Copyright (c) 2013, Peter Michaux
All rights reserved.
Licensed under the Simplified BSD License.
https://github.com/petermichaux/maria-NodeModel/blob/master/LICENSE
*/
<commit_msg>Heading towards a new version. Increment version number.<commit_after>/*
maria-NodeModel version 1.0.0-beta.3
Copyright (c) 2013, Peter Michaux
All rights reserved.
Licensed under the Simplified BSD License.
https://github.com/petermichaux/maria-NodeModel/blob/master/LICENSE
*/
<|endoftext|>