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

  // bc.vc, shortcut, dirty hack
  $.register({
    rule: {
      host: /^bc\.vc$/,
      query: /^.+(https?:\/\/.+)/,
    },
    start: function (m) {
      $.openLink(m.query[1]);
    },
  });

  // bc.vc, shortcut
  // FIXME may cut hash or query string
  $.register({
    rule: {
      host: /^bc\.vc$/,
      path: /^.+(https?:\/\/.+)$/,
    },
    start: function (m) {
      $.openLink(m.path[1]);
    },
  });

  function searchScript () {
      var content = $.$$('script').find(function (script) {
        return script.innerHTML.indexOf('make_log') >= 0;
      });
      return content.innerHTML;
  }

  function knockServer (script, dirtyFix) {
    var matches = script.match(/\$.post\('([^']*)'[^{]+(\{opt:'make_log'[^}]+\}\}),/i);
    var make_url = matches[1];
    var make_opts = eval('(' + matches[2] + ')');

    var i = setInterval(function () {
      $.post(make_url, make_opts, function (text) {
        if (dirtyFix) {
          // dirty fix for tr5.in
          text = text.match(/\{.+\}/)[0];
        }
        var jj = JSON.parse(text);
        if (jj.message) {
          clearInterval(i);
          $.openLink(jj.message.url);
        }
      });
    }, 1000);
  }

  // bc.vc
  $.register({
    rule: {
      host: /^bc\.vc$/,
      path: /^\/.+/,
    },
    ready: function () {
      $.removeNodes('iframe');

      var content = searchScript();

      knockServer(content);
    },
  });

  function run () {
    // prevent redirection by iframe
    $.removeNodes('iframe');

    var content = searchScript();
    var matches = content.match(/eval(.*)/);
    matches = matches[1];
    content = eval(matches);

    knockServer(content);
  }

  // adli.pw
  $.register({
    rule: {
      host: /^adli\.pw$/,
      path: /^\/[^.]+$/,
    },
    ready: run,
  });

  $.register({
    rule: {
      host: /^adcrun\.ch|(youlinking|fly2url|raksoyun)\.com|(zpoz|ultry)\.net|wwy\.me|(ssl|adfro)\.gs|link\.tl|bih\.cc|xip\.ir|www\.budurl\.ru|juuh\.de|www\.adjet\.eu|1y\.lt$/,
      path: /^\/.+/,
    },
    ready: run,
  });

  $.register({
    rule: {
      host: /^tr5\.in$/,
      path: /^\/.+/,
    },
    ready: function () {
      $.removeNodes('iframe');

      var content = searchScript();
      var matches = content.match(/eval(.*)/);
      matches = matches[1];
      content = eval(matches);

      knockServer(content, true);
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>hit.us<commit_after>(function () {
  'use strict';

  // bc.vc, shortcut, dirty hack
  $.register({
    rule: {
      host: /^bc\.vc$/,
      query: /^.+(https?:\/\/.+)/,
    },
    start: function (m) {
      $.openLink(m.query[1]);
    },
  });

  // bc.vc, shortcut
  // FIXME may cut hash or query string
  $.register({
    rule: {
      host: /^bc\.vc$/,
      path: /^.+(https?:\/\/.+)$/,
    },
    start: function (m) {
      $.openLink(m.path[1]);
    },
  });

  function searchScript () {
      var content = $.$$('script').find(function (script) {
        return script.innerHTML.indexOf('make_log') >= 0;
      });
      return content.innerHTML;
  }

  function knockServer (script, dirtyFix) {
    var matches = script.match(/\$.post\('([^']*)'[^{]+(\{opt:'make_log'[^}]+\}\}),/i);
    var make_url = matches[1];
    var make_opts = eval('(' + matches[2] + ')');

    var i = setInterval(function () {
      $.post(make_url, make_opts, function (text) {
        if (dirtyFix) {
          // dirty fix for tr5.in
          text = text.match(/\{.+\}/)[0];
        }
        var jj = JSON.parse(text);
        if (jj.message) {
          clearInterval(i);
          $.openLink(jj.message.url);
        }
      });
    }, 1000);
  }

  // bc.vc
  $.register({
    rule: {
      host: /^bc\.vc$/,
      path: /^\/.+/,
    },
    ready: function () {
      $.removeNodes('iframe');

      var content = searchScript();

      knockServer(content);
    },
  });

  function run () {
    // prevent redirection by iframe
    $.removeNodes('iframe');

    var content = searchScript();
    var matches = content.match(/eval(.*)/);
    matches = matches[1];
    content = eval(matches);

    knockServer(content);
  }

  // adli.pw
  $.register({
    rule: {
      host: /^adli\.pw$/,
      path: /^\/[^.]+$/,
    },
    ready: run,
  });

  $.register({
    rule: {
      host: /^adcrun\.ch|(youlinking|fly2url|raksoyun)\.com|(zpoz|ultry)\.net|wwy\.me|(ssl|adfro)\.gs|link\.tl|bih\.cc|xip\.ir|www\.budurl\.ru|juuh\.de|www\.adjet\.eu|1y\.lt|hit\.us$/,
      path: /^\/.+/,
    },
    ready: run,
  });

  $.register({
    rule: {
      host: /^tr5\.in$/,
      path: /^\/.+/,
    },
    ready: function () {
      $.removeNodes('iframe');

      var content = searchScript();
      var matches = content.match(/eval(.*)/);
      matches = matches[1];
      content = eval(matches);

      knockServer(content, true);
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>{
  let route = {
    register: () => {

    },
    default : () => {

    }
  };

  window.addEventListener('popstate', (event) => {
    console.log('event', event);
  });

  window.addEventListener('hashchange',() => {
    console.log('event', event);

  })

  sixth.route = route;
}<commit_msg>routing war in progress<commit_after>{

  class Route {
    construtor() {
      this.routes = [];
      this.root = '/';
      this.html5Mode = false;
      this.default = {};

      window.addEventListener('popstate', (event) => {
        console.log('event', event);
      });

      window.addEventListener('hashchange', () => {
        console.log('event', event);

      });
    };

    config(options = {}) {
      this.html5Mode = !!options.html5Mode;
      this.root = options.root
        ? `/${this.clearSlashes(options.root)}/`
        : '/';

      return this;
    }

    clearSlases(path) {
      return path.toString()
        .replace(/\/$/, '')
        .replace(/^\//, '');
    }

    register(state = {}) {
      this.routes.push(state);

      return this;
    }

    default(state = {}){
      this.default = state;

      return this;
    }

  }

  //TODO Look on this address
  // http://krasimirtsonev.com/blog/article/A-modern-JavaScript-router-in-100-lines-history-api-pushState-hash-url

  sixth.route = route;
}<|endoftext|>


<commit_before>/* globals __DEV__ */
import Phaser from 'phaser'
import config from '../config'
import { makeGreen } from '../utils'
import _ from 'lodash'

export default class extends Phaser.State {
	init() {
		this.years = 11
		this.startYear = 2007
	}

	preload() {
	}

	create() {
		this.map = this.game.add.tilemap('liip')
		this.map.addTilesetImage('tiles_spritesheet', 'gameTiles')
		this.mapWidthInPixels = this.map.widthInPixels;

		// create layers
		this.backgroundLayer = this.map.createLayer('backgroundLayer')
		this.blockedLayer = this.map.createLayer('blockedLayer')
		this.map.setCollisionBetween(1, 100000, true, 'blockedLayer')
		this.backgroundLayer.resizeWorld()

		this.logo = this.game.add.sprite(20, 35, 'liipLogo')
		this.logo.scale.setTo(0.2)
		this.logo.fixedToCamera = true

		// setup player
		this.player = this.game.add.sprite(0, 250, 'player')
		this.game.physics.arcade.enable(this.player)
		this.player.body.gravity.y = config.player.weight
		this.game.camera.follow(this.player)

		// score
		this.scoreLabel = this.game.add.text(config.gameWidth - 70, 30, '0', makeGreen(config.text.xl))
		this.scoreLabel.fixedToCamera = true

		// current position
		this.positionLabel = this.game.add.text(0, 0, '2007', Object.assign(config.text.xl, ({ boundsAlignH: "center" })))
		this.positionLabel.setTextBounds(0, 30, config.gameWidth, 30);
		this.positionLabel.fixedToCamera = true

		// init keys
		this.keys = this.game.input.keyboard.addKeys({
			space: Phaser.KeyCode.SPACEBAR,
			down: Phaser.KeyCode.DOWN
		})

		let playerDuckImg = this.game.cache.getImage('playerDuck')
		this.player.duckedDimensions = {width: playerDuckImg.width, height: playerDuckImg.height}
		this.player.standDimensions = {width: this.player.width, height: this.player.height}
		this.player.anchor.setTo(0.5, 1)

		// make the player move sideways continuously
		this.player.body.velocity.x = config.player.speed

		// load sounds
		this.soundCoin = this.game.add.audio('coin')
		this.soundOuch = this.game.add.audio('ouch')
		this.soundJump = this.game.add.audio('jump')

		// add objects
		this.createBeers();
		this.createAwards();
	}

	update() {
		this.game.physics.arcade.collide(this.player, this.blockedLayer, this.playerHit, null, this)

		if(this.player.alive) {
			if (this.keys.space.isDown) {
				this.playerJump()
			} else if (this.keys.down.isDown) {
				this.playerDuck()
			}

			this.updateScore(5)

			if (!this.keys.down.isDown && this.player.isDucked) {
				// change image and update the body size for the physics engine
				this.player.loadTexture('player')
				this.player.body.setSize(this.player.standDimensions.width, this.player.standDimensions.height)
				this.player.isDucked = false
			}

			// Update position label depending on the position of the player
			this.positionLabel.text = this.getCurrentYear(this.player.x);
		}

		// make obejects collectable
		this.game.physics.arcade.overlap(this.player, this.beers, this.collect, null, this);
		this.game.physics.arcade.overlap(this.player, this.awards, this.collect, null, this);

		// restart the game if reaching the edge
		if (this.player.x >= this.game.world.width) {
			this.game.time.events.add(1500, this.restart, this)
		}
	}

	getCurrentYear(playerPositionX) {
		const pixelsPerYear = this.mapWidthInPixels / this.years
		let relativeYear = Math.floor(playerPositionX / pixelsPerYear);
		if(relativeYear > this.years - 1) {
			relativeYear = this.years - 1;
		}
		return this.startYear + relativeYear;
	}

	gameOver() {
		this.game.state.start('HighScore')
	}

	restart() {
		this.game.state.start('Game')
	}

	playerJump() {
		if (this.player.body.blocked.down) {
			this.soundJump.play()
			this.player.body.velocity.y -= 900
		}
	}

	playerDuck() {
		//change image and update the body size for the physics engine
		this.player.loadTexture('playerDuck')
		this.player.body.setSize(this.player.duckedDimensions.width, this.player.duckedDimensions.height)
		//we use this to keep track whether it's ducked or not
		this.player.isDucked = true
	}

	playerHit(player, blockedLayer) {
		this.game.physics.arcade.collide(this.player, this.blockedLayer)

		if (player.body.blocked.right) {
			this.soundOuch.play()
			// set to dead (this doesn't affect rendering)
			this.player.alive = false
			// stop moving to the right
			this.player.body.velocity.x = 0
			// change sprite image
			this.player.loadTexture('playerDead')
			// go to gameover after a few miliseconds
			this.game.time.events.add(1500, this.gameOver, this)
		}
	}

	updateScore (newScore) {
		// this.score = newScore
		let score = parseInt(this.scoreLabel.text, 10) + newScore
		this.scoreLabel.text = score
	}

	findObjectsByType(type, map, layerName) {
		return _
			.chain(map.objects[layerName])
			.filter(element => element.properties.type === type)
			.map((element) => {
				element.y -= map.tileHeight
				return element
			})
			.value()
	}

	createFromTiledObject(element, group) {
		let sprite = group.create(element.x, element.y, element.properties.sprite)
		// copy all properties to the sprite
		Object.keys(element.properties).forEach(key => {
			sprite[key] = element.properties[key]
		})
	}

	createBeers() {
		this.beers = this.game.add.group();
		this.beers.enableBody = true;
		let result = this.findObjectsByType('beer', this.map, 'objectsLayer');

		result.forEach((element) => {
			this.createFromTiledObject(element, this.beers)
		})
	}

	createAwards() {
		this.awards = this.game.add.group()
		this.awards.enableBody = true
		let result = this.findObjectsByType('award', this.map, 'objectsLayer')

		result.forEach((element) => {
			this.createFromTiledObject(element, this.awards)
		})
	}

	collect(player, collectable) {
		// play audio
		this.soundCoin.play()
		// remove sprite
		collectable.destroy()
	}

	render() {
	}
}
<commit_msg>game over when you finish level<commit_after>/* globals __DEV__ */
import Phaser from 'phaser'
import config from '../config'
import {makeGreen} from '../utils'
import _ from 'lodash'

export default class extends Phaser.State {
	init() {
		this.years = 11
		this.startYear = 2007
	}

	preload() {
	}

	create() {
		this.map = this.game.add.tilemap('liip')
		this.map.addTilesetImage('tiles_spritesheet', 'gameTiles')
		this.mapWidthInPixels = this.map.widthInPixels;

		// create layers
		this.backgroundLayer = this.map.createLayer('backgroundLayer')
		this.blockedLayer = this.map.createLayer('blockedLayer')
		this.map.setCollisionBetween(1, 100000, true, 'blockedLayer')
		this.backgroundLayer.resizeWorld()

		this.logo = this.game.add.sprite(20, 35, 'liipLogo')
		this.logo.scale.setTo(0.2)
		this.logo.fixedToCamera = true

		// setup player
		this.player = this.game.add.sprite(0, 250, 'player')
		this.game.physics.arcade.enable(this.player)
		this.player.body.gravity.y = config.player.weight
		this.game.camera.follow(this.player)

		// score
		this.scoreLabel = this.game.add.text(config.gameWidth - 70, 30, '0', makeGreen(config.text.xl))
		this.scoreLabel.fixedToCamera = true

		// current position
		this.positionLabel = this.game.add.text(0, 0, '2007', Object.assign(config.text.xl, ({boundsAlignH: "center"})))
		this.positionLabel.setTextBounds(0, 30, config.gameWidth, 30);
		this.positionLabel.fixedToCamera = true

		// init keys
		this.keys = this.game.input.keyboard.addKeys({
			space: Phaser.KeyCode.SPACEBAR,
			down: Phaser.KeyCode.DOWN
		})

		let playerDuckImg = this.game.cache.getImage('playerDuck')
		this.player.duckedDimensions = {width: playerDuckImg.width, height: playerDuckImg.height}
		this.player.standDimensions = {width: this.player.width, height: this.player.height}
		this.player.anchor.setTo(0.5, 1)

		// make the player move sideways continuously
		this.player.body.velocity.x = config.player.speed

		// load sounds
		this.soundCoin = this.game.add.audio('coin')
		this.soundOuch = this.game.add.audio('ouch')
		this.soundJump = this.game.add.audio('jump')

		// add objects
		this.createBeers()
		this.createAwards()
	}

	update() {
		this.game.physics.arcade.collide(this.player, this.blockedLayer, this.playerHit, null, this)

		if (this.player.alive) {
			if (this.keys.space.isDown) {
				this.playerJump()
			} else if (this.keys.down.isDown) {
				this.playerDuck()
			}

			this.updateScore(5)

			if (!this.keys.down.isDown && this.player.isDucked) {
				// change image and update the body size for the physics engine
				this.player.loadTexture('player')
				this.player.body.setSize(this.player.standDimensions.width, this.player.standDimensions.height)
				this.player.isDucked = false
			}

			// Update position label depending on the position of the player
			this.positionLabel.text = this.getCurrentYear(this.player.x)
		}

		// make obejects collectable
		this.game.physics.arcade.overlap(this.player, this.beers, this.collect, null, this);
		this.game.physics.arcade.overlap(this.player, this.awards, this.collect, null, this);

		// restart the game if reaching the edge
		if (this.player.x >= this.game.world.width) {
			this.game.time.events.add(1500, this.gameOver, this)
		}
	}

	getCurrentYear(playerPositionX) {
		const pixelsPerYear = this.mapWidthInPixels / this.years
		let relativeYear = Math.floor(playerPositionX / pixelsPerYear)
		if (relativeYear > this.years - 1) {
			relativeYear = this.years - 1
		}
		return this.startYear + relativeYear
	}

	gameOver() {
		this.game.state.start('HighScore')
	}

	restart() {
		this.game.state.start('Game')
	}

	playerJump() {
		if (this.player.body.blocked.down) {
			this.soundJump.play()
			this.player.body.velocity.y -= 900
		}
	}

	playerDuck() {
		//change image and update the body size for the physics engine
		this.player.loadTexture('playerDuck')
		this.player.body.setSize(this.player.duckedDimensions.width, this.player.duckedDimensions.height)
		//we use this to keep track whether it's ducked or not
		this.player.isDucked = true
	}

	playerHit(player, blockedLayer) {
		this.game.physics.arcade.collide(this.player, this.blockedLayer)

		if (player.body.blocked.right) {
			this.soundOuch.play()
			// set to dead (this doesn't affect rendering)
			this.player.alive = false
			// stop moving to the right
			this.player.body.velocity.x = 0
			// change sprite image
			this.player.loadTexture('playerDead')
			// go to gameover after a few miliseconds
			this.game.time.events.add(1500, this.gameOver, this)
		}
		console.log(player, blockedLayer)
	}

	updateScore(newScore) {
		// this.score = newScore
		let score = parseInt(this.scoreLabel.text, 10) + newScore
		this.scoreLabel.text = score
	}

	findObjectsByType(type, map, layerName) {
		return _
			.chain(map.objects[layerName])
			.filter(element => element.properties.type === type)
			.map((element) => {
				element.y -= map.tileHeight
				return element
			})
			.value()
	}

	createFromTiledObject(element, group) {
		let sprite = group.create(element.x, element.y, element.properties.sprite)
		// copy all properties to the sprite
		Object.keys(element.properties).forEach(key => {
			sprite[key] = element.properties[key]
		})
	}

	createBeers() {
		this.beers = this.game.add.group();
		this.beers.enableBody = true;
		let result = this.findObjectsByType('beer', this.map, 'objectsLayer');

		result.forEach((element) => {
			this.createFromTiledObject(element, this.beers)
		})
	}

	createAwards() {
		this.awards = this.game.add.group()
		this.awards.enableBody = true
		let result = this.findObjectsByType('award', this.map, 'objectsLayer')

		result.forEach((element) => {
			this.createFromTiledObject(element, this.awards)
		})
	}

	collect(player, collectable) {
		// play audio
		this.soundCoin.play()
		// remove sprite
		collectable.destroy()
	}

	render() {
	}
}
<|endoftext|>


<commit_before>/**
 *   Copyright 2017 OSBI Ltd
 *
 *   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.
 */

import { createStore, compose } from 'redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';
import rootReducer from '../reducers/index';

const defaultState = {
  filter: ''
};

const enhancers = compose(
  window.devToolsExtension ? window.devToolsExtension() : f => f
);

const store = createStore(rootReducer, defaultState, enhancers);

export const history = syncHistoryWithStore(browserHistory, store);

export default store;
<commit_msg>SREP-3 #comment browserHistory does not work on production<commit_after>/**
 *   Copyright 2017 OSBI Ltd
 *
 *   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.
 */

import { createStore, compose } from 'redux';
import { syncHistoryWithStore } from 'react-router-redux';
// `browserHistory` does not work on production
// this code will be commented on temporarily
// import { browserHistory } from 'react-router';
import { hashHistory } from 'react-router';
import rootReducer from '../reducers/index';

const defaultState = {
  filter: ''
};

const enhancers = compose(
  window.devToolsExtension ? window.devToolsExtension() : f => f
);

const store = createStore(rootReducer, defaultState, enhancers);

// export const history = syncHistoryWithStore(browserHistory, store);
export const history = syncHistoryWithStore(hashHistory, store);

export default store;
<|endoftext|>


<commit_before>// vendor
import { EventEmitter } from 'events';
import { Promise } from 'es6-promise';

// setting
import setting from '../setting';

const LIST_API_URL = `https://api.github.com/repos/${setting.config.repo}/contents/${setting.config.path}?ref=${setting.config.branch}`;
const POST_API_URL = `https://raw.githubusercontent.com/${setting.config.repo}/${setting.config.branch}/${setting.config.path}`;

let store = new EventEmitter();

export default store;

/**
 * fetch post content from github
 *
 * @param title
 * @returns {Promise}
 */
store.getPost = (title) => {
    return new Promise((resolve, reject) => {

        const xhr = new XMLHttpRequest();

        xhr.open('GET', `${POST_API_URL}/${title}`);
        xhr.onload = () => {
            const resText = xhr.responseText;
            resolve(resText);
        };
        xhr.onerror = () => reject;
        xhr.send();

    });
}

/**
 * fetch the list from cache or from github api
 *
 * @todo paginate not yet
 *
 * @param page
 * @returns {Promise}
 */
store.getListByPage = (page = 1) => {
    return new Promise((resolve, reject) => {

        if (sessionStorage.getItem('posts')) {

            // read data from cache
            resolve(JSON.parse(sessionStorage.posts));

        } else {

            const xhr = new XMLHttpRequest();

            xhr.open('GET', LIST_API_URL);
            xhr.onload = () => {
                const resJson = xhr.responseText;
                // caching
                sessionStorage.setItem('posts', resJson);

                resolve(JSON.parse(resJson));
            };
            xhr.onerror = () => reject;
            xhr.send();

        }

    });

}
<commit_msg>update<commit_after>// vendor
import { EventEmitter } from 'events';
import { Promise } from 'es6-promise';

// setting
import setting from '../setting';

const LIST_API_URL = `https://api.github.com/repos/${setting.config.repo}/contents/${setting.config.path}?ref=${setting.config.branch}`;
const POST_API_URL = `https://raw.githubusercontent.com/${setting.config.repo}/${setting.config.branch}/${setting.config.path}`;

let store = new EventEmitter();

export default store;

/**
 * fetch post content from github
 *
 * @param title
 * @returns {Promise}
 */
store.getPost = (title) => {
    return new Promise((resolve, reject) => {

        const xhr = new XMLHttpRequest();

        xhr.open('GET', `${POST_API_URL}/${title}`);
        xhr.onload = () => {
            const resText = xhr.responseText;
            resolve(resText);
        };
        xhr.onerror = () => reject;
        xhr.send();

    });
}

/**
 * fetch the list from cache or from github api
 *
 * @todo paginate not yet
 *
 * @param page
 * @returns {Promise}
 */
store.getListByPage = (page = 1) => {
    return new Promise((resolve, reject) => {

        if (sessionStorage.getItem('posts')) {

            // read data from cache
            // resolve(JSON.parse(sessionStorage.posts));

        } else {

            const xhr = new XMLHttpRequest();

            xhr.open('GET', LIST_API_URL);
            xhr.onload = () => {
                const resJson = xhr.responseText;
                // caching
                sessionStorage.setItem('posts', resJson);

                resolve(JSON.parse(resJson));
            };
            xhr.onerror = () => reject;
            xhr.send();

        }

    });

}
<|endoftext|>


<commit_before>var dgram = require('dgram')
var events = require('events')
var util = require('util')
var Q = require('q')
var winston = require('winston')

var Packet = require('./packet')

// Init socket object
var StunSocket = function (stunHost, stunPort, udpSocket) {
  if (stunPort === undefined || stunHost === undefined) {
    var error = '[libstun] invalid socket params'
    winston.error(error)
    throw new Error(error)
  }
  this._stunPort = stunPort
  this._stunHost = stunHost

  this._responseCallbacks = {}

  events.EventEmitter.call(this)

  var socket = (udpSocket === undefined) ? dgram.createSocket('udp4') : udpSocket
  this._socket = socket
  socket.on('message', this.onIncomingMessage())
  socket.on('error', this.onFailure())
}

// Inherit EventEmitter
util.inherits(StunSocket, events.EventEmitter)

// Open socket
StunSocket.prototype.listenP = function (args) {
  var deferred = Q.defer()
  args = args | {}
  var self = this
  this._socket.bind(args.address, args.port, function () {
    var listeningAddress = self._socket.address()
    winston.debug('[libstun] socket listening ' + listeningAddress.address + ':' + listeningAddress.port)
    deferred.resolve(listeningAddress)
  })
  return deferred.promise
}

StunSocket.prototype.listen = function (args, onSuccess, onFailure) {
  args = args | {}
  if (onSuccess === undefined || onFailure === undefined) {
    var error = '[libstun] listen callback handlers are undefined'
    winston.error(error)
    throw new Error(error)
  }
  this.listenP(args)
    .then(function (result) {
      onSuccess(result)
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Close socket
StunSocket.prototype.close = function () {
  var listeningAddress = this._socket.address()
  winston.debug('[libstun] closing socket ' + listeningAddress.address + ':' + listeningAddress.port)
  this._socket.close()
}

/** UDP communication */

// Send STUN request
StunSocket.prototype.sendStunRequestP = function (message) {
  var deferred = Q.defer()
  // get tid
  var tid = message.readUInt32BE(16)
  // store response handler for this tid
  var onResponse = function (stunPacket) {
    deferred.resolve(stunPacket)
  }
  this._responseCallbacks[tid] = onResponse
  // send bytes
  this.send(
    message,
    this._stunHost,
    this._stunPort,
    function () { // on success
      // do nothing
    },
    function (error) { // on failure
      deferred.reject(error)
    }
  )
  return deferred.promise
}

StunSocket.prototype.sendStunRequest = function (message, onSuccess, onFailure) {
  this.sendStunRequestP(message)
    .then(function (result) {
      onSuccess(result)
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Send STUN indication
StunSocket.prototype.sendStunIndicationP = function (message) {
  return this.sendP(message, this._stunHost, this._stunPort)
}

StunSocket.prototype.sendStunIndication = function (message, onSuccess, onFailure) {
  if (onSuccess === undefined || onFailure === undefined) {
    var error = '[libstun] send stun indication callback handlers are undefined'
    winston.error(error)
    throw new Error(error)
  }
  this.sendStunIndicationP(message)
    .then(function (result) {
      onSuccess(result)
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Send bytes
StunSocket.prototype.sendP = function (bytes, host, port) {
  var deferred = Q.defer()
  this._socket.send(bytes, 0, bytes.length, port, host, function (error) {
    if (error) {
      var errorMsg = '[libstun] could not send bytes to ' + host + ':' + port + '. ' + error
      winston.error(errorMsg)
      deferred.reject(errorMsg)
    } else {
      deferred.resolve()
    }
  })
  return deferred.promise
}

StunSocket.prototype.send = function (bytes, host, port, onSuccess, onFailure) {
  if (onSuccess === undefined || onFailure === undefined) {
    var error = '[libstun] send bytes callback handlers are undefined'
    winston.error(error)
    throw new Error(error)
  }
  this.sendP(bytes, host, port)
    .then(function () {
      onSuccess()
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Incoming message handler
StunSocket.prototype.onIncomingMessage = function () {
  var self = this
  return function (bytes, rinfo) {
    winston.debug('[libstun] receiving message from ' + JSON.stringify(rinfo))

    // this is a stun packet
    var stunPacket = Packet.decode(bytes)
    if (stunPacket) {
      switch (stunPacket.type) {
        case Packet.TYPE.SUCCESS_RESPONSE:
          self.onIncomingStunResponse(stunPacket, rinfo)
          break
        case Packet.TYPE.ERROR_RESPONSE:
          self.onIncomingStunResponse(stunPacket, rinfo)
          break
        case Packet.TYPE.INDICATION:
          self.onIncomingStunIndication(stunPacket, rinfo)
          break
        default:
          var errorMsg = "[libstun] don't know how to process incoming STUN message -- dropping it on the floor"
          winston.error(errorMsg)
          throw new Error(errorMsg)
      }
    } else {
      self.onOtherIncomingMessage(bytes, rinfo)
    }
  }
}

// Incoming STUN reply
StunSocket.prototype.onIncomingStunResponse = function (stunPacket, rinfo) {
  // this is a stun reply
  var onResponseCallback = this._responseCallbacks[stunPacket.tid]
  if (onResponseCallback) {
    onResponseCallback(stunPacket)
    delete this._responseCallbacks[stunPacket.tid]
  } else {
    var errorMsg = '[libstun] no handler available to process response with tid ' + stunPacket.tid
    winston.error(errorMsg)
    throw new Error(errorMsg)
  }
}

// Incoming STUN indication
StunSocket.prototype.onIncomingStunIndication = function (stunPacket, rinfo) {
  this.emit('indication', stunPacket, rinfo)
}

// Incoming message that is different from regular STUN packets
StunSocket.prototype.onOtherIncomingMessage = function (bytes, rinfo) {
  this.emit('message', bytes, rinfo)
}

// Error handler
StunSocket.prototype.onFailure = function () {
  return function (error) {
    var errorMsg = '[libstun] socket error: ' + error
    winston.error(errorMsg)
    throw new Error(errorMsg)
  }
}

module.exports = StunSocket
<commit_msg>minor update<commit_after>var dgram = require('dgram')
var events = require('events')
var util = require('util')
var Q = require('q')
var winston = require('winston')

var Packet = require('./packet')

// Init socket object
var StunSocket = function (stunHost, stunPort, udpSocket) {
  if (stunPort === undefined || stunHost === undefined) {
    var error = '[libstun] invalid socket params'
    winston.error(error)
    throw new Error(error)
  }
  this._stunPort = stunPort
  this._stunHost = stunHost

  this._responseCallbacks = {}

  events.EventEmitter.call(this)

  var socket = (udpSocket === undefined) ? dgram.createSocket('udp4') : udpSocket
  this._socket = socket
  socket.on('message', this.onIncomingMessage())
  socket.on('error', this.onFailure())
}

// Inherit EventEmitter
util.inherits(StunSocket, events.EventEmitter)

// Open socket
StunSocket.prototype.listenP = function (args) {
  var deferred = Q.defer()
  args = args | {}
  var self = this
  this._socket.bind(args.address, args.port, function () {
    var listeningAddress = self._socket.address()
    winston.debug('[libstun] socket listening ' + listeningAddress.address + ':' + listeningAddress.port)
    deferred.resolve(listeningAddress)
  })
  return deferred.promise
}

StunSocket.prototype.listen = function (args, onSuccess, onFailure) {
  args = args | {}
  if (onSuccess === undefined || onFailure === undefined) {
    var error = '[libstun] listen callback handlers are undefined'
    winston.error(error)
    throw new Error(error)
  }
  this.listenP(args)
    .then(function (result) {
      onSuccess(result)
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Close socket
StunSocket.prototype.close = function () {
  var listeningAddress = this._socket.address()
  winston.debug('[libstun] closing socket ' + listeningAddress.address + ':' + listeningAddress.port)
  this._socket.close()
}

/** UDP communication */

// Send STUN request
StunSocket.prototype.sendStunRequestP = function (bytes) {
  var deferred = Q.defer()
  // get tid
  var tid = bytes.readUInt32BE(16)
  // store response handler for this tid
  var onResponse = function (stunPacket) {
    deferred.resolve(stunPacket)
  }
  this._responseCallbacks[tid] = onResponse
  // send bytes
  this.send(
    bytes,
    this._stunHost,
    this._stunPort,
    function () { // on success
      // do nothing
    },
    function (error) { // on failure
      deferred.reject(error)
    }
  )
  return deferred.promise
}

StunSocket.prototype.sendStunRequest = function (bytes, onSuccess, onFailure) {
  this.sendStunRequestP(bytes)
    .then(function (result) {
      onSuccess(result)
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Send STUN indication
StunSocket.prototype.sendStunIndicationP = function (bytes) {
  return this.sendP(bytes, this._stunHost, this._stunPort)
}

StunSocket.prototype.sendStunIndication = function (bytes, onSuccess, onFailure) {
  if (onSuccess === undefined || onFailure === undefined) {
    var error = '[libstun] send stun indication callback handlers are undefined'
    winston.error(error)
    throw new Error(error)
  }
  this.sendStunIndicationP(bytes)
    .then(function (result) {
      onSuccess(result)
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Send bytes
StunSocket.prototype.sendP = function (bytes, host, port) {
  var deferred = Q.defer()
  this._socket.send(bytes, 0, bytes.length, port, host, function (error) {
    if (error) {
      var errorMsg = '[libstun] could not send bytes to ' + host + ':' + port + '. ' + error
      winston.error(errorMsg)
      deferred.reject(errorMsg)
    } else {
      deferred.resolve()
    }
  })
  return deferred.promise
}

StunSocket.prototype.send = function (bytes, host, port, onSuccess, onFailure) {
  if (onSuccess === undefined || onFailure === undefined) {
    var error = '[libstun] send bytes callback handlers are undefined'
    winston.error(error)
    throw new Error(error)
  }
  this.sendP(bytes, host, port)
    .then(function () {
      onSuccess()
    })
    .catch(function (error) {
      onFailure(error)
    })
}

// Incoming message handler
StunSocket.prototype.onIncomingMessage = function () {
  var self = this
  return function (bytes, rinfo) {
    winston.debug('[libstun] receiving message from ' + JSON.stringify(rinfo))

    // this is a stun packet
    var stunPacket = Packet.decode(bytes)
    if (stunPacket) {
      switch (stunPacket.type) {
        case Packet.TYPE.SUCCESS_RESPONSE:
          self.onIncomingStunResponse(stunPacket, rinfo)
          break
        case Packet.TYPE.ERROR_RESPONSE:
          self.onIncomingStunResponse(stunPacket, rinfo)
          break
        case Packet.TYPE.INDICATION:
          self.onIncomingStunIndication(stunPacket, rinfo)
          break
        default:
          var errorMsg = "[libstun] don't know how to process incoming STUN message -- dropping it on the floor"
          winston.error(errorMsg)
          throw new Error(errorMsg)
      }
    } else {
      self.onOtherIncomingMessage(bytes, rinfo)
    }
  }
}

// Incoming STUN reply
StunSocket.prototype.onIncomingStunResponse = function (stunPacket, rinfo) {
  // this is a stun reply
  var onResponseCallback = this._responseCallbacks[stunPacket.tid]
  if (onResponseCallback) {
    onResponseCallback(stunPacket)
    delete this._responseCallbacks[stunPacket.tid]
  } else {
    var errorMsg = '[libstun] no handler available to process response with tid ' + stunPacket.tid
    winston.error(errorMsg)
    throw new Error(errorMsg)
  }
}

// Incoming STUN indication
StunSocket.prototype.onIncomingStunIndication = function (stunPacket, rinfo) {
  this.emit('indication', stunPacket, rinfo)
}

// Incoming message that is different from regular STUN packets
StunSocket.prototype.onOtherIncomingMessage = function (bytes, rinfo) {
  this.emit('message', bytes, rinfo)
}

// Error handler
StunSocket.prototype.onFailure = function () {
  return function (error) {
    var errorMsg = '[libstun] socket error: ' + error
    winston.error(errorMsg)
    throw new Error(errorMsg)
  }
}

module.exports = StunSocket
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { View, Flex } from '../flex'
import { Table, TableHeader, TableHeaderContents, TableRow, TableCell, TableFooter } from './styles'

const { element, string, arrayOf, oneOf, shape, number, object } = PropTypes

const FlexTable = ({ HeaderContents, Footer, EmptyState, columns, rows }) =>

    <View column>
      <TableHeader>
        <View column>
          {HeaderContents &&
            <TableHeaderContents>
              {HeaderContents}
            </TableHeaderContents>
          }

            <TableRow>
              <View>
                {columns.map(({ label, flex }) =>
                  <Flex flex={flex}>
                    <TableCell>{label}</TableCell>
                  </Flex>
                )}
              </View>
            </TableRow>

        </View>
      </TableHeader>
      <Flex scroll>
        {rows && rows.length ? rows.map(({ rowProps = {}, rowCells, rowElement }) =>
          <TableRow {...rowProps}>
            <View>
              {rowCells && rowCells.map((el, i) =>
                <Flex flex={columns[i].flex}>
                  <TableCell>{el}</TableCell>
                </Flex>
              )}
            </View>
            <View>
              {rowElement}
            </View>
          </TableRow>
        ) : EmptyState}
      </Flex>
      <TableFooter>
        {Footer}
      </TableFooter>
    </View>

FlexTable.propTypes = {
  HeaderContents: element,
  Footer: element,
  EmptyState: element,
  columns: arrayOf(shape({
    label: string,
    flex: oneOf([number, string])
  })),
  rowProps: object,
  rows: shape({
    rowCells: arrayOf(element),
    rowElement: element,
    rowProps: object
  })
}

export default FlexTable
<commit_msg>Fix FlexTable props<commit_after>import React, { PropTypes } from 'react'
import { View, Flex } from '../flex'
import { Table, TableHeader, TableHeaderContents, TableRow, TableCell, TableFooter } from './styles'

const { element, string, arrayOf, oneOf, shape, number, object } = PropTypes

const FlexTable = ({ HeaderContents, Footer, EmptyState, columns, rows }) =>

    <View column>
      <TableHeader>
        <View column>
          {HeaderContents &&
            <TableHeaderContents>
              {HeaderContents}
            </TableHeaderContents>
          }

            <TableRow>
              <View>
                {columns.map(({ label, flex }) =>
                  <Flex flex={flex}>
                    <TableCell>{label}</TableCell>
                  </Flex>
                )}
              </View>
            </TableRow>

        </View>
      </TableHeader>
      <Flex scroll>
        {rows && rows.length ? rows.map(({ rowProps = {}, rowCells, rowElement }) =>
          <TableRow {...rowProps}>
            <View>
              {rowCells && rowCells.map((el, i) =>
                <Flex flex={columns[i].flex}>
                  <TableCell>{el}</TableCell>
                </Flex>
              )}
            </View>
            <View>
              {rowElement}
            </View>
          </TableRow>
        ) : EmptyState}
      </Flex>
      <TableFooter>
        {Footer}
      </TableFooter>
    </View>

FlexTable.propTypes = {
  HeaderContents: element,
  Footer: element,
  EmptyState: element,
  columns: arrayOf(shape({
    label: string,
    flex: oneOf([number, string])
  })),
  rows: arrayOf(shape({
    rowCells: arrayOf(element),
    rowElement: element,
    rowProps: object
  }))
}

export default FlexTable
<|endoftext|>


<commit_before>import Vue from 'vue'
import {
  MIN_COLUMN_WIDTH,
  getColumnWidth,
  fitColumnWidth
} from './utils'
import TableHead from './table-head'
import TableBody from './table-body'
import TableLayout from './table-layout'

export default {
  name: 'table',

  props: {
    columns: {
      type: Array,
      default () { return [] }
    },

    rows: {
      type: Array,
      default () { return [] }
    },

    fixed: {
      type: [Number, Array],
      default: 0
    },

    height: Number,

    useMax: Boolean,

    dataBus: null
  },

  data () {
    return {
      layoutComplete: false
    }
  },

  computed: {
    leftColumns () {
      return this.columns.slice(0, this.layout.leftColumnNumber)
    },

    rightColumns () {
      return this.columns.slice(-this.layout.rightColumnNumber)
    }
  },

  watch: {
    'fixed': {
      immediate: true,
      deep: true,
      handler (value) {
        this.layout.fixed = value
      }
    },

    'height': {
      immediate: true,
      handler (value) {
        this.layout.height = value
      }
    },

    'useMax': {
      immediate: true,
      handler (value) {
        this.layout.useMax = value
      }
    },

    'columns': {
      deep: true,
      handler () {
        this.$nextTick(_ => {
          this.layoutColumns(true)
        })
      }
    },

    'rows': {
      deep: true,
      handler: 'syncHeight'
    },

    'layout.bodyWidth' () {
      // no need to adjust column width
      if (this.layoutComplete && this.layout.scrollbarHeight !== 0) return
      this.layoutColumns()
    }
  },

  methods: {
    resetHoveredRowIndex () {
      this.layout.hoveredRowIndex = null
    },

    layoutColumns (reset) {
      if (this.columns.length !== this.layout.columnWidth.length || reset) {
        // get new column size
        getColumnWidth(this.columns, this.layout, this.$refs.head.$el)
      }
      // fit column width
      fitColumnWidth(this.columns, this.layout)
      if (!this.layoutComplete) this.layoutComplete = true
    },

    // column resize
    columnResize (column, offset, cb) {
      var index = this.columns.indexOf(column)
      var newWidth = this.layout.columnWidth[index] + offset
      if (offset < 0) {
        // keep column min width set in column options
        if (typeof column.width === 'number' && newWidth < column.width) {
          return
        }
        // keep table fill the container
        if (this.layout.totalWidth + offset < this.layout.bodyWidth) {
          return
        }
        // keep min column width
        if (newWidth < MIN_COLUMN_WIDTH) {
          return
        }
      }
      this.layout.columnWidth.splice(index, 1, newWidth)
      if (cb) cb()
    },

    // @exposed
    syncHeight () {
      if (this.$refs.head) {
        this.$refs.head.updateHeight()
      }
      if (this.$refs.body) {
        this.$refs.body.updateRowHeight(true)
      }
    }
  },

  beforeCreate () {
    this.layout = new Vue(TableLayout)
  },

  render (h) {
    var left, right

    var main = (
      <div
        staticClass="vt__main-wrapper">
        <TableHead
          style={this.layout.mainHeadStyle}
          columns={this.columns}
          dataBus={this.dataBus}
          layout={this.layout}
          ref="head"
          onColumnResize={this.columnResize}
        />
        <TableBody
          style={this.layout.bodyStyle}
          columns={this.columns}
          rows={this.rows}
          dataBus={this.dataBus}
          layout={this.layout}
          ref="body"
        />
      </div>
    )

    if (this.layout.leftColumnNumber) {
      left = (
        <div
          staticClass="vt__left-wrapper">
          <TableHead
            fixed="left"
            columns={this.leftColumns}
            dataBus={this.dataBus}
            layout={this.layout}
            onColumnResize={this.columnResize}
          />
          <TableBody
            style={this.layout.fixedBodyStyle}
            fixed="left"
            columns={this.leftColumns}
            rows={this.rows}
            dataBus={this.dataBus}
            layout={this.layout}
          />
        </div>
      )
    }

    if (this.layout.rightColumnNumber) {
      right = (
        <div
          staticClass="vt__right-wrapper"
          style={this.layout.rightWrapperStyle}>
          <TableHead
            fixed="right"
            columns={this.rightColumns}
            dataBus={this.dataBus}
            layout={this.layout}
            onColumnResize={this.columnResize}
          />
          <TableBody
            style={this.layout.fixedBodyStyle}
            fixed="right"
            columns={this.rightColumns}
            rows={this.rows}
            dataBus={this.dataBus}
            layout={this.layout}
          />
        </div>
      )
    }

    return (
      <div
        staticClass="vt__wrapper"
        style={{ visibility: this.layoutComplete ? 'visible' : 'hidden' }}
        onMouseleave={this.resetHoveredRowIndex}
        ref="wrapper">
        {main}
        {left}
        {right}
      </div>
    )
  }
}
<commit_msg>style: Temp var<commit_after>import Vue from 'vue'
import {
  MIN_COLUMN_WIDTH,
  getColumnWidth,
  fitColumnWidth
} from './utils'
import TableHead from './table-head'
import TableBody from './table-body'
import TableLayout from './table-layout'

export default {
  name: 'table',

  props: {
    columns: {
      type: Array,
      default () { return [] }
    },

    rows: {
      type: Array,
      default () { return [] }
    },

    fixed: {
      type: [Number, Array],
      default: 0
    },

    height: Number,

    useMax: Boolean,

    dataBus: null
  },

  data () {
    return {
      layoutComplete: false
    }
  },

  computed: {
    leftColumns () {
      return this.columns.slice(0, this.layout.leftColumnNumber)
    },

    rightColumns () {
      return this.columns.slice(-this.layout.rightColumnNumber)
    }
  },

  watch: {
    'fixed': {
      immediate: true,
      deep: true,
      handler (value) {
        this.layout.fixed = value
      }
    },

    'height': {
      immediate: true,
      handler (value) {
        this.layout.height = value
      }
    },

    'useMax': {
      immediate: true,
      handler (value) {
        this.layout.useMax = value
      }
    },

    'columns': {
      deep: true,
      handler () {
        this.$nextTick(_ => {
          this.layoutColumns(true)
        })
      }
    },

    'rows': {
      deep: true,
      handler: 'syncHeight'
    },

    'layout.bodyWidth' () {
      // no need to adjust column width
      if (this.layoutComplete && this.layout.scrollbarHeight !== 0) return
      this.layoutColumns()
    }
  },

  methods: {
    resetHoveredRowIndex () {
      this.layout.hoveredRowIndex = null
    },

    layoutColumns (reset) {
      if (this.columns.length !== this.layout.columnWidth.length || reset) {
        // get new column size
        getColumnWidth(this.columns, this.layout, this.$refs.head.$el)
      }
      // fit column width
      fitColumnWidth(this.columns, this.layout)
      if (!this.layoutComplete) this.layoutComplete = true
    },

    // column resize
    columnResize (column, offset, cb) {
      var index = this.columns.indexOf(column)
      var newWidth = this.layout.columnWidth[index] + offset
      var layout = this.layout
      if (offset < 0) {
        // keep column min width set in column options
        if (typeof column.width === 'number' && newWidth < column.width) {
          return
        }
        // keep table fill the container
        if (layout.totalWidth + offset < layout.bodyWidth) {
          return
        }
        // keep min column width
        if (newWidth < MIN_COLUMN_WIDTH) {
          return
        }
      }
      layout.columnWidth.splice(index, 1, newWidth)
      if (cb) cb()
    },

    // @exposed
    syncHeight () {
      if (this.$refs.head) {
        this.$refs.head.updateHeight()
      }
      if (this.$refs.body) {
        this.$refs.body.updateRowHeight(true)
      }
    }
  },

  beforeCreate () {
    this.layout = new Vue(TableLayout)
  },

  render (h) {
    var left, right

    var main = (
      <div
        staticClass="vt__main-wrapper">
        <TableHead
          style={this.layout.mainHeadStyle}
          columns={this.columns}
          dataBus={this.dataBus}
          layout={this.layout}
          ref="head"
          onColumnResize={this.columnResize}
        />
        <TableBody
          style={this.layout.bodyStyle}
          columns={this.columns}
          rows={this.rows}
          dataBus={this.dataBus}
          layout={this.layout}
          ref="body"
        />
      </div>
    )

    if (this.layout.leftColumnNumber) {
      left = (
        <div
          staticClass="vt__left-wrapper">
          <TableHead
            fixed="left"
            columns={this.leftColumns}
            dataBus={this.dataBus}
            layout={this.layout}
            onColumnResize={this.columnResize}
          />
          <TableBody
            style={this.layout.fixedBodyStyle}
            fixed="left"
            columns={this.leftColumns}
            rows={this.rows}
            dataBus={this.dataBus}
            layout={this.layout}
          />
        </div>
      )
    }

    if (this.layout.rightColumnNumber) {
      right = (
        <div
          staticClass="vt__right-wrapper"
          style={this.layout.rightWrapperStyle}>
          <TableHead
            fixed="right"
            columns={this.rightColumns}
            dataBus={this.dataBus}
            layout={this.layout}
            onColumnResize={this.columnResize}
          />
          <TableBody
            style={this.layout.fixedBodyStyle}
            fixed="right"
            columns={this.rightColumns}
            rows={this.rows}
            dataBus={this.dataBus}
            layout={this.layout}
          />
        </div>
      )
    }

    return (
      <div
        staticClass="vt__wrapper"
        style={{ visibility: this.layoutComplete ? 'visible' : 'hidden' }}
        onMouseleave={this.resetHoveredRowIndex}
        ref="wrapper">
        {main}
        {left}
        {right}
      </div>
    )
  }
}
<|endoftext|>


<commit_before>// The `kern` table contains kerning pairs.
// Note that some fonts use the GPOS OpenType layout table to specify kerning.
// https://www.microsoft.com/typography/OTSPEC/kern.htm

'use strict';

var check = require('../check');
var parse = require('../parse');

// Parse the `kern` table which contains kerning pairs.
function parseKernTable(data, start) {
    var pairs = {};
    var p = new parse.Parser(data, start);
    var tableVersion = p.parseUShort();
    check.argument(tableVersion === 0, 'Unsupported kern table version.');
    // Skip nTables.
    p.skip('uShort', 1);
    var subTableVersion = p.parseUShort();
    check.argument(subTableVersion === 0, 'Unsupported kern sub-table version.');
    // Skip subTableLength, subTableCoverage
    p.skip('uShort', 2);
    var nPairs = p.parseUShort();
    // Skip searchRange, entrySelector, rangeShift.
    p.skip('uShort', 3);
    for (var i = 0; i < nPairs; i += 1) {
        var leftIndex = p.parseUShort();
        var rightIndex = p.parseUShort();
        var value = p.parseShort();
        pairs[leftIndex + ',' + rightIndex] = value;
    }

    return pairs;
}

exports.parse = parseKernTable;
<commit_msg>Add preliminary support for Mac kern table.<commit_after>// The `kern` table contains kerning pairs.
// Note that some fonts use the GPOS OpenType layout table to specify kerning.
// https://www.microsoft.com/typography/OTSPEC/kern.htm

'use strict';

var check = require('../check');
var parse = require('../parse');

function parseWindowsKernTable(p) {
    var pairs = {};
    // Skip nTables.
    p.skip('uShort');
    var subtableVersion = p.parseUShort();
    check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.');
    // Skip subtableLength, subtableCoverage
    p.skip('uShort', 2);
    var nPairs = p.parseUShort();
    // Skip searchRange, entrySelector, rangeShift.
    p.skip('uShort', 3);
    for (var i = 0; i < nPairs; i += 1) {
        var leftIndex = p.parseUShort();
        var rightIndex = p.parseUShort();
        var value = p.parseShort();
        pairs[leftIndex + ',' + rightIndex] = value;
    }
    return pairs;
}

function parseMacKernTable(p) {
    var pairs = {};
    // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits.
    // Skip the rest.
    p.skip('uShort');
    var nTables = p.parseULong();
    //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').');
    if (nTables > 1) {
        console.warn('Only the first kern subtable is supported.');
    }
    p.skip('uLong');
    var coverage = p.parseUShort();
    var subtableVersion = coverage & 0xFF;
    p.skip('uShort');
    if (subtableVersion === 0) {
        var nPairs = p.parseUShort();
        // Skip searchRange, entrySelector, rangeShift.
        p.skip('uShort', 3);
        for (var i = 0; i < nPairs; i += 1) {
            var leftIndex = p.parseUShort();
            var rightIndex = p.parseUShort();
            var value = p.parseShort();
            pairs[leftIndex + ',' + rightIndex] = value;
        }
    }
    return pairs;
}

// Parse the `kern` table which contains kerning pairs.
function parseKernTable(data, start) {
    var p = new parse.Parser(data, start);
    var tableVersion = p.parseUShort();
    if (tableVersion === 0) {
        return parseWindowsKernTable(p);
    } else if (tableVersion === 1) {
        return parseMacKernTable(p);
    } else {
        throw new Error('Unsupported kern table version (' + tableVersion + ').');
    }
}

exports.parse = parseKernTable;
<|endoftext|>


<commit_before>var Sqlite = require('../index');

module.exports = {
  adapter: Sqlite,
  filename: 'firenze.sqlite'
};
<commit_msg>move created test database<commit_after>var Sqlite = require('../index');

module.exports = {
  adapter: Sqlite,
  filename: './src/test/firenze.sqlite'
};
<|endoftext|>


<commit_before>var fs = require('fs');

var troncfg = function(cfg) {
  var self = this;

  /** app defaults */
  this.html = 'index.html';
  this.debug = false;
  this.frame = true;
  this.fullscreen = false;
  this.verbose = true;
  this.appPath = __dirname + '/../../../'; // running from within this node module
  /*******************/

  this.options = {
    'debug': { flags: [ 'd', 'debug', 'D'], type: 'boolean' },
    'fullscreen': { flags: [ 'fullscreen'], type: 'boolean' },
    'html': { flags: ['html'], type: 'string' } };

  /**
   * apply args from CLI
   */
  this.load = function(cfg) {
    var props = null;
    if (cfg && typeof cfg === 'string') {
      props = JSON.parse(fs.readFileSync(cfg));
    } else if (cfg) {
      props = cfg;
    } else {
      props = {};
      process.argv.forEach(function (arg) {
        var key = arg.split(':')[0];
        var value = arg.split(':')[1];
        props[key] = value;
      });
    }

    Object.keys(props).forEach(function (key) {
      if (props[key] != "undefined" && props[key] != undefined && props[key]) {
        for (var c in self.options) {
          if (self.options[c].flags.indexOf(key) != -1) {
            if (self.options[c].type === 'boolean') {
              props[key] = self.argToBoolean(props[key]);
            }
            self[key] = props[key];
            console.log("Setting config." + key + " to " + props[key]);
          }
        }
      }
    });
  };

  /**
   * simple arg to boolean conversion
   * @param arg
   * @returns {boolean}
   */
  this.argToBoolean = function(arg) {
    if (typeof arg === 'boolean') { return arg; }
    return (arg == "true") ? true : false;
  };

  this.load(cfg);
};

module.exports = troncfg;
<commit_msg>added ability for custom application config<commit_after>var fs = require('fs');

var troncfg = function(cfg) {
  var self = this;

  this.application = {};

  /** app defaults */
  this.html = 'index.html';
  this.debug = false;
  this.frame = true;
  this.fullscreen = false;
  this.verbose = true;
  this.appPath = __dirname + '/../../../'; // running from within this node module
  /*******************/

  this.options = {
    'debug': { flags: [ 'd', 'debug', 'D'], type: 'boolean' },
    'fullscreen': { flags: [ 'fullscreen'], type: 'boolean' },
    'html': { flags: ['html'], type: 'string' } };

  /**
   * apply args from CLI
   */
  this.load = function(cfg) {
    var props = null;
    if (cfg && typeof cfg === 'string') {
      props = JSON.parse(fs.readFileSync(cfg));
    } else if (cfg) {
      props = cfg;
    } else {
      props = {};
      process.argv.forEach(function (arg) {
        var key = arg.split(':')[0];
        var value = arg.split(':')[1];
        props[key] = value;
      });
    }

    if (props.application) {
      this.application = props.application;
    }

    Object.keys(props).forEach(function (key) {
      if (props[key] != "undefined" && props[key] != undefined && props[key]) {
        for (var c in self.options) {
          if (self.options[c].flags.indexOf(key) != -1) {
            if (self.options[c].type === 'boolean') {
              props[key] = self.argToBoolean(props[key]);
            }
            self[key] = props[key];
            console.log("Setting config." + key + " to " + props[key]);
          }
        }
      }
    });
  };

  /**
   * simple arg to boolean conversion
   * @param arg
   * @returns {boolean}
   */
  this.argToBoolean = function(arg) {
    if (typeof arg === 'boolean') { return arg; }
    return (arg == "true") ? true : false;
  };

  this.load(cfg);
};

module.exports = troncfg;
<|endoftext|>


<commit_before>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2014 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* @class Phaser.Utils
* @static
*/
Phaser.Utils = {

    /**
     * Gets an objects property by string.
     *
     * @method Phaser.Utils.getProperty
     * @param {object} obj - The object to traverse.
     * @param {string} prop - The property whose value will be returned.
     * @return {*} the value of the property or null if property isn't found .
     */
    getProperty: function(obj, prop) {

        var parts = prop.split('.'),
            last = parts.pop(),
            l = parts.length,
            i = 1,
            current = parts[0];

        while (i < l && (obj = obj[current]))
        {
            current = parts[i];
            i++;
        }

        if (obj)
        {
            return obj[last];
        }
        else
        {
            return null;
        }

    },

    /**
     * Sets an objects property by string.
     *
     * @method Phaser.Utils.setProperty
     * @param {object} obj - The object to traverse
     * @param {string} prop - The property whose value will be changed
     * @return {object} The object on which the property was set.
     */
    setProperty: function(obj, prop, value) {

        var parts = prop.split('.'),
            last = parts.pop(),
            l = parts.length,
            i = 1,
            current = parts[0];

        while (i < l && (obj = obj[current]))
        {
            current = parts[i];
            i++;
        }

        if (obj)
        {
            obj[last] = value;
        }

        return obj;

    },

    /**
    * Generate a random bool result based on the chance value.
    *
    * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
    * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
    *
    * @method Phaser.Math#chanceRoll
    * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
    * @return {boolean} True if the roll passed, or false otherwise.
    */
    chanceRoll: function (chance) {
        if (typeof chance === 'undefined') { chance = 50; }
        return chance > 0 && (Math.random() * 100 <= chance);
    },

    /**
    * Choose between one of two values randomly.
    *
    * @method Phaser.Utils#randomChoice
    * @param {any} choice1
    * @param {any} choice2
    * @return {any} The randomly selected choice
    */
    randomChoice: function (choice1, choice2) {
        return (Math.random() < 0.5) ? choice1 : choice2;
    },

    /**
    * Transposes the elements of the given matrix (array of arrays).
    *
    * @method Phaser.Utils.transposeArray
    * @param {Array<any[]>} array - The matrix to transpose.
    * @return {Array<any[]>} A new transposed matrix
    * @deprecated 2.2.0 - Use Phaser.ArrayUtils.transposeMatrix
    */
    transposeArray: function (array) {
        return Phaser.ArrayUtils.transposeMatrix(array);
    },

    /**
    * Rotates the given matrix (array of arrays).
    *
    * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}.
    *
    * @method Phaser.Utils.rotateArray
    * @param {Array<any[]>} matrix - The array to rotate; this matrix _may_ be altered.
    * @param {number|string} direction - The amount to rotate: the roation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180').
    * @return {Array<any[]>} The rotated matrix. The source matrix should be discarded for the returned matrix.
    * @deprecated 2.2.0 - Use Phaser.ArrayUtils.rotateMatrix
    */
    rotateArray: function (matrix, direction) {
        return Phaser.ArrayUtils.rotateMatrix(matrix, direction);
    },

    /**
    * A standard Fisher-Yates Array shuffle implementation.
    *
    * @method Phaser.Utils.shuffle
    * @param {any[]} array - The array to shuffle.
    * @return {any[]} The shuffled array.
    * @deprecated 2.2.0 - User Phaser.ArrayUtils.shuffle
    */
    shuffle: function (array) {
        return Phaser.ArrayUtils.shuffle(array);
    },

    /**
    * Get a unit dimension from a string.
    *
    * @method Phaser.Utils.parseDimension
    * @param {string|number} size - The size to parse.
    * @param {number} dimension - The window dimension to check.
    * @return {number} The parsed dimension.
    */
    parseDimension: function (size, dimension) {

        var f = 0;
        var px = 0;

        if (typeof size === 'string')
        {
            //  %?
            if (size.substr(-1) === '%')
            {
                f = parseInt(size, 10) / 100;

                if (dimension === 0)
                {
                    px = window.innerWidth * f;
                }
                else
                {
                    px = window.innerHeight * f;
                }
            }
            else
            {
                px = parseInt(size, 10);
            }
        }
        else
        {
            px = size;
        }

        return px;

    },

    /**
    * Javascript string pad http://www.webtoolkit.info/.
    *
    * @method Phaser.Utils.pad
    * @param {string} str - The target string.
    * @param {number} len - The number of characters to be added.
    * @param {number} pad - The string to pad it out with (defaults to a space).
    * @param {number} [dir=3] The direction dir = 1 (left), 2 (right), 3 (both).
    * @return {string} The padded string
    */
    pad: function (str, len, pad, dir) {

        if (typeof(len) === "undefined") { var len = 0; }
        if (typeof(pad) === "undefined") { var pad = ' '; }
        if (typeof(dir) === "undefined") { var dir = 3; }

        var padlen = 0;

        if (len + 1 >= str.length)
        {
            switch (dir)
            {
                case 1:
                    str = new Array(len + 1 - str.length).join(pad) + str;
                    break;

                case 3:
                    var right = Math.ceil((padlen = len - str.length) / 2);
                    var left = padlen - right;
                    str = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
                    break;

                default:
                    str = str + new Array(len + 1 - str.length).join(pad);
                    break;
            }
        }

        return str;

    },

    /**
    * This is a slightly modified version of jQuery.isPlainObject.
    * A plain object is an object whose internal class property is [object Object].
    * @method Phaser.Utils.isPlainObject
    * @param {object} obj - The object to inspect.
    * @return {boolean} - true if the object is plain, otherwise false.
    */
    isPlainObject: function (obj) {

        // Not plain objects:
        // - Any object or value whose internal [[Class]] property is not "[object Object]"
        // - DOM nodes
        // - window
        if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
        {
            return false;
        }

        // Support: Firefox <20
        // The try/catch suppresses exceptions thrown when attempting to access
        // the "constructor" property of certain host objects, ie. |window.location|
        // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
        try {
            if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf"))
            {
                return false;
            }
        } catch (e) {
            return false;
        }

        // If the function hasn't returned already, we're confident that
        // |obj| is a plain object, created by {} or constructed with new Object
        return true;
    },

    /**
    * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
    * @method Phaser.Utils.extend
    * @param {boolean} deep - Perform a deep copy?
    * @param {object} target - The target object to copy to.
    * @return {object} The extended object.
    */
    extend: function () {

        var options, name, src, copy, copyIsArray, clone,
            target = arguments[0] || {},
            i = 1,
            length = arguments.length,
            deep = false;

        // Handle a deep copy situation
        if (typeof target === "boolean")
        {
            deep = target;
            target = arguments[1] || {};
            // skip the boolean and the target
            i = 2;
        }

        // extend Phaser if only one argument is passed
        if (length === i)
        {
            target = this;
            --i;
        }

        for (; i < length; i++)
        {
            // Only deal with non-null/undefined values
            if ((options = arguments[i]) != null)
            {
                // Extend the base object
                for (name in options)
                {
                    src = target[name];
                    copy = options[name];

                    // Prevent never-ending loop
                    if (target === copy)
                    {
                        continue;
                    }

                    // Recurse if we're merging plain objects or arrays
                    if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
                    {
                        if (copyIsArray)
                        {
                            copyIsArray = false;
                            clone = src && Array.isArray(src) ? src : [];
                        }
                        else
                        {
                            clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
                        }

                        // Never move original objects, clone them
                        target[name] = Phaser.Utils.extend(deep, clone, copy);

                    // Don't bring in undefined values
                    }
                    else if (copy !== undefined)
                    {
                        target[name] = copy;
                    }
                }
            }
        }

        // Return the modified object
        return target;

    },

    /**
    * Mixes in an existing mixin object with the target.
    * Prototype values with that have either `get` or `set` functions are created as properties via defineProperty.
    *
    * @method Phaser.Utils.mixinPrototype
    * @param {object} target - The target object to receive the new functions.
    * @param {object} mixin - The object to copy the functions from.
    * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not?
    */
    mixinPrototype: function (target, mixin, replace) {

        if (typeof replace === 'undefined') { replace = false; }

        var mixinKeys = Object.keys(mixin);

        for (var i = 0; i < mixinKeys.length; i++)
        {
            var key = mixinKeys[i];
            var value = mixin[key];

            if (!replace && target[key])
            {
                continue;
            }
            else
            {
                if (value && (typeof value.get === 'function' || typeof value.set === 'function'))
                {
                    Object.defineProperty(target, key, value);
                }
                else
                {
                    target[key] = value;
                }
            }
        }

    },

    /**
    * Mixes the source object into the destination object, returning the newly modified destination object.
    * Based on original code by @mudcube
    *
    * @method Phaser.Utils.mixin
    * @param {object} from - The object to copy (the source object).
    * @param {object} to - The object to copy to (the destination object).
    * @return {object} The modified destination object.
    */
    mixin: function (from, to) {

        if (!from || typeof (from) !== "object")
        {
            return to;
        }

        for (var key in from)
        {
            var o = from[key];

            if (o.childNodes || o.cloneNode)
            {
                continue;
            }

            var type = typeof (from[key]);

            if (!from[key] || type !== "object")
            {
                to[key] = from[key];
            }
            else
            {
                //  Clone sub-object
                if (typeof (to[key]) === type)
                {
                    to[key] = Phaser.Utils.mixin(from[key], to[key]);
                }
                else
                {
                    to[key] = Phaser.Utils.mixin(from[key], new o.constructor());
                }
            }
        }

        return to;

    }

};
<commit_msg>mixinPrototype can now clone objects that support it.<commit_after>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2014 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* @class Phaser.Utils
* @static
*/
Phaser.Utils = {

    /**
     * Gets an objects property by string.
     *
     * @method Phaser.Utils.getProperty
     * @param {object} obj - The object to traverse.
     * @param {string} prop - The property whose value will be returned.
     * @return {*} the value of the property or null if property isn't found .
     */
    getProperty: function(obj, prop) {

        var parts = prop.split('.'),
            last = parts.pop(),
            l = parts.length,
            i = 1,
            current = parts[0];

        while (i < l && (obj = obj[current]))
        {
            current = parts[i];
            i++;
        }

        if (obj)
        {
            return obj[last];
        }
        else
        {
            return null;
        }

    },

    /**
     * Sets an objects property by string.
     *
     * @method Phaser.Utils.setProperty
     * @param {object} obj - The object to traverse
     * @param {string} prop - The property whose value will be changed
     * @return {object} The object on which the property was set.
     */
    setProperty: function(obj, prop, value) {

        var parts = prop.split('.'),
            last = parts.pop(),
            l = parts.length,
            i = 1,
            current = parts[0];

        while (i < l && (obj = obj[current]))
        {
            current = parts[i];
            i++;
        }

        if (obj)
        {
            obj[last] = value;
        }

        return obj;

    },

    /**
    * Generate a random bool result based on the chance value.
    *
    * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
    * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
    *
    * @method Phaser.Math#chanceRoll
    * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
    * @return {boolean} True if the roll passed, or false otherwise.
    */
    chanceRoll: function (chance) {
        if (typeof chance === 'undefined') { chance = 50; }
        return chance > 0 && (Math.random() * 100 <= chance);
    },

    /**
    * Choose between one of two values randomly.
    *
    * @method Phaser.Utils#randomChoice
    * @param {any} choice1
    * @param {any} choice2
    * @return {any} The randomly selected choice
    */
    randomChoice: function (choice1, choice2) {
        return (Math.random() < 0.5) ? choice1 : choice2;
    },

    /**
    * Transposes the elements of the given matrix (array of arrays).
    *
    * @method Phaser.Utils.transposeArray
    * @param {Array<any[]>} array - The matrix to transpose.
    * @return {Array<any[]>} A new transposed matrix
    * @deprecated 2.2.0 - Use Phaser.ArrayUtils.transposeMatrix
    */
    transposeArray: function (array) {
        return Phaser.ArrayUtils.transposeMatrix(array);
    },

    /**
    * Rotates the given matrix (array of arrays).
    *
    * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}.
    *
    * @method Phaser.Utils.rotateArray
    * @param {Array<any[]>} matrix - The array to rotate; this matrix _may_ be altered.
    * @param {number|string} direction - The amount to rotate: the roation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180').
    * @return {Array<any[]>} The rotated matrix. The source matrix should be discarded for the returned matrix.
    * @deprecated 2.2.0 - Use Phaser.ArrayUtils.rotateMatrix
    */
    rotateArray: function (matrix, direction) {
        return Phaser.ArrayUtils.rotateMatrix(matrix, direction);
    },

    /**
    * A standard Fisher-Yates Array shuffle implementation.
    *
    * @method Phaser.Utils.shuffle
    * @param {any[]} array - The array to shuffle.
    * @return {any[]} The shuffled array.
    * @deprecated 2.2.0 - User Phaser.ArrayUtils.shuffle
    */
    shuffle: function (array) {
        return Phaser.ArrayUtils.shuffle(array);
    },

    /**
    * Get a unit dimension from a string.
    *
    * @method Phaser.Utils.parseDimension
    * @param {string|number} size - The size to parse.
    * @param {number} dimension - The window dimension to check.
    * @return {number} The parsed dimension.
    */
    parseDimension: function (size, dimension) {

        var f = 0;
        var px = 0;

        if (typeof size === 'string')
        {
            //  %?
            if (size.substr(-1) === '%')
            {
                f = parseInt(size, 10) / 100;

                if (dimension === 0)
                {
                    px = window.innerWidth * f;
                }
                else
                {
                    px = window.innerHeight * f;
                }
            }
            else
            {
                px = parseInt(size, 10);
            }
        }
        else
        {
            px = size;
        }

        return px;

    },

    /**
    * Javascript string pad http://www.webtoolkit.info/.
    *
    * @method Phaser.Utils.pad
    * @param {string} str - The target string.
    * @param {number} len - The number of characters to be added.
    * @param {number} pad - The string to pad it out with (defaults to a space).
    * @param {number} [dir=3] The direction dir = 1 (left), 2 (right), 3 (both).
    * @return {string} The padded string
    */
    pad: function (str, len, pad, dir) {

        if (typeof(len) === "undefined") { var len = 0; }
        if (typeof(pad) === "undefined") { var pad = ' '; }
        if (typeof(dir) === "undefined") { var dir = 3; }

        var padlen = 0;

        if (len + 1 >= str.length)
        {
            switch (dir)
            {
                case 1:
                    str = new Array(len + 1 - str.length).join(pad) + str;
                    break;

                case 3:
                    var right = Math.ceil((padlen = len - str.length) / 2);
                    var left = padlen - right;
                    str = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
                    break;

                default:
                    str = str + new Array(len + 1 - str.length).join(pad);
                    break;
            }
        }

        return str;

    },

    /**
    * This is a slightly modified version of jQuery.isPlainObject.
    * A plain object is an object whose internal class property is [object Object].
    * @method Phaser.Utils.isPlainObject
    * @param {object} obj - The object to inspect.
    * @return {boolean} - true if the object is plain, otherwise false.
    */
    isPlainObject: function (obj) {

        // Not plain objects:
        // - Any object or value whose internal [[Class]] property is not "[object Object]"
        // - DOM nodes
        // - window
        if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
        {
            return false;
        }

        // Support: Firefox <20
        // The try/catch suppresses exceptions thrown when attempting to access
        // the "constructor" property of certain host objects, ie. |window.location|
        // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
        try {
            if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf"))
            {
                return false;
            }
        } catch (e) {
            return false;
        }

        // If the function hasn't returned already, we're confident that
        // |obj| is a plain object, created by {} or constructed with new Object
        return true;
    },

    /**
    * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
    * @method Phaser.Utils.extend
    * @param {boolean} deep - Perform a deep copy?
    * @param {object} target - The target object to copy to.
    * @return {object} The extended object.
    */
    extend: function () {

        var options, name, src, copy, copyIsArray, clone,
            target = arguments[0] || {},
            i = 1,
            length = arguments.length,
            deep = false;

        // Handle a deep copy situation
        if (typeof target === "boolean")
        {
            deep = target;
            target = arguments[1] || {};
            // skip the boolean and the target
            i = 2;
        }

        // extend Phaser if only one argument is passed
        if (length === i)
        {
            target = this;
            --i;
        }

        for (; i < length; i++)
        {
            // Only deal with non-null/undefined values
            if ((options = arguments[i]) != null)
            {
                // Extend the base object
                for (name in options)
                {
                    src = target[name];
                    copy = options[name];

                    // Prevent never-ending loop
                    if (target === copy)
                    {
                        continue;
                    }

                    // Recurse if we're merging plain objects or arrays
                    if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
                    {
                        if (copyIsArray)
                        {
                            copyIsArray = false;
                            clone = src && Array.isArray(src) ? src : [];
                        }
                        else
                        {
                            clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
                        }

                        // Never move original objects, clone them
                        target[name] = Phaser.Utils.extend(deep, clone, copy);

                    // Don't bring in undefined values
                    }
                    else if (copy !== undefined)
                    {
                        target[name] = copy;
                    }
                }
            }
        }

        // Return the modified object
        return target;

    },

    /**
    * Mixes in an existing mixin object with the target.
    * Prototype values with that have either `get` or `set` functions are created as properties via defineProperty.
    *
    * @method Phaser.Utils.mixinPrototype
    * @param {object} target - The target object to receive the new functions.
    * @param {object} mixin - The object to copy the functions from.
    * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not?
    */
    mixinPrototype: function (target, mixin, replace) {

        // console.log('------------------------------------------------------------------');
        // console.log('mixin target', target);
        // console.log('mixin source', mixin);

        if (typeof replace === 'undefined') { replace = false; }

        var mixinKeys = Object.keys(mixin);

        for (var i = 0; i < mixinKeys.length; i++)
        {
            var key = mixinKeys[i];
            var value = mixin[key];

            if (!replace && target[key])
            {
                continue;
            }
            else
            {
                if (value && typeof value.clone === 'function')
                {
                    target[key] = value.clone();
                }
                else
                {
                    //  Breaks in classes like Phaser.Point which has a 'set' function! Hence the clone exception above
                    if (value && (typeof value.get === 'function' || typeof value.set === 'function'))
                    {
                        Object.defineProperty(target, key, value);
                        // console.log('def prop', key, 'to', value);
                    }
                    else
                    {
                        target[key] = value;
                        // console.log('set', key, 'to', value);
                    }
                }
            }
        }

    },

    /**
    * Mixes the source object into the destination object, returning the newly modified destination object.
    * Based on original code by @mudcube
    *
    * @method Phaser.Utils.mixin
    * @param {object} from - The object to copy (the source object).
    * @param {object} to - The object to copy to (the destination object).
    * @return {object} The modified destination object.
    */
    mixin: function (from, to) {

        if (!from || typeof (from) !== "object")
        {
            return to;
        }

        for (var key in from)
        {
            var o = from[key];

            if (o.childNodes || o.cloneNode)
            {
                continue;
            }

            var type = typeof (from[key]);

            if (!from[key] || type !== "object")
            {
                to[key] = from[key];
            }
            else
            {
                //  Clone sub-object
                if (typeof (to[key]) === type)
                {
                    to[key] = Phaser.Utils.mixin(from[key], to[key]);
                }
                else
                {
                    to[key] = Phaser.Utils.mixin(from[key], new o.constructor());
                }
            }
        }

        return to;

    }

};
<|endoftext|>