<commit_before>/**
 * Calulcate blackjack hand probabilities for different actions.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * Author: Chris Zieba (zieba.chris@gmail.com)
 */

'use strict';

var Blackjack = Blackjack || {};

Blackjack.Probability = (function() {
    /**
     * Helper function to initiliaze the probabilities object.
     *
     * @return {Object} stats
     */
    function init() {
        var stats = {
            hands: 0,
            win: {
                hands: 0,
                odds: 0
            },
            lose: {
                hands: 0,
                odds: 0
            },
            push: {
                hands: 0,
                odds: 0
            }
        };

        return stats;
    }

    /**
     * Helper function to combine probabilities.
     *
     * @return {Object} currentStats
     */
    function combine(currentStats, newStats) {
        currentStats.hands += newStats.hands;
        currentStats.win.hands += newStats.win.hands;
        currentStats.win.odds += newStats.win.odds;
        currentStats.lose.hands += newStats.lose.hands;
        currentStats.lose.odds += newStats.lose.odds;
        currentStats.push.hands += newStats.push.hands;
        currentStats.push.odds += newStats.push.odds;

        return currentStats;
    }

    /**
     * Calculate the win/losss/push probabilities of the player standing after the deal.
     *
     * @param {Array} shoe
     * @param {Object} dealerCards
     * @param {Object} playerCards
     * @param {Integer} maxPullCount
     * @param {Integer} pullCount
     * @param {Integer} startIndex
     * @return {Object} stats
     */
    var stand = function(shoe, dealerCards, playerCards, maxPullCount, pullCount, startIndex) {
        var dealerTotalAfterPull, dealerCardsAfterPull, newStats;
        var playerTotal = Blackjack.Utils.score(playerCards);
        var stats = initStats();

        //var index = (startIndex !== null) ? startIndex : 0;

        for (var i = 0, j=pullCount+startIndex; i < shoe.length-pullCount; i+=1, j+=1) {
            // The dealer pulls a card from the shoe

            j = (j >= shoe.length) ? 0 : j;
            // this is just making sure we wrap around the array
            var nextCard = shoe[(pullCount > 0) ? j : i];

            /**
             * Calculate the probability of pulling a card from the deck.
             * The probability for pulling one card from the shoe is 1/(cards in shoe).
            */
            var cardProbabilty = 1;
            for (var l=0; l<=pullCount; l+=1) {
                cardProbabilty *= 1/(shoe.length-l)
            }

            dealerCardsAfterPull = dealerCards.slice();
            dealerCardsAfterPull.push(nextCard);

            // We want to create a new array so we can use the previos cards easily
            dealerTotalAfterPull = Blackjack.Utils.score(dealerCardsAfterPull);

            if (playerTotal > 21) {
                stats.hands += 1;
                stats.lose.hands += 1
                stats.lose.odds += cardProbabilty;
            } else if (dealerTotalAfterPull > 21) {
                stats.hands+=1;
                stats.win.hands += 1
                stats.win.odds += cardProbabilty;
            } else if (dealerTotalAfterPull >= 17) {
                stats.hands += 1;
                // the odds are 0% on a push so it is ignored
                if (dealerTotalAfterPull < playerTotal) {
                    stats.win.hands += 1
                    stats.win.odds+=cardProbabilty;
                } else if (dealerTotalAfterPull > playerTotal) {
                    stats.lose.hands += 1
                    stats.lose.odds += cardProbabilty;
                } else {
                    stats.push.hands += 1
                    stats.push.odds += cardProbabilty;
                }
            } else {
                // The reason for passing null in if the pullCount is gratr than 0 is
                // because we want to start at a specific element in the shoe once for each
                // main out loop
                if (pullCount <= maxPullCount) {
                    newStats = stand(shoe, dealerCardsAfterPull, playerCards, maxPullCount, pullCount+1, (pullCount > 0) ? startIndex : i);
                    stats = combineStats(stats, newStats);
                }
            }
        }

        return stats;
    };

    /**
     * Calculate the win/losss/push probabilities of the player hitting their hand.
     *
     * @param {Array} shoe
     * @param {Object} dealerCards
     * @param {Object} playerCards
     * @param {Integer} maxPullCount
     * @param {Integer} pullCount
     * @param {Integer} startIndex
     * @return {Object} stats
     */
    var hit = function(shoe, dealerCards, playerCards, maxPullCount, pullCount, startIndex) {
        var playerTotalAfterPull, playerCardsAfterPull, newStats;
        var playerTotal = Blackjack.Utils.score(playerCards);
        var stats = init();

        /**
         * Loop through every card in the shoe.
         * Use the counters i,j, and pullCount to remember at what
         * point in the shoe we are.
         */
        for (var i = 0, j = pullCount + startIndex; i < shoe.length - pullCount; i+=1, j+=1) {
            // The player pulls a card from the shoe
            j = (j >= shoe.length) ? 0 : j;

            // This is just making sure we wrap around the array
            var nextCard = shoe[(pullCount > 0) ? j : i];

            /**
             * Calculate the probability of pulling a card from the deck.
             * The probability for pulling one card from the shoe is 1/(cards left in shoe).
             */
            var cardProbabilty = 1;
            for (var l=0; l<=pullCount; l+=1) {
                cardProbabilty*= 1/(shoe.length-l)
            }

            playerCardsAfterPull = playerCards.slice();
            playerCardsAfterPull.push(nextCard);

            // Only take a card if not a blackjack
            if (pullCount == 0 && playerTotal == 21) {
                playerTotalAfterPull = playerTotal;
            } else {
                playerTotalAfterPull = Blackjack.Utils.score(playerCardsAfterPull);
            }

            // Even if the player total is a bust we need run through the hand probabilites agasint the dealer
            if (playerTotalAfterPull >= 17) {
                /**
                 * If the player hand is within standing range (17 and 21) or bust (> 21)
                 * we need to calculate the probabilites as if the hand was played out by the dealer.
                 */
                newStats = stand(shoe, dealerCards, playerCardsAfterPull, maxPullCount, pullCount + 1, 0);
                stats = combine(stats, newStats);
            } else {
                /**
                 * If the player hand is not withing the standing range we hit again.
                 * The startIndex is important because we want to pull a card at a
                 * specific element in the shoe (the next card).
                 */
                if (pullCount <= maxPullCount) {
                    newStats = hit(shoe, dealerCards, playerCardsAfterPull, maxPullCount, pullCount + 1, (pullCount > 0) ? startIndex : i);
                    stats = combine(stats, newStats);
                }
            }
        }

        return stats;
    };

    var double = function(shoe, dealerCards, playerCards, maxPullCount, pullCount, startIndex) {
        var playerTotalAfterPull, playerCardsAfterPull, newStats;
        var playerTotal = Blackjack.Utils.score(playerCards);
        var stats = initStats();

        for (var i = 0, j=pullCount+startIndex; i < shoe.length-pullCount; i+=1, j+=1) {
            // The player pulls a card from the shoe

            j = (j >= shoe.length) ? 0 : j;
            // this is just making sure we wrap around the array
            var nextCard = shoe[(pullCount > 0) ? j : i];

            playerCardsAfterPull = playerCards.slice();
            playerCardsAfterPull.push(nextCard);
            //playerTotalAfterPull = Blackjack.Utils.score(playerCardsAfterPull);

            newStats = stand(shoe, dealerCards, playerCardsAfterPull, maxPullCount, pullCount+1, 0);
            stats = combineStats(stats, newStats);

        }

        return stats;
    };

    return {
        stand: function(shoe, dealerCards, playerCards, maxPullCount) {
            return stand(shoe, dealerCards, playerCards, maxPullCount, 0, 0);
        },

        hit: function(shoe, dealerCards, playerCards, maxPullCount) {
            return hit(shoe, dealerCards, playerCards, maxPullCount, 0, 0);
        },

        double: function(shoe, dealerCards, playerCards, maxPullCount) {
            return double(shoe, dealerCards, playerCards, maxPullCount, 0, 0);
        }
    };
}());<commit_msg>Cleanup the double method<commit_after>/**
 * Calulcate blackjack hand probabilities for different actions.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * Author: Chris Zieba (zieba.chris@gmail.com)
 */

'use strict';

var Blackjack = Blackjack || {};

Blackjack.Probability = (function() {
    /**
     * Helper function to initiliaze the probabilities object.
     *
     * @return {Object} stats
     */
    function init() {
        var stats = {
            hands: 0,
            win: {
                hands: 0,
                odds: 0
            },
            lose: {
                hands: 0,
                odds: 0
            },
            push: {
                hands: 0,
                odds: 0
            }
        };

        return stats;
    }

    /**
     * Helper function to combine probabilities.
     *
     * @return {Object} currentStats
     */
    function combine(currentStats, newStats) {
        currentStats.hands += newStats.hands;
        currentStats.win.hands += newStats.win.hands;
        currentStats.win.odds += newStats.win.odds;
        currentStats.lose.hands += newStats.lose.hands;
        currentStats.lose.odds += newStats.lose.odds;
        currentStats.push.hands += newStats.push.hands;
        currentStats.push.odds += newStats.push.odds;

        return currentStats;
    }

    /**
     * Calculate the win/loss/push probabilities of the player standing after the deal.
     *
     * @param {Array} shoe
     * @param {Object} dealerCards
     * @param {Object} playerCards
     * @param {Integer} maxPullCount
     * @param {Integer} pullCount
     * @param {Integer} startIndex
     * @return {Object} stats
     */
    var stand = function(shoe, dealerCards, playerCards, maxPullCount, pullCount, startIndex) {
        var dealerTotalAfterPull, dealerCardsAfterPull, newStats;
        var playerTotal = Blackjack.Utils.score(playerCards);
        var stats = initStats();

        //var index = (startIndex !== null) ? startIndex : 0;

        for (var i = 0, j=pullCount+startIndex; i < shoe.length-pullCount; i+=1, j+=1) {
            // The dealer pulls a card from the shoe

            j = (j >= shoe.length) ? 0 : j;
            // this is just making sure we wrap around the array
            var nextCard = shoe[(pullCount > 0) ? j : i];

            /**
             * Calculate the probability of pulling a card from the deck.
             * The probability for pulling one card from the shoe is 1/(cards in shoe).
            */
            var cardProbabilty = 1;
            for (var l=0; l<=pullCount; l+=1) {
                cardProbabilty *= 1/(shoe.length-l)
            }

            dealerCardsAfterPull = dealerCards.slice();
            dealerCardsAfterPull.push(nextCard);

            // We want to create a new array so we can use the previos cards easily
            dealerTotalAfterPull = Blackjack.Utils.score(dealerCardsAfterPull);

            if (playerTotal > 21) {
                stats.hands += 1;
                stats.lose.hands += 1
                stats.lose.odds += cardProbabilty;
            } else if (dealerTotalAfterPull > 21) {
                stats.hands+=1;
                stats.win.hands += 1
                stats.win.odds += cardProbabilty;
            } else if (dealerTotalAfterPull >= 17) {
                stats.hands += 1;
                // the odds are 0% on a push so it is ignored
                if (dealerTotalAfterPull < playerTotal) {
                    stats.win.hands += 1
                    stats.win.odds+=cardProbabilty;
                } else if (dealerTotalAfterPull > playerTotal) {
                    stats.lose.hands += 1
                    stats.lose.odds += cardProbabilty;
                } else {
                    stats.push.hands += 1
                    stats.push.odds += cardProbabilty;
                }
            } else {
                // The reason for passing null in if the pullCount is gratr than 0 is
                // because we want to start at a specific element in the shoe once for each
                // main out loop
                if (pullCount <= maxPullCount) {
                    newStats = stand(shoe, dealerCardsAfterPull, playerCards, maxPullCount, pullCount+1, (pullCount > 0) ? startIndex : i);
                    stats = combineStats(stats, newStats);
                }
            }
        }

        return stats;
    };

    /**
     * Calculate the win/loss/push probabilities of the player hitting their hand.
     *
     * @param {Array} shoe
     * @param {Object} dealerCards
     * @param {Object} playerCards
     * @param {Integer} maxPullCount
     * @param {Integer} pullCount
     * @param {Integer} startIndex
     * @return {Object} stats
     */
    var hit = function(shoe, dealerCards, playerCards, maxPullCount, pullCount, startIndex) {
        var playerTotalAfterPull, playerCardsAfterPull, newStats;
        var playerTotal = Blackjack.Utils.score(playerCards);
        var stats = init();

        /**
         * Loop through every card in the shoe.
         * Use the counters i,j, and pullCount to remember at what
         * point in the shoe we are.
         */
        for (var i = 0, j = pullCount + startIndex; i < shoe.length - pullCount; i+=1, j+=1) {
            // The player pulls a card from the shoe
            j = (j >= shoe.length) ? 0 : j;

            // This is just making sure we wrap around the array
            var nextCard = shoe[(pullCount > 0) ? j : i];

            /**
             * Calculate the probability of pulling a card from the deck.
             * The probability for pulling one card from the shoe is 1/(cards left in shoe).
             */
            var cardProbabilty = 1;
            for (var l=0; l<=pullCount; l+=1) {
                cardProbabilty*= 1/(shoe.length-l)
            }

            playerCardsAfterPull = playerCards.slice();
            playerCardsAfterPull.push(nextCard);

            // Only take a card if not a blackjack
            if (pullCount == 0 && playerTotal == 21) {
                playerTotalAfterPull = playerTotal;
            } else {
                playerTotalAfterPull = Blackjack.Utils.score(playerCardsAfterPull);
            }

            // Even if the player total is a bust we need run through the hand probabilites agasint the dealer
            if (playerTotalAfterPull >= 17) {
                /**
                 * If the player hand is within standing range (17 and 21) or bust (> 21)
                 * we need to calculate the probabilites as if the hand was played out by the dealer.
                 */
                newStats = stand(shoe, dealerCards, playerCardsAfterPull, maxPullCount, pullCount + 1, 0);
                stats = combine(stats, newStats);
            } else {
                /**
                 * If the player hand is not withing the standing range we hit again.
                 * The startIndex is important because we want to pull a card at a
                 * specific element in the shoe (the next card).
                 */
                if (pullCount <= maxPullCount) {
                    newStats = hit(shoe, dealerCards, playerCardsAfterPull, maxPullCount, pullCount + 1, (pullCount > 0) ? startIndex : i);
                    stats = combine(stats, newStats);
                }
            }
        }

        return stats;
    };

    /**
     * Calculate the win/loss/push probabilities of the player doubling down.
     *
     * @param {Array} shoe
     * @param {Object} dealerCards
     * @param {Object} playerCards
     * @param {Integer} maxPullCount
     * @param {Integer} pullCount
     * @param {Integer} startIndex
     * @return {Object} stats
     */
    var double = function(shoe, dealerCards, playerCards, maxPullCount, pullCount, startIndex) {
        var playerTotalAfterPull, playerCardsAfterPull, newStats;
        var playerTotal = Blackjack.Utils.score(playerCards);
        var stats = init();

        for (var i = 0, j=pullCount+startIndex; i < shoe.length-pullCount; i+=1, j+=1) {
            j = (j >= shoe.length) ? 0 : j;
            // The player pulls a card from the shoe
            var nextCard = shoe[(pullCount > 0) ? j : i];

            // Add the card to the players hand
            playerCardsAfterPull = playerCards.slice();
            playerCardsAfterPull.push(nextCard);

            // Calculate what the probabilities are when compared to the dealers hand
            newStats = stand(shoe, dealerCards, playerCardsAfterPull, maxPullCount, pullCount+1, 0);
            stats = combine(stats, newStats);
        }

        return stats;
    };

    return {
        stand: function(shoe, dealerCards, playerCards, maxPullCount) {
            return stand(shoe, dealerCards, playerCards, maxPullCount, 0, 0);
        },

        hit: function(shoe, dealerCards, playerCards, maxPullCount) {
            return hit(shoe, dealerCards, playerCards, maxPullCount, 0, 0);
        },

        double: function(shoe, dealerCards, playerCards, maxPullCount) {
            return double(shoe, dealerCards, playerCards, maxPullCount, 0, 0);
        }
    };
}());<|endoftext|>


<commit_before>export default class QueryParser{
	static ParseToQuery(data, query){
		query = '(';
		for (let i = 0, length = data.rules.length; i < length; i++){
			if (!data.rules[i].combinator){
				query += `${data.rules[i].field} ${data.rules[i].operator} '${data.rules[i].value}'`;
				if (i !== length - 1 && !data.rules[i+1].combinator){
					query += data.combinator + ' ';
				}
			}
			else{
				query += ` ${data.combinator} ${this.ParseToQuery(data.rules[i], query)}`;
			}
		}
		return query + ')';
	}

	static ParseToData(query, config){
		let initData = {
				combinator: config.combinators[0].combinator,
				nodeName: '1',
				rules: []
				};
		if (query === '()'){
			return initData;
		}

	}

	CreateOutputStack(query, config){
		let operatorsStack = [];
		let outputStack = [];
		let separators = '';
		for (let i = 0, length = config.combinators.length; i < length; i++){
			separators += config.combinators[i];
		}
		for (let i = 0, length = query.length; i < length; i++){
			// if (query.)
		}
	}

	GetTokensArray(query, combinators){
		let combinatorsIndexes = this.GetCombinatorsIndexes(query, combinators);
		let tokens = [];
		for (let i = 0, length = query.length; i < length; i++){
			if (combinatorsIndexes.find(x => x.start===i)){
				// there is a token
			}
			else if(query[i] === '(' || query[i] === ')'){
				tokens.push(query[i]);
			}
			else{

			}
		}
	}

	isInArray(element, index, array){

	}

	static GetCombinatorsIndexes(query, combinators){
		let combinatorsIndexes = [];
		let combinatorsPattern = '';
		for (let i = 0; i < combinators.length; i++){
			combinatorsPattern += `|${combinators[i].combinator}`;
		}
		//To remove first | character
		combinatorsPattern = combinatorsPattern.slice(1);
		combinatorsPattern = new RegExp(combinatorsPattern, 'gi');
		var match;
		while ((match = combinatorsPattern.exec(query)) !== null){
			combinatorsIndexes.push({start: match.index, end: combinatorsPattern.lastIndex});
		}
		return combinatorsIndexes;
	}
}
<commit_msg>tokenizer<commit_after>export default class QueryParser{
	static ParseToQuery(data, query){
		query = '(';
		for (let i = 0, length = data.rules.length; i < length; i++){
			if (!data.rules[i].combinator){
				query += `${data.rules[i].field} ${data.rules[i].operator} '${data.rules[i].value}'`;
				if (i !== length - 1 && !data.rules[i+1].combinator){
					query += data.combinator + ' ';
				}
			}
			else{
				query += ` ${data.combinator} ${this.ParseToQuery(data.rules[i], query)}`;
			}
		}
		return query + ')';
	}

	static ParseToData(query, config){
		let initData = {
				combinator: config.combinators[0].combinator,
				nodeName: '1',
				rules: []
				};
		if (query === '()'){
			return initData;
		}

	}

	CreateOutputStack(query, config){
		let operatorsStack = [];
		let outputStack = [];
		let separators = '';
		for (let i = 0, length = config.combinators.length; i < length; i++){
			separators += config.combinators[i];
		}
		for (let i = 0, length = query.length; i < length; i++){
			// if (query.)
		}
	}

	GetTokensArray(query, combinators){
		let combinatorsIndexes = this.GetCombinatorsIndexes(query, combinators);
		let tokens = [];
		let token = '';
		for (let i = 0, length = query.length; i < length; i++){
			let combinatorIndexes = combinatorsIndexes.find(x => x.start===i);
			if (combinatorIndexes){
				let combinator = this.GetCombinatorByIndexes(query, combinatorIndexes.start, combinatorIndexes.end);
				this.PushTokenIfNotEmpty(token, tokens);
				tokens.push(combinator);
				i=combinatorIndexes.end;
			}
			else if(query[i] === '(' || query[i] === ')'){
				this.PushTokenIfNotEmpty(token, tokens);
				tokens.push(query[i]);
			}
			else{
				token += query[i];
			}
		}
		return tokens;
	}

	PushTokenIfNotEmpty(token, array){
		if (token){
			array.push(token);
		}
		token = '';
	}

	GetCombinatorByIndexes(query, start, end){
		let combinator = '';
		for(let i = start; i <= end; i++){
			combinator+=query[i];
		}
		return combinator;
	}

	static GetCombinatorsIndexes(query, combinators){
		let combinatorsIndexes = [];
		let combinatorsPattern = '';
		for (let i = 0; i < combinators.length; i++){
			combinatorsPattern += `|${combinators[i].combinator}`;
		}
		//To remove first | character
		combinatorsPattern = combinatorsPattern.slice(1);
		combinatorsPattern = new RegExp(combinatorsPattern, 'gi');
		var match;
		while ((match = combinatorsPattern.exec(query)) !== null){
			combinatorsIndexes.push({start: match.index, end: combinatorsPattern.lastIndex});
		}
		return combinatorsIndexes;
	}
}
<|endoftext|>


<commit_before>/**
 * @file Radio component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import IconButton from '../IconButton';
import Theme from '../Theme';

import Util from '../_vendors/Util';

export default class Radio extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            checked: !!props.checked
        };

        this.touchTapHandler = ::this.touchTapHandler;
        this.mouseDownHandler = ::this.mouseDownHandler;
        this.mouseUpHandler = ::this.mouseUpHandler;

    }

    touchTapHandler() {

        let {checked} = this.state;

        if (checked) {
            return;
        }

        this.setState({
            checked: true
        }, () => {
            this.props.onChange && this.props.onChange(true);
        });

    }

    mouseDownHandler(e) {

        if (this.props.disabled) {
            return;
        }

        this.refs.radioIcon.startRipple(e);
        this.touchTapHandler();

    }

    mouseUpHandler(e) {

        if (this.props.disabled) {
            return;
        }

        this.refs.radioIcon.endRipple(e);

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.checked !== this.state.checked) {
            this.setState({
                checked: !!nextProps.checked
            });
        }
    }

    render() {

        const {
                className, style, theme, name, label, value,
                uncheckedIconCls, checkedIconCls, disabled
            } = this.props,
            {checked} = this.state,

            radioClassName = (checked ? ' activated' : '') + (theme ? ` theme-${theme}` : '')
                + (className ? ' ' + className : '');

        return (

                {
                    name ?
                        <input className="hidden-radio"
                               type="radio"
                               name={name}
                               value={value}
                               checked={checked}
                               onChange={() => {
                               }}/>
                        :
                        null
                }

                    <IconButton ref="radioIcon"
                                className="radio-bg-icon"
                                iconCls={uncheckedIconCls}
                                onTouchTap={this.touchTapHandler}
                                disabled={disabled}/>

                    <IconButton className="radio-icon"
                                iconCls={checkedIconCls}
                                onTouchTap={this.touchTapHandler}
                                disabled={disabled}/>

                    {label}

        );

    }
};

Radio.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The Radio theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The name of the radio.
     */
    name: PropTypes.string,

    /**
     * Label for radio.
     */
    label: PropTypes.any,

    /**
     * Value for radio.
     */
    value: PropTypes.any,

    /**
     * If true,the radio will be checked.
     */
    checked: PropTypes.bool,

    uncheckedIconCls: PropTypes.string,
    checkedIconCls: PropTypes.string,

    /**
     * If true, the radio will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * Callback function fired when the radio status change.
     */
    onChange: PropTypes.func

};

Radio.defaultProps = {

    className: null,
    style: null,
    theme: Theme.DEFAULT,

    name: null,
    label: null,
    value: '',
    checked: false,
    uncheckedIconCls: 'fa fa-circle-o',
    checkedIconCls: 'fa fa-dot-circle-o',
    disabled: false

};<commit_msg>optimize Radio<commit_after>/**
 * @file Radio component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import IconButton from '../IconButton';
import Theme from '../Theme';

import Util from '../_vendors/Util';

export default class Radio extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            checked: !!props.checked
        };

        this.touchTapHandler = ::this.touchTapHandler;
        this.mouseDownHandler = ::this.mouseDownHandler;
        this.mouseUpHandler = ::this.mouseUpHandler;

    }

    touchTapHandler() {

        let {checked} = this.state;

        if (checked) {
            return;
        }

        this.setState({
            checked: true
        }, () => {
            this.props.onChange && this.props.onChange(true);
        });

    }

    mouseDownHandler(e) {

        if (this.props.disabled) {
            return;
        }

        this.refs.radioIcon.startRipple(e);
        this.touchTapHandler();

    }

    mouseUpHandler(e) {

        if (this.props.disabled) {
            return;
        }

        this.refs.radioIcon.endRipple(e);

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.checked !== this.state.checked) {
            this.setState({
                checked: !!nextProps.checked
            });
        }
    }

    render() {

        const {
                className, style, theme, name, label, value,
                uncheckedIconCls, checkedIconCls, disabled
            } = this.props,
            {checked} = this.state,

            radioClassName = (checked ? ' activated' : '') + (theme ? ` theme-${theme}` : '')
                + (className ? ' ' + className : '');

        return (

                {
                    name ?
                        <input className="hidden-radio"
                               type="radio"
                               name={name}
                               value={value}
                               checked={checked}
                               onChange={() => {
                               }}/>
                        :
                        null
                }

                    <IconButton ref="radioIcon"
                                className="radio-bg-icon"
                                iconCls={uncheckedIconCls}
                                onTouchTap={this.touchTapHandler}
                                disabled={disabled}/>

                    <IconButton className="radio-icon"
                                iconCls={checkedIconCls}
                                onTouchTap={this.touchTapHandler}
                                disabled={disabled}/>

                {
                    label ?

                            {label}

                        :
                        null
                }

        );

    }
};

Radio.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The Radio theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The name of the radio.
     */
    name: PropTypes.string,

    /**
     * Label for radio.
     */
    label: PropTypes.any,

    /**
     * Value for radio.
     */
    value: PropTypes.any,

    /**
     * If true,the radio will be checked.
     */
    checked: PropTypes.bool,

    uncheckedIconCls: PropTypes.string,
    checkedIconCls: PropTypes.string,

    /**
     * If true, the radio will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * Callback function fired when the radio status change.
     */
    onChange: PropTypes.func

};

Radio.defaultProps = {

    className: null,
    style: null,
    theme: Theme.DEFAULT,

    name: null,
    label: null,
    value: '',
    checked: false,
    uncheckedIconCls: 'fa fa-circle-o',
    checkedIconCls: 'fa fa-dot-circle-o',
    disabled: false

};<|endoftext|>


<commit_before>// Copyright (c) E5R Development Team. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.

(function(main){ 'use strict'
  // DOC: https://technet.microsoft.com/pt-br/library/ff920171(v=ws.10).aspx
  if(typeof WScript != 'object') throw new Error('WSH not detected!');

  var _fso = new ActiveXObject("Scripting.FileSystemObject"),
      _shell = new ActiveXObject("WScript.Shell"),
      _userPath = _shell.Environment('PROCESS')('USERPROFILE'),
      _productInfo = {
        name: 'E5R Environment',
        version: {
          major: 0,
          minor: 1,
          patch: 0,
          label: 'alpha-2',
          toString:function(){
            return '{MAJOR}.{MINOR}.{PATCH}.{LABEL}'
              .replace('{MAJOR}', this.major)
              .replace('{MINOR}', this.minor)
              .replace('{PATCH}', this.patch)
              .replace('{LABEL}', this.label);
          }
        },
        meta: {
          userPath: _userPath,
          installPath: _userPath + '\\.e5r',
          binPath: _userPath + '\\.e5r\\bin',
          libPath: _userPath + '\\.e5r\\lib',
          fileRepository: 'https://raw.githubusercontent.com/e5r/env/migrate-to-javascript',
          makeUrl: function(url){
            if(url.indexOf('/') != 0) url = '/' + url;
            return _productInfo.meta.fileRepository + url;
          },
          makePath: function(path){
            path = path.replace('/', '\\');
            if(path.indexOf('\\') != 0) path = '\\' + path;
            return _productInfo.meta.installPath + path;
          },
          copyright: '(C) 2014-2015, E5R Development Team. All rights reserved.',
          authors: [
            {name:'Erlimar Silva Campos', email:'erlimar@gmail.com', github:'erlimar'}
          ]
        }
      },
      _sys = {
        product: _productInfo,
        include: function(filePath){
          var _filePath = _productInfo.meta.libPath + '\\' + fileName,
              content = _fso.OpenTextFile(_filePath, 1).ReadAll(),
              sys = _sys;
          eval(content);
        },
        require: function(fileName){
          var _filePath = _productInfo.meta.libPath + '\\' + fileName,
              module = {},
              content = _fso.OpenTextFile(_filePath, 1).ReadAll(),
              sys = _sys;
          eval(content);
          return module.exports;
        },
        log: function(){
          var _msg = '';
          for(var arg = 0; arg < arguments.length; arg++){
            _msg += _msg.length > 0 ? ' ' : '';
            _msg += arguments[arg];
          }
          if(this === _sys.logTask || this === _sys.logSubTask || this === _sys.logAction){
            this.print(_msg);
            return;
          }
          WScript.Echo(_msg);
        },
        logTask: function(msg){
          _sys.logTask.print = function(msg){
            WScript.Echo('\n----->', msg);
          }
          _sys.log.apply(_sys.logTask, arguments);
        },
        logSubTask: function(){
          _sys.logSubTask.print = function(msg){
            WScript.Echo('     >', msg);
          }
          _sys.log.apply(_sys.logSubTask, arguments);
        },
        logAction: function(){
          _sys.logAction.print = function(msg){
            WScript.Echo('      ', msg);
          }
          _sys.log.apply(_sys.logAction, arguments);
        }
      };

  if(typeof main == 'function'){
    var _args = [];
    for(var a = 0; a < WScript.Arguments.length; a++){
      _args.push(WScript.Arguments.Item(a));
    }
    main(_sys, _args);
  }
})(function(sys, args){
  var su = sys.require('sysutils.js');

  sys.log('Host: ' + su.host.name + ' v' + su.host.version + '(' + su.host.build + ')');
  sys.log(' > ExecPath: ' + su.host.execPath);
  sys.log(' > ExecDirectory: ' + su.host.execDirectory);

  sys.log('\nScript: ' + su.script.name);
  sys.log(' > File: ' + su.script.file );
  sys.log(' > Directory: ' + su.script.directory );

  sys.log('\n%USERPROFILE%: ' + su.buildEnvString('%USERPROFILE%'));

  sys.log('\nNet: ');
  sys.log(' > Domain: ' + su.net.domain);
  sys.log(' > User: ' + su.net.user);
  sys.log(' > Computer: ' + su.net.computer);
  sys.log(' > Drives: ' + (su.net.drives.length > 0 ? '' : '[no drives mapped]'));
  for(var d in su.net.drives){
    var _drive = su.net.drives[d];
    sys.log('   - Drive: ' + _drive.drive + ', Path: ' + _drive.path);
  }
  sys.log(' > Printers: ' + (su.net.printers.length > 0 ? '' : '[no printers mapped]'));
  for(var p in su.net.printers){
    var _printer = su.net.printers[p];
    sys.log('   - Id: ' + _printer.id + ', Name: ' + _printer.name);
  }

  sys.log('\nEnvironment:');
  sys.log(' > Process.MYVAR: ' + su.getEnvironment('MYVAR', su.CONST.ENVTYPE_PROCESS));
  sys.log(' > User.MYVAR: ' + su.getEnvironment('MYVAR', su.CONST.ENVTYPE_USER));
  sys.log(' > System.MYVAR: ' + su.getEnvironment('MYVAR', su.CONST.ENVTYPE_SYSTEM));
  sys.log(' > MYVAR: ' + su.getEnvironment('MYVAR'));
});
<commit_msg>Updating cmdrunner.js as e5r-install.js<commit_after>// Copyright (c) E5R Development Team. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.

(function(main){ 'use strict'
  // DOC: https://msdn.microsoft.com/pt-br/library/9bbdkx3k.aspx
  if(typeof WScript != 'object') throw new Error('WSH not detected!');

  var _fso = new ActiveXObject("Scripting.FileSystemObject"),
      _shell = new ActiveXObject("WScript.Shell"),
      _userPath = _shell.Environment('PROCESS')('USERPROFILE'),
      _productInfo = {
        name: 'E5R Environment',
        version: {
          major: 0,
          minor: 1,
          patch: 0,
          label: 'alpha-2',
          toString:function(){
            return '{MAJOR}.{MINOR}.{PATCH}.{LABEL}'
              .replace('{MAJOR}', this.major)
              .replace('{MINOR}', this.minor)
              .replace('{PATCH}', this.patch)
              .replace('{LABEL}', this.label);
          }
        },
        meta: {
          userPath: _userPath,
          installPath: _userPath + '\\.e5r',
          binPath: _userPath + '\\.e5r\\bin',
          libPath: _userPath + '\\.e5r\\lib',
          fileRepository: 'https://raw.githubusercontent.com/e5r/env/migrate-to-javascript',
          makeUrl: function(url){
            if(url.indexOf('/') != 0) url = '/' + url;
            return _productInfo.meta.fileRepository + url;
          },
          makePath: function(path){
            path = path.replace('/', '\\');
            if(path.indexOf('\\') != 0) path = '\\' + path;
            return _productInfo.meta.installPath + path;
          },
          copyright: '(C) 2014-2015, E5R Development Team. All rights reserved.',
          authors: [
            {name:'Erlimar Silva Campos', email:'erlimar@gmail.com', github:'erlimar'}
          ]
        }
      },
      _sys = {
        product: _productInfo,
        include: function(filePath){
          var _filePath = _productInfo.meta.libPath + '\\' + fileName,
              content = _fso.OpenTextFile(_filePath, 1).ReadAll(),
              sys = _sys;
          eval(content);
        },
        require: function(fileName){
          var _filePath = _productInfo.meta.libPath + '\\' + fileName,
              module = {},
              content = _fso.OpenTextFile(_filePath, 1).ReadAll(),
              sys = _sys;
          eval(content);
          return module.exports;
        },
        log: function(){
          var _msg = '';
          for(var arg = 0; arg < arguments.length; arg++){
            _msg += _msg.length > 0 ? ' ' : '';
            _msg += arguments[arg];
          }
          if(this === _sys.logTask || this === _sys.logSubTask || this === _sys.logAction){
            this.print(_msg);
            return;
          }
          WScript.Echo(_msg);
        },
        logTask: function(msg){
          _sys.logTask.print = function(msg){
            WScript.Echo('\n----->', msg);
          }
          _sys.log.apply(_sys.logTask, arguments);
        },
        logSubTask: function(){
          _sys.logSubTask.print = function(msg){
            WScript.Echo('     *', msg);
          }
          _sys.log.apply(_sys.logSubTask, arguments);
        },
        logAction: function(){
          _sys.logAction.print = function(msg){
            WScript.Echo('       >', msg);
          }
          _sys.log.apply(_sys.logAction, arguments);
        }
      };

  if(typeof main == 'function'){
    var _args = [];
    for(var a = 0; a < WScript.Arguments.length; a++){
      _args.push(WScript.Arguments.Item(a));
    }
    main(_sys, _args);
  }
})(function(sys, args){
  var su = sys.require('sysutils.js');

  sys.log('Host: ' + su.host.name + ' v' + su.host.version + '(' + su.host.build + ')');
  sys.log(' > ExecPath: ' + su.host.execPath);
  sys.log(' > ExecDirectory: ' + su.host.execDirectory);

  sys.log('\nScript: ' + su.script.name);
  sys.log(' > File: ' + su.script.file );
  sys.log(' > Directory: ' + su.script.directory );

  sys.log('\n%USERPROFILE%: ' + su.buildEnvString('%USERPROFILE%'));

  sys.log('\nNet: ');
  sys.log(' > Domain: ' + su.net.domain);
  sys.log(' > User: ' + su.net.user);
  sys.log(' > Computer: ' + su.net.computer);
  sys.log(' > Drives: ' + (su.net.drives.length > 0 ? '' : '[no drives mapped]'));
  for(var d in su.net.drives){
    var _drive = su.net.drives[d];
    sys.log('   - Drive: ' + _drive.drive + ', Path: ' + _drive.path);
  }
  sys.log(' > Printers: ' + (su.net.printers.length > 0 ? '' : '[no printers mapped]'));
  for(var p in su.net.printers){
    var _printer = su.net.printers[p];
    sys.log('   - Id: ' + _printer.id + ', Name: ' + _printer.name);
  }

  sys.log('\nEnvironment:');
  sys.log(' > Process.MYVAR: ' + su.getEnvironment('MYVAR', su.CONST.ENVTYPE_PROCESS));
  sys.log(' > User.MYVAR: ' + su.getEnvironment('MYVAR', su.CONST.ENVTYPE_USER));
  sys.log(' > System.MYVAR: ' + su.getEnvironment('MYVAR', su.CONST.ENVTYPE_SYSTEM));
  sys.log(' > MYVAR: ' + su.getEnvironment('MYVAR'));
});
<|endoftext|>


<commit_before>// Call the functions
countDownTimer('05/29/2015 2:00 PM', 'seniors');
countDownTimer('06/05/2015 2:00 PM', 'others');

// Define the countdown function
function countDownTimer(dt, id) {
	// Define the goal date
	var end = new Date(dt);

	// Define each in milliseconds
	var _second = 1000;
	var _minute = _second * 60;
	var _hour = _minute * 60;
	var _day = _hour * 24;
	// Interval variable
	var timer;

	// Create another function to show the time remaining
	function showRemaining() {
		// Get the current date
		var now = new Date();
		// Get the difference
		var distance = end - now;
		// If the date has passed
		if(distance <= 0) {
			// Clear the timer
			clearInterval(timer);
			// Print some text
			if(id == 'seniors') {
				document.getElementById(id).innerHTML = 'GRADUATION!!!';
			} else {
				document.getElementById(id).innerHTML = 'SUMMER!!!';
			}
			// Don't continue with the rest of the function
			return;
		}

		// Obtain the number for each of the following
		var days = Math.floor(distance / _day);
		var hours = Math.floor((distance % _day) / _hour);
		var minutes = Math.floor((distance % _hour) / _minute);
		var seconds = Math.floor((distance % _minute) / _second);

		var timer = "";

		// Print the information on the page
		if(days != 0) timer += days + ' days, ';
		if(days != 0 || hours != 0) timer += hours + ' hrs, ';
		if(days != 0 || hours != 0 || minutes != 0) timer += minutes + ' min, ';
		if(days != 0 || hours != 0 || minutes != 0 || seconds != 0) timer += seconds + ' sec';

		document.getElementById(id).innerHTML = timer;
	};
	// Refresh every second
	timer = setInterval(showRemaining, 1000);
};
<commit_msg>Adding weeks.<commit_after>// Call the functions
countDownTimer('05/29/2015 2:00 PM', 'seniors');
countDownTimer('06/05/2015 2:00 PM', 'others');

// Define the countdown function
function countDownTimer(dt, id) {
	// Define the goal date
	var end = new Date(dt);

	// Define each in milliseconds
	var _second = 1000;
	var _minute = _second * 60;
	var _hour = _minute * 60;
	var _day = _hour * 24;
	var _week = _day * 7
	// Interval variable
	var timer;

	// Create another function to show the time remaining
	function showRemaining() {
		// Get the current date
		var now = new Date();
		// Get the difference
		var distance = end - now;
		// If the date has passed
		if(distance <= 0) {
			// Clear the timer
			clearInterval(timer);
			// Print some text
			if(id == 'seniors') {
				document.getElementById(id).innerHTML = 'GRADUATION!!!';
			} else {
				document.getElementById(id).innerHTML = 'SUMMER!!!';
			}
			// Don't continue with the rest of the function
			return;
		}

		// Obtain the number for each of the following
		var weeks = Math.floor(distance / _week);
		var days = Math.floor((distance % _week) / _day);
		var hours = Math.floor((distance % _day) / _hour);
		var minutes = Math.floor((distance % _hour) / _minute);
		var seconds = Math.floor((distance % _minute) / _second);

		var timer = "";

		// Print the information on the page
		if(weeks != 0) timer += weeks + 'weeks, ';
		if(weeks != 0 || days != 0) timer += days + ' days, ';
		if(weeks != 0 || days != 0 || hours != 0) timer += hours + ' hrs, ';
		if(weeks != 0 || days != 0 || hours != 0 || minutes != 0) timer += minutes + ' min, ';
		if(weeks != 0 || days != 0 || hours != 0 || minutes != 0 || seconds != 0) timer += seconds + ' sec';

		document.getElementById(id).innerHTML = timer;
	};
	// Refresh every second
	timer = setInterval(showRemaining, 1000);
};
<|endoftext|>


<commit_before>// dependencies
// Interface for Google Deepdream
const Response = require('hubot').Response
var _ = require('lomath')
var fs = require('fs')
var runDeepdream = require('../lib/deepdream')
var request = require('request')

// for rate limiting
const maxUse = 20
var counter = {
  'id': 0
}
// deduct usages for each user
function deduct(userId) {
  counter[userId] = (counter[userId]||maxUse)-1
  return counter[userId]
}

// quick test scripts
/* istanbul ignore next */
module.exports = function(robot) {
  robot.on("fb_richMsg", function(envelope) {
    res = new Response(robot, envelope, undefined)
    // rate limit
    var remain = deduct(envelope.user.id)
    if (remain < 0) {
      res.send(`Sorry, you ran out of your ${maxUse} uses of Deepdream. Hope you enjoyed!`)
      return
    }

    res.send(`running DeepDream. This may take up to 2 minutes :) Meanwhile you have ${remain} uses left.`)
    robot.logger.info("got fb richMsg", envelope.attachments[0])
    runDeepdream(envelope)
    .then(function(outFilepath) {
      robot.logger.info('DeepDream outFile', outFilepath)
      var formData = {
        recipient: `{"id":"${envelope.user.id}"}`,
        message: '{"attachment":{"type":"image", "payload":{}}}',
        filedata: fs.createReadStream(outFilepath)
      }
      request.post({url:'https://graph.facebook.com/v2.6/me/messages?access_token='+process.env.FB_PAGE_TOKEN, formData: formData});
    })
  })

  robot.catchAll(/.+/, function(res) {
    // only telegram for now
    if (robot.adapterName != 'telegram') { return };
    if (_.has(res.message, 'photo')) {
      // rate limit
      var remain = deduct(res.envelope.user.id)
      if (remain < 0) {
        res.send(`Sorry, you ran out of your ${maxUse} uses of Deepdream. Hope you enjoyed!`)
        return
      }

      robot.logger.info("got telegram photo")
      res.send(`running DeepDream. This may take up to 2 minutes :) Meanwhile you have ${remain} uses left.`)
      runDeepdream(res.message)
      .then(function(outFilepath) {
        robot.logger.info('DeepDream outFile', outFilepath)
        robot.emit('telegram:invoke', 'sendPhoto', { chat_id: res.message.from.id, photo: fs.createReadStream(outFilepath) }, function (error, response) {
          if (error) { console.log(error) };
        });
      })
      .catch(console.log)
    };
  })
}
<commit_msg>add welcome msg for deepdream<commit_after>// dependencies
// Interface for Google Deepdream
const Response = require('hubot').Response
var _ = require('lomath')
var fs = require('fs')
var runDeepdream = require('../lib/deepdream')
var request = require('request')

// for rate limiting
const maxUse = 20
var counter = {
  'id': 0
}
// deduct usages for each user
function deduct(userId) {
  counter[userId] = (counter[userId]||maxUse)-1
  return counter[userId]
}

// quick test scripts
/* istanbul ignore next */
module.exports = function(robot) {
  // ensure bot name
  robot.respond(/hi|hello|hey/i, function(res) {
    res.send(`Hi, I'm ${robot.name}. Upload a photo to run DeepDream.`)
  })

  robot.on("fb_richMsg", function(envelope) {
    res = new Response(robot, envelope, undefined)
    // rate limit
    var remain = deduct(envelope.user.id)
    if (remain < 0) {
      res.send(`Sorry, you ran out of your ${maxUse} uses of Deepdream. Hope you enjoyed!`)
      return
    }

    res.send(`running DeepDream. This may take up to 2 minutes :) Meanwhile you have ${remain} uses left.`)
    robot.logger.info("got fb richMsg", envelope.attachments[0])
    runDeepdream(envelope)
    .then(function(outFilepath) {
      robot.logger.info('DeepDream outFile', outFilepath)
      var formData = {
        recipient: `{"id":"${envelope.user.id}"}`,
        message: '{"attachment":{"type":"image", "payload":{}}}',
        filedata: fs.createReadStream(outFilepath)
      }
      request.post({url:'https://graph.facebook.com/v2.6/me/messages?access_token='+process.env.FB_PAGE_TOKEN, formData: formData});
    })
  })

  robot.catchAll(/.+/, function(res) {
    // only telegram for now
    if (robot.adapterName != 'telegram') { return };
    if (_.has(res.message, 'photo')) {
      // rate limit
      var remain = deduct(res.envelope.user.id)
      if (remain < 0) {
        res.send(`Sorry, you ran out of your ${maxUse} uses of Deepdream. Hope you enjoyed!`)
        return
      }

      robot.logger.info("got telegram photo")
      res.send(`running DeepDream. This may take up to 2 minutes :) Meanwhile you have ${remain} uses left.`)
      runDeepdream(res.message)
      .then(function(outFilepath) {
        robot.logger.info('DeepDream outFile', outFilepath)
        robot.emit('telegram:invoke', 'sendPhoto', { chat_id: res.message.from.id, photo: fs.createReadStream(outFilepath) }, function (error, response) {
          if (error) { console.log(error) };
        });
      })
      .catch(console.log)
    };
  })
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule RelayPublic
 * @flow
 */

'use strict';

const RelayContainer = require('RelayContainer');
const RelayEnvironment = require('RelayEnvironment');
const RelayInternals = require('RelayInternals');
const RelayMutation = require('RelayMutation');
const RelayPropTypes = require('RelayPropTypes');
const RelayQL = require('RelayQL');
const RelayQueryCaching = require('RelayQueryCaching');
const RelayQueryConfig = require('RelayQueryConfig');
const RelayReadyStateRenderer = require('RelayReadyStateRenderer');
const RelayRenderer = require('RelayRenderer');
const RelayRootContainer = require('RelayRootContainer');
const RelayRoute = require('RelayRoute');
const RelayStore = require('RelayStore');

const createRelayQuery = require('createRelayQuery');
const getRelayQueries = require('getRelayQueries');
const isRelayContainer = require('isRelayContainer');

if (typeof global.__REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined') {
  global.__REACT_DEVTOOLS_GLOBAL_HOOK__._relayInternals = RelayInternals;
}

/**
 * Relay contains the set of public methods used to initialize and orchestrate
 * a React application that uses GraphQL to declare data dependencies.
 */
const RelayPublic = {
  Environment: RelayEnvironment,
  Mutation: RelayMutation,
  PropTypes: RelayPropTypes,
  QL: RelayQL,
  QueryConfig: RelayQueryConfig,
  ReadyStateRenderer: RelayReadyStateRenderer,
  Renderer: RelayRenderer,
  RootContainer: RelayRootContainer,
  Route: RelayRoute,
  Store: RelayStore,

  createContainer: RelayContainer.create,
  createQuery: createRelayQuery,
  getQueries: getRelayQueries,
  disableQueryCaching: RelayQueryCaching.disable,
  injectNetworkLayer: RelayStore.injectNetworkLayer.bind(RelayStore),
  injectTaskScheduler: RelayStore.injectTaskScheduler.bind(RelayStore),
  isContainer: isRelayContainer,
};

module.exports = RelayPublic;
<commit_msg>Add RelayGraphQLMutation to public Relay API<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule RelayPublic
 * @flow
 */

'use strict';

const RelayContainer = require('RelayContainer');
const RelayEnvironment = require('RelayEnvironment');
const RelayGraphQLMutation = require('RelayGraphQLMutation');
const RelayInternals = require('RelayInternals');
const RelayMutation = require('RelayMutation');
const RelayPropTypes = require('RelayPropTypes');
const RelayQL = require('RelayQL');
const RelayQueryCaching = require('RelayQueryCaching');
const RelayQueryConfig = require('RelayQueryConfig');
const RelayReadyStateRenderer = require('RelayReadyStateRenderer');
const RelayRenderer = require('RelayRenderer');
const RelayRootContainer = require('RelayRootContainer');
const RelayRoute = require('RelayRoute');
const RelayStore = require('RelayStore');

const createRelayQuery = require('createRelayQuery');
const getRelayQueries = require('getRelayQueries');
const isRelayContainer = require('isRelayContainer');

if (typeof global.__REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined') {
  global.__REACT_DEVTOOLS_GLOBAL_HOOK__._relayInternals = RelayInternals;
}

/**
 * Relay contains the set of public methods used to initialize and orchestrate
 * a React application that uses GraphQL to declare data dependencies.
 */
const RelayPublic = {
  Environment: RelayEnvironment,
  GraphQLMutation: RelayGraphQLMutation,
  Mutation: RelayMutation,
  PropTypes: RelayPropTypes,
  QL: RelayQL,
  QueryConfig: RelayQueryConfig,
  ReadyStateRenderer: RelayReadyStateRenderer,
  Renderer: RelayRenderer,
  RootContainer: RelayRootContainer,
  Route: RelayRoute,
  Store: RelayStore,

  createContainer: RelayContainer.create,
  createQuery: createRelayQuery,
  getQueries: getRelayQueries,
  disableQueryCaching: RelayQueryCaching.disable,
  injectNetworkLayer: RelayStore.injectNetworkLayer.bind(RelayStore),
  injectTaskScheduler: RelayStore.injectTaskScheduler.bind(RelayStore),
  isContainer: isRelayContainer,
};

module.exports = RelayPublic;
<|endoftext|>


<commit_before>import EventEmitter from 'eventemitter3'
import fs from 'fs'

import Speaker from 'speaker'
import {Reader as WavReader} from 'wav'
import Volume from 'pcm-volume'

import Omx from 'node-omxplayer'

const end = Symbol('end')

export default class Sound extends EventEmitter {
  constructor(){
    super()

    this.currentMode = null

    this.loopStates = new Set()
  }

  hasEnded(){
    this.currentMode = null
    this.emit(end)
  }

  async createEndPromise(){
    return new Promise(resolve => this.once(end, resolve))
  }

  async slowPlay(path, {volumeLevel}={}){
    if(this.currentMode) throw new Error('Player Busy')

    this.currentMode = 'omx'

    const omx = new Omx()
    omx.newSource(path, undefined, undefined, volumeLevel)
    omx.once('close', () => this.hasEnded())

    return this.createEndPromise()
  }

  async quickPlay(path, {volumeLevel=1}={}){
    if(this.currentMode) throw new Error('Player Busy')

    this.currentMode = 'speaker'

    const volume = new Volume(volumeLevel)
    const reader = new WavReader()

    // pipe the WAVE file to the Reader instance
    fs.createReadStream(path).pipe(reader)

    // the "format" event gets emitted at the end of the WAVE header
    reader.on('format', format => {
      // the WAVE header is stripped from the output of the reader
      const speaker = new Speaker(format)
      reader.pipe(volume)
      volume.pipe(speaker)

      this.hasEnded()
    })

    return this.createEndPromise()
  }

  slowLoop(path, {volumeLevel, symbol=Symbol(path)}={}){
    let resolveStatus = false
    let hoistedResolve = () => (resolveStatus = true)

    this.loopStates.add(symbol)

    this.slowPlay(path, {volumeLevel})
    .then(() => (this.loopStates.has(symbol) ? this.slowLoop(path, {volumeLevel, symbol}) : hoistedResolve()))

    return async () => {
      const hoistPromise = new Promise(resolve => (resolveStatus ? resolve() : (hoistedResolve = resolve)))
      this.loopStates.delete(symbol)

      return hoistPromise
    }
  }
}

export {end}
<commit_msg>🐛 Race Condition Attempt #3<commit_after>import EventEmitter from 'eventemitter3'
import fs from 'fs'

import Speaker from 'speaker'
import {Reader as WavReader} from 'wav'
import Volume from 'pcm-volume'

import Omx from 'node-omxplayer'

const end = Symbol('end')

export default class Sound extends EventEmitter {
  constructor(){
    super()

    this.currentMode = null

    this.loopStates = new Map()
  }

  hasEnded(){
    this.currentMode = null
    this.emit(end)
  }

  async createEndPromise(){
    return new Promise(resolve => this.once(end, resolve))
  }

  async slowPlay(path, {volumeLevel}={}){
    if(this.currentMode) throw new Error('Player Busy')

    this.currentMode = 'omx'

    const omx = new Omx()
    omx.newSource(path, undefined, undefined, volumeLevel)
    omx.once('close', () => this.hasEnded())

    return this.createEndPromise()
  }

  async quickPlay(path, {volumeLevel=1}={}){
    if(this.currentMode) throw new Error('Player Busy')

    this.currentMode = 'speaker'

    const volume = new Volume(volumeLevel)
    const reader = new WavReader()

    // pipe the WAVE file to the Reader instance
    fs.createReadStream(path).pipe(reader)

    // the "format" event gets emitted at the end of the WAVE header
    reader.on('format', format => {
      // the WAVE header is stripped from the output of the reader
      const speaker = new Speaker(format)
      reader.pipe(volume)
      volume.pipe(speaker)

      this.hasEnded()
    })

    return this.createEndPromise()
  }

  slowLoop(path, {volumeLevel, symbol=Symbol(path), root=true}={}){
    if(root) this.loopStates.set(symbol, null)

    this.slowPlay(path, {volumeLevel})
    .then(() => {
      if(!this.loopStates.get(symbol)) this.slowLoop(path, {volumeLevel, symbol, root: false})
      else this.loopStates.get(symbol)()
    })

    return () => new Promise(resolve => this.loopStates.set(symbol, resolve))
  }
}

export {end}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

class Spritesheet extends React.Component {
  constructor(props) {
    super(props);

    this.id = 'react-responsive-spritesheet--' + Math.random().toString(36).substring(7);
    this.spriteEl = this.spriteElContainer = this.spriteElMove = this.intervalSprite = null;
    this.startAt = this.props.startAt ? this.setStartAt(this.props.startAt) : 0;
    this.endAt = this.setEndAt(this.props.endAt);
    this.frame = this.startAt ? this.startAt : 0;
    this.fps = this.setFps(this.props.fps);
    this.steps = this.props.steps;
    this.completeLoopCicles = 0;
    this.isPlaying = false;
    this.spriteScale = 1;
  }

  componentDidMount() {
    this.init();
  }

  renderElements() {
    let containerBackgroundImage = '';
    let containerBackgroundSize = '';
    let containerBackgroundRepeat = '';
    let containerBackgroundPosition = '';
    if (this.props.background) {
      containerBackgroundImage = 'url(' + this.props.background + ')';
      containerBackgroundSize = this.props.backgroundSize ? this.props.backgroundSize : 'cover';
      containerBackgroundRepeat = this.props.backgroundRepeat ? this.props.backgroundRepeat : 'no-repeat';
      containerBackgroundPosition = this.props.backgroundPosition ? this.props.backgroundPosition : '';
    }

    let containerStyles = {
      position: 'relative',
      overflow: 'hidden',
      width: `${this.props.widthFrame}px`,
      height: `${this.props.heightFrame}px`,
      transform:`scale(${this.spriteScale})`,
      transformOrigin: '0 50%',
      backgroundImage: containerBackgroundImage,
      backgroundSize: containerBackgroundSize,
      backgroundRepeat: containerBackgroundRepeat,
      backgroundPosition: containerBackgroundPosition
    }

    let moveStyles = {
      overflow: 'hidden',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat',
      display: 'table',
      backgroundImage: 'url(' + this.props.image + ')',
      width: `${this.props.widthFrame}px`,
      height: `${this.props.heightFrame}px`,
      transformOrigin: '0 50%'
    }

    let elMove = React.createElement('div', { className: 'react-responsive-spritesheet-container__move', style: moveStyles });
    let elContainer = React.createElement('div', { className: 'react-responsive-spritesheet-container', style: containerStyles }, elMove);
    let elSprite = React.createElement('div', {
      className: `react-responsive-spritesheet ${this.id} ${this.props.className ? this.props.className : ''}`,
      style: this.props.style,
      onClick: this.props.onClick ? this.props.onClick.bind(this.setInstance(), this) : null,
      onDoubleClick: this.props.onDoubleClick ? this.props.onDoubleClick.bind(this.setInstance(), this) : null,
      onMouseMove: this.props.onMouseMove ? this.props.onMouseMove.bind(this.setInstance(), this) : null,
      onMouseEnter: this.props.onMouseEnter ? this.props.onMouseEnter.bind(this.setInstance(), this) : null,
      onMouseLeave: this.props.onMouseLeave ? this.props.onMouseLeave.bind(this.setInstance(), this) : null,
      onMouseOver: this.props.onMouseOver ? this.props.onMouseOver.bind(this.setInstance(), this) : null,
      onMouseOut: this.props.onMouseOut ? this.props.onMouseOut.bind(this.setInstance(), this) : null,
      onMouseDown: this.props.onMouseDown ? this.props.onMouseDown.bind(this.setInstance(), this) : null,
      onMouseUp: this.props.onMouseUp ? this.props.onMouseUp.bind(this.setInstance(), this) : null
    }, elContainer);

    return elSprite;
  }

  init() {
    this.spriteEl = document.querySelector('.' + this.id);
    this.spriteElContainer = this.spriteEl.querySelector('.react-responsive-spritesheet-container');
    this.spriteElMove = this.spriteElContainer.querySelector('.react-responsive-spritesheet-container__move');

    this.resize(false);
    window.addEventListener('resize', this.resize.bind(this));
    this.moveImage(false);
    setTimeout(() => {
      this.resize(false);
    }, 10);

    if (this.props.autoplay !== false) {
      this.play(true);
    }

    if (this.props.getInstance) this.props.getInstance(this.setInstance());
    if (this.props.onInit) this.props.onInit(this.setInstance.bind(this));
  }

  resize(callback = true) {
    this.spriteScale = this.spriteEl.offsetWidth / this.props.widthFrame;
    this.spriteElContainer.style.transform = `scale(${this.spriteScale})`;
    if(callback && this.props.onResize) this.props.onResize(this.setInstance());
  }

  moveImage(play = true) {
    if (this.props.orientation === 'vertical') {
      this.spriteElMove.style.backgroundPosition = `0 -${this.props.heightFrame * this.frame}px`;
    } else {
      this.spriteElMove.style.backgroundPosition = `-${this.props.widthFrame * this.frame}px 0`;
    }

    if(this.props.onEnterFrame){
      this.props.onEnterFrame.map((frameAction, i) => {
        if(frameAction.frame === this.frame && frameAction.callback){
          frameAction.callback();
        }
      });
    }

    if (play) {
      this.frame += 1;
      if (this.props.onEachFrame) this.props.onEachFrame(this.setInstance());
    }
  }

  setInstance(){
    return {
      play: this.play.bind(this),
      pause: this.pause.bind(this),
      goToAndPlay: this.goToAndPlay.bind(this),
      goToAndPause: this.goToAndPause.bind(this),
      setStartAt: this.setStartAt.bind(this),
      setEndAt: this.setEndAt.bind(this),
      setFps: this.setFps.bind(this),
      getInfo: this.getInfo.bind(this)
    };
  }

  getInfo(param){
    switch(param){
      case 'frame': {
        return this.frame;
      }
      case 'fps': {
        return this.fps;
      }
      case 'steps': {
        return this.steps;
      }
      case 'width': {
        return this.spriteElContainer.getBoundingClientRect().width;
      }
      case 'height': {
        return this.spriteElContainer.getBoundingClientRect().height;
      }
      case 'scale': {
        return this.spriteScale;
      }
      case 'isPlaying': {
        return this.isPlaying;
      }
      case 'isPaused': {
        return !this.isPlaying;
      }
      case 'completeLoopCicles': {
        return this.completeLoopCicles;
      }
      default: {
        console.error(`Invalid param \`${param}\` requested by Spritesheet.getinfo(). See the documentation on https://github.com/danilosetra/react-responsive-spritesheet`);
        break;
      }
    }
  }

  setStartAt(frame){
    this.startAt = frame - 1;
    return this.startAt;
  }

  setEndAt(frame){
    this.endAt = frame;
    return this.endAt;
  }

  setFps(fps){
    this.fps = fps;
    return this.fps;
  }

  play(withTimeout = false) {
    if (!this.isPlaying) {
      setTimeout(() => {
        if(this.props.onPlay) this.props.onPlay(this.setInstance());
        this.intervalSprite = setInterval(() => {
          this.moveImage();

          if (this.frame === this.steps || this.frame === this.endAt) {
            if (this.props.loop) {
              if(this.props.onLoopComplete) this.props.onLoopComplete(this.setInstance());
              this.completeLoopCicles += 1;
              this.frame = this.startAt ? this.startAt : 0;
            } else {
              this.pause();
            }
          }
        }, 1000 / this.fps);
      }, withTimeout ? (this.props.timeout ? this.props.timeout : 0) : 0);
      this.isPlaying = true;
    }
  }

  pause() {
    this.isPlaying = false;
    clearInterval(this.intervalSprite);
    if(this.props.onPause) this.props.onPause(this.setInstance());
  }

  goToAndPlay(frame = 0){
    this.frame = frame;
    this.play();
  }

  goToAndPause(frame = 0){
    this.pause();
    this.frame = frame;
    this.moveImage();
  }

  render() {
    return this.renderElements();
  }
}

Spritesheet.propTypes = {
  className: PropTypes.string,
  style: PropTypes.object,
  image: PropTypes.string.isRequired,
  widthFrame: PropTypes.number.isRequired,
  heightFrame: PropTypes.number.isRequired,
  steps: PropTypes.number.isRequired,
  fps: PropTypes.number.isRequired,
  orientation: PropTypes.string.isRequired,
  timeout: PropTypes.number,
  autoplay: PropTypes.bool,
  loop: PropTypes.bool,
  startAt: PropTypes.number,
  endAt: PropTypes.number,
  background: PropTypes.string,
  backgroundSize: PropTypes.string,
  backgroundRepeat: PropTypes.string,
  backgroundPosition: PropTypes.string,
  getInstance: PropTypes.func,
  onClick: PropTypes.func,
  onDoubleClick: PropTypes.func,
  onMouseMove: PropTypes.func,
  onMouseEnter: PropTypes.func,
  onMouseLeave: PropTypes.func,
  onMouseOver: PropTypes.func,
  onMouseOut: PropTypes.func,
  onMouseDown: PropTypes.func,
  onMouseUp: PropTypes.func,
  onInit: PropTypes.func,
  onResize: PropTypes.func,
  onPlay: PropTypes.func,
  onPause: PropTypes.func,
  onLoopComplete: PropTypes.func,
  onEachFrame: PropTypes.func,
  onEnterFrame: PropTypes.array
};

export default Spritesheet;<commit_msg>creating setFps function is done, closes #12<commit_after>import React from 'react';
import PropTypes from 'prop-types';

class Spritesheet extends React.Component {
  constructor(props) {
    super(props);

    this.id = 'react-responsive-spritesheet--' + Math.random().toString(36).substring(7);
    this.spriteEl = this.spriteElContainer = this.spriteElMove = null;
    this.intervalSprite = false;
    this.startAt = this.props.startAt ? this.setStartAt(this.props.startAt) : 0;
    this.endAt = this.setEndAt(this.props.endAt);
    this.frame = this.startAt ? this.startAt : 0;
    this.fps = this.props.fps;
    this.steps = this.props.steps;
    this.completeLoopCicles = 0;
    this.isPlaying = false;
    this.spriteScale = 1;
  }

  componentDidMount() {
    this.init();
  }

  renderElements() {
    let containerBackgroundImage = '';
    let containerBackgroundSize = '';
    let containerBackgroundRepeat = '';
    let containerBackgroundPosition = '';
    if (this.props.background) {
      containerBackgroundImage = 'url(' + this.props.background + ')';
      containerBackgroundSize = this.props.backgroundSize ? this.props.backgroundSize : 'cover';
      containerBackgroundRepeat = this.props.backgroundRepeat ? this.props.backgroundRepeat : 'no-repeat';
      containerBackgroundPosition = this.props.backgroundPosition ? this.props.backgroundPosition : '';
    }

    let containerStyles = {
      position: 'relative',
      overflow: 'hidden',
      width: `${this.props.widthFrame}px`,
      height: `${this.props.heightFrame}px`,
      transform:`scale(${this.spriteScale})`,
      transformOrigin: '0 50%',
      backgroundImage: containerBackgroundImage,
      backgroundSize: containerBackgroundSize,
      backgroundRepeat: containerBackgroundRepeat,
      backgroundPosition: containerBackgroundPosition
    }

    let moveStyles = {
      overflow: 'hidden',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat',
      display: 'table',
      backgroundImage: 'url(' + this.props.image + ')',
      width: `${this.props.widthFrame}px`,
      height: `${this.props.heightFrame}px`,
      transformOrigin: '0 50%'
    }

    let elMove = React.createElement('div', { className: 'react-responsive-spritesheet-container__move', style: moveStyles });
    let elContainer = React.createElement('div', { className: 'react-responsive-spritesheet-container', style: containerStyles }, elMove);
    let elSprite = React.createElement('div', {
      className: `react-responsive-spritesheet ${this.id} ${this.props.className ? this.props.className : ''}`,
      style: this.props.style,
      onClick: this.props.onClick ? this.props.onClick.bind(this.setInstance(), this) : null,
      onDoubleClick: this.props.onDoubleClick ? this.props.onDoubleClick.bind(this.setInstance(), this) : null,
      onMouseMove: this.props.onMouseMove ? this.props.onMouseMove.bind(this.setInstance(), this) : null,
      onMouseEnter: this.props.onMouseEnter ? this.props.onMouseEnter.bind(this.setInstance(), this) : null,
      onMouseLeave: this.props.onMouseLeave ? this.props.onMouseLeave.bind(this.setInstance(), this) : null,
      onMouseOver: this.props.onMouseOver ? this.props.onMouseOver.bind(this.setInstance(), this) : null,
      onMouseOut: this.props.onMouseOut ? this.props.onMouseOut.bind(this.setInstance(), this) : null,
      onMouseDown: this.props.onMouseDown ? this.props.onMouseDown.bind(this.setInstance(), this) : null,
      onMouseUp: this.props.onMouseUp ? this.props.onMouseUp.bind(this.setInstance(), this) : null
    }, elContainer);

    return elSprite;
  }

  init() {
    this.spriteEl = document.querySelector('.' + this.id);
    this.spriteElContainer = this.spriteEl.querySelector('.react-responsive-spritesheet-container');
    this.spriteElMove = this.spriteElContainer.querySelector('.react-responsive-spritesheet-container__move');

    this.resize(false);
    window.addEventListener('resize', this.resize.bind(this));
    this.moveImage(false);
    setTimeout(() => {
      this.resize(false);
    }, 10);

    if (this.props.autoplay !== false) {
      this.play(true);
    }

    if (this.props.getInstance) this.props.getInstance(this.setInstance());
    if (this.props.onInit) this.props.onInit(this.setInstance.bind(this));
  }

  resize(callback = true) {
    this.spriteScale = this.spriteEl.offsetWidth / this.props.widthFrame;
    this.spriteElContainer.style.transform = `scale(${this.spriteScale})`;
    if(callback && this.props.onResize) this.props.onResize(this.setInstance());
  }

  moveImage(play = true) {
    if (this.props.orientation === 'vertical') {
      this.spriteElMove.style.backgroundPosition = `0 -${this.props.heightFrame * this.frame}px`;
    } else {
      this.spriteElMove.style.backgroundPosition = `-${this.props.widthFrame * this.frame}px 0`;
    }

    if(this.props.onEnterFrame){
      this.props.onEnterFrame.map((frameAction, i) => {
        if(frameAction.frame === this.frame && frameAction.callback){
          frameAction.callback();
        }
      });
    }

    if (play) {
      this.frame += 1;
      if (this.props.onEachFrame) this.props.onEachFrame(this.setInstance());
    }

    if(this.isPlaying){
      if (this.frame === this.steps || this.frame === this.endAt) {
        if (this.props.loop) {
          if(this.props.onLoopComplete) this.props.onLoopComplete(this.setInstance());
          this.completeLoopCicles += 1;
          this.frame = this.startAt ? this.startAt : 0;
        } else {
          this.pause();
        }
      }
    }
  }

  setInstance(){
    return {
      play: this.play.bind(this),
      pause: this.pause.bind(this),
      goToAndPlay: this.goToAndPlay.bind(this),
      goToAndPause: this.goToAndPause.bind(this),
      setStartAt: this.setStartAt.bind(this),
      setEndAt: this.setEndAt.bind(this),
      setFps: this.setFps.bind(this),
      getInfo: this.getInfo.bind(this)
    };
  }

  getInfo(param){
    switch(param){
      case 'frame': {
        return this.frame;
      }
      case 'fps': {
        return this.fps;
      }
      case 'steps': {
        return this.steps;
      }
      case 'width': {
        return this.spriteElContainer.getBoundingClientRect().width;
      }
      case 'height': {
        return this.spriteElContainer.getBoundingClientRect().height;
      }
      case 'scale': {
        return this.spriteScale;
      }
      case 'isPlaying': {
        return this.isPlaying;
      }
      case 'isPaused': {
        return !this.isPlaying;
      }
      case 'completeLoopCicles': {
        return this.completeLoopCicles;
      }
      default: {
        console.error(`Invalid param \`${param}\` requested by Spritesheet.getinfo(). See the documentation on https://github.com/danilosetra/react-responsive-spritesheet`);
        break;
      }
    }
  }

  setStartAt(frame){
    this.startAt = frame - 1;
    return this.startAt;
  }

  setEndAt(frame){
    this.endAt = frame;
    return this.endAt;
  }

  setFps(fps){
    this.fps = fps;
    this.setIntervalPlayFunctions();
  }

  play(withTimeout = false, setNewInterval = false) {
    if (!this.isPlaying) {
      setTimeout(() => {
        if(this.props.onPlay) this.props.onPlay(this.setInstance());
        this.setIntervalPlayFunctions();
        this.isPlaying = true;
      }, withTimeout ? (this.props.timeout ? this.props.timeout : 0) : 0);
    }
  }

  setIntervalPlayFunctions(){
    if(this.intervalSprite) clearInterval(this.intervalSprite);
    this.intervalSprite = setInterval(() => {
      if (this.isPlaying) {
        this.moveImage();
      }
    }, 1000 / this.fps);
  }

  pause() {
    this.isPlaying = false;
    clearInterval(this.intervalSprite);
    if(this.props.onPause) this.props.onPause(this.setInstance());
  }

  goToAndPlay(frame = 0){
    this.frame = frame;
    this.play();
  }

  goToAndPause(frame = 0){
    this.pause();
    this.frame = frame;
    this.moveImage();
  }

  render() {
    return this.renderElements();
  }
}

Spritesheet.propTypes = {
  className: PropTypes.string,
  style: PropTypes.object,
  image: PropTypes.string.isRequired,
  widthFrame: PropTypes.number.isRequired,
  heightFrame: PropTypes.number.isRequired,
  steps: PropTypes.number.isRequired,
  fps: PropTypes.number.isRequired,
  orientation: PropTypes.string.isRequired,
  timeout: PropTypes.number,
  autoplay: PropTypes.bool,
  loop: PropTypes.bool,
  startAt: PropTypes.number,
  endAt: PropTypes.number,
  background: PropTypes.string,
  backgroundSize: PropTypes.string,
  backgroundRepeat: PropTypes.string,
  backgroundPosition: PropTypes.string,
  getInstance: PropTypes.func,
  onClick: PropTypes.func,
  onDoubleClick: PropTypes.func,
  onMouseMove: PropTypes.func,
  onMouseEnter: PropTypes.func,
  onMouseLeave: PropTypes.func,
  onMouseOver: PropTypes.func,
  onMouseOut: PropTypes.func,
  onMouseDown: PropTypes.func,
  onMouseUp: PropTypes.func,
  onInit: PropTypes.func,
  onResize: PropTypes.func,
  onPlay: PropTypes.func,
  onPause: PropTypes.func,
  onLoopComplete: PropTypes.func,
  onEachFrame: PropTypes.func,
  onEnterFrame: PropTypes.array
};

export default Spritesheet;<|endoftext|>


<commit_before><commit_msg>made the render sprite function more generic for use with other entities<commit_after><|endoftext|>


<commit_before>document.getElementById("id_logic_version").innerHTML = "Logic version: 2018.12.10.1";
document.getElementById("id_start").addEventListener("click", get_position);

//---------------------------
function get_position()
{
	navigator.geolocation.getCurrentPosition(on_gps_ok, on_error);
}
//---------------------------
function on_gps_ok(e)
{
	document.getElementById("id_lat").innerHTML = e.coords.latitude;
	document.getElementById("id_long").innerHTML = e.coords.longitude;
	document.getElementById("id_acc").innerHTML = e.coords.accuracy;
}
//---------------------------
function on_error(e)
{
	alert("Error" + e.error);
}
//---------------------------<commit_msg>more labels<commit_after>document.getElementById("id_logic_version").innerHTML = "Logic version: 2019.05.23.0";
document.getElementById("id_start").addEventListener("click", get_position);

//---------------------------
function get_position()
{
	navigator.geolocation.getCurrentPosition(on_gps_ok, on_error);
}
//---------------------------
function on_gps_ok(e)
{
	document.getElementById("id_lat").innerHTML = "Latitude = " + e.coords.latitude;
	document.getElementById("id_long").innerHTML = "Longitude = " + e.coords.longitude;
	document.getElementById("id_acc").innerHTML = "Accuracy = " + e.coords.accuracy;
}
//---------------------------
function on_error(e)
{
	alert("Error" + e.error);
}
//---------------------------<|endoftext|>


<commit_before>import classNames from 'classnames';
import DOMUtil from '../Util/DOMUtil';
import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
import Util from '../Util/Util';
import VirtualList from '../VirtualList/VirtualList';

const MAX_CACHE_SIZE = 10000;

let sortData = (columns, data, sortBy) => {
  if (sortBy.order === undefined || sortBy.prop === undefined) {
    return data;
  }

  let sortFunction;

  columns.forEach((column) => {
    if (column.prop === sortBy.prop) {
      sortFunction = column.sortFunction;
    }
  });

  if (sortFunction) {
    // Use custom sort method if specified.
    data = Util.sortBy(data, sortFunction(sortBy.prop, sortBy.order));
  } else {
    // Otherwise, use default sorting.
    data = Util.sortBy(data, sortBy.prop);
  }

  if (sortBy.order === 'desc') {
    data.reverse();
  }

  return data;
};

let getClassName = (column, sortBy, data, columns) => {
  if (Util.isFunction(column.className)) {
    return column.className(
      column.prop, sortBy, data, columns
    );
  }

  return column.className || '';
};

class Table extends React.Component {
  constructor() {
    super();
    this.state = {
      sortBy: {}
    };
    this.cachedCells = {};
    this.cachedIDs = [];
    this.container = window;
  }

  componentWillMount() {
    if (!!this.props.sortBy) {
      this.setState(
        {sortBy: this.props.sortBy},
        this.handleSort.bind(this, this.props.sortBy.prop, {toggle: false})
      );
    }
  }

  componentDidMount() {
    this.updateHeight();
  }

  componentWillReceiveProps() {
    this.updateHeight();

    if (this.props.sortBy.prop) {
      this.handleSort(this.props.sortBy.prop, {toggle: false});
    }
  }

  checkFullCache() {
    if (this.cachedIDs.length < MAX_CACHE_SIZE) {
      return;
    }

    let lastID = this.cachedIDs.shift();
    delete this.cachedCells[lastID];
  }

  addToCache(id, element) {
    this.cachedCells[id] = element;
    this.cachedIDs.push(id);
    this.checkFullCache();
  }

  updateHeight() {
    let {props, state, refs} = this;

    if (props.containerSelector && this.container === window) {
      this.container = DOMUtil.closest(
        ReactDOM.findDOMNode(this), props.containerSelector
      ) || window;
    }

    if (props.itemHeight == null &&
      state.itemHeight == null &&
      refs.itemHeightContainer != null) {
      // Calculate content height only once and when node is ready
      let itemHeight = DOMUtil.getComputedDimensions(
        ReactDOM.findDOMNode(refs.itemHeightContainer).querySelector('tr')
      ).height;
      this.setState({itemHeight});
    }
  }

  buildUniqueID(cellClassName, cellValue, prop) {
    return prop + cellClassName + cellValue;
  }

  getHeaders(headers, sortBy) {
    let buildSortAttributes = (header) => {
      let sortEvent = this.handleSort.bind(this, header.prop);
      return {
        onClick: sortEvent,
        tabIndex: 0,
        'aria-sort': this.state.sortBy.order,
        'aria-label':
          `${header.prop}: activate to sort column ${this.state.sortBy.order}`
      };
    };

    return headers.map((header, index) => {
      let order, heading;
      let attributes = {};

      // Only add sorting events if the column has a value for 'prop'
      // and the 'sorting' property is true.
      if (header.sortable !== false && 'prop' in header) {
        attributes = buildSortAttributes(header);
        order = this.state.sortBy.order;
      }

      // If the heading property is a method, then pass to it the options and
      // render the result. Otherwise, display the value.
      if (Util.isFunction(header.heading)) {
        heading = header.heading(header.prop, order, sortBy);
      } else {
        heading = header.heading;
      }

      attributes.className = getClassName(
        header, this.state.sortBy, null, this.props.columns
      );
      attributes.key = index;

      return (

          {heading}

      );
    });
  }

  getBufferItem(columns, styles) {
    return

;
  }

  getEmptyRowCell(columns) {
    return (

          {this.props.emptyMessage}

    );
  }

  getCellValue(row, prop, column) {
    let {getValue} = column;
    if (getValue && typeof getValue === 'function') {
      return getValue(row, prop);
    }

    return row[prop];
  }

  getRowCells(columns, sortBy, buildRowOptions, row, rowIndex) {
    let rowCells = columns.map((column, index) => {
      let cellClassName = getClassName(column, sortBy, row, columns);
      let prop = column.prop;
      let cellValue = this.getCellValue(row, prop, column);
      let cellID;

      if (column.cacheCell === true) {
        cellID = this.buildUniqueID(cellClassName, cellValue, prop);
      }

      // Skip build cell if we have it memoized
      if (cellID === undefined || this.cachedCells[cellID] == null) {
        if (column.render) {
          cellValue = column.render(prop, row);
        }

        if (cellValue === undefined) {
          cellValue = column.defaultContent;
          cellClassName += ' empty-cell';
        }

        let cellElement = (

            {cellValue}

        );

        if (!column.cacheCell) {
          return cellElement;
        }

        this.addToCache(cellID, cellElement);
      }

      return this.cachedCells[cellID];
    });

    return (

        {rowCells}

    );
  }

  handleSort(prop, options) {
    let sortBy = this.state.sortBy;
    let onSortCallback = this.props.onSortCallback;
    options = Util.extend({
      toggle: true
    }, options);

    if (options.toggle) {
      let order;

      if (sortBy.order === 'desc' || sortBy.prop !== prop) {
        order = 'asc';
      } else {
        order = 'desc';
      }

      this.setState({
        sortBy: {order, prop}
      });
    }

    if (Util.isFunction(onSortCallback)) {
      onSortCallback(sortBy);
    }
  }

  getTBody(columns, data, sortBy, itemHeight) {
    let buildRowOptions = this.props.buildRowOptions;
    let childToMeasure;

    if (itemHeight === 0 && data.length) {
      childToMeasure = this.getRowCells(columns, sortBy, buildRowOptions, data[0], -1);
      return (

          {childToMeasure}

      );
    }

    if (data.length === 0) {
      return (

          {this.getEmptyRowCell(columns)}

      );
    }

    return (
      <VirtualList
        container={this.container}
        itemBuffer={70}
        itemHeight={itemHeight}
        items={sortData(columns, data, sortBy)}
        renderBufferItem={this.getBufferItem.bind(this, columns)}
        renderItem={this.getRowCells.bind(this, columns, sortBy, buildRowOptions)}
        scrollDelay={200}
        tagName="tbody" />
    );
  }

  render() {
    let {props, state} = this;
    let {columns, data} = props;
    let classes = classNames(props.className, 'flush-bottom');
    let sortBy = state.sortBy;
    let itemHeight = state.itemHeight || props.itemHeight || 0;

    return (

          {props.colGroup}

              {this.getHeaders(columns, sortBy)}

          {this.getTBody(columns, data, sortBy, itemHeight)}

    );
  }
}

Table.defaultProps = {
  buildRowOptions: () => { return {}; },
  sortBy: {},
  emptyMessage: 'No data'
};

Table.propTypes = {
  // Optional attributes to be passed to the row elements.
  buildRowOptions: PropTypes.func,

  className: PropTypes.string,

  // Optional colgroup component.
  colGroup: PropTypes.object,

  // Define how columns should be rendered and if they are sortable.
  columns: PropTypes.arrayOf(
    PropTypes.shape({
      // Attributes to pass down to each column item.
      attributes: PropTypes.object,

      // Class to give to each column item.
      // Can be a function to programmatically create a class.
      className: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func
      ]),

      // Content to default to in the case of no data for the prop.
      defaultContent: PropTypes.string,

      // Enable caching of cells for better performance. Not cached by default.
      cacheCell: PropTypes.bool,

      // Function to render the header of the column. Can also be a string.
      // The arguments to the function will be:
      // prop (prop to sort by), order (asc/desc), sortBy (the sort function)
      heading: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func
      ]).isRequired,

      // What prop of the data object to use.
      prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

      // If true, the column will sort on column heading click.
      sortable: PropTypes.bool,

      // Custom sorting function. If this function returns null,
      // it will fallback to default sorting.
      sortFunction: PropTypes.func
    })
  ).isRequired,

  // Optional selector of the parent element that has a scrollbar in order to
  // listen to its scroll event.
  containerSelector: PropTypes.string,

  // Data to display in the table.
  // Make sure to clone the data, cannot be modified!
  data: PropTypes.array.isRequired,

  // Text to show if there is no data.
  emptyMessage: PropTypes.string,

  // Optional item height for the scroll table. If not provided, it will render
  // once to measure the height of the first child.
  // NB: Initial render will stop any ongoing animation, if this is not provided
  itemHeight: PropTypes.number,

  // Optional callback function when sorting is complete.
  onSortCallback: PropTypes.func,

  // Optional default sorting criteria.
  sortBy: PropTypes.shape({
    order: PropTypes.oneOf(['asc', 'desc']),
    prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
  })
};

module.exports = Table;
<commit_msg>Address feedback<commit_after>import classNames from 'classnames';
import DOMUtil from '../Util/DOMUtil';
import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
import Util from '../Util/Util';
import VirtualList from '../VirtualList/VirtualList';

const MAX_CACHE_SIZE = 10000;

let sortData = (columns, data, sortBy) => {
  if (sortBy.order === undefined || sortBy.prop === undefined) {
    return data;
  }

  let sortFunction;

  columns.forEach((column) => {
    if (column.prop === sortBy.prop) {
      sortFunction = column.sortFunction;
    }
  });

  if (sortFunction) {
    // Use custom sort method if specified.
    data = Util.sortBy(data, sortFunction(sortBy.prop, sortBy.order));
  } else {
    // Otherwise, use default sorting.
    data = Util.sortBy(data, sortBy.prop);
  }

  if (sortBy.order === 'desc') {
    data.reverse();
  }

  return data;
};

let getClassName = (column, sortBy, data, columns) => {
  if (Util.isFunction(column.className)) {
    return column.className(
      column.prop, sortBy, data, columns
    );
  }

  return column.className || '';
};

class Table extends React.Component {
  constructor() {
    super();
    this.state = {
      sortBy: {}
    };
    this.cachedCells = {};
    this.cachedIDs = [];
    this.container = window;
  }

  componentWillMount() {
    if (this.props.sortBy != null) {
      this.setState(
        {sortBy: this.props.sortBy},
        this.handleSort.bind(this, this.props.sortBy.prop, {toggle: false})
      );
    }
  }

  componentDidMount() {
    this.updateHeight();
  }

  componentWillReceiveProps() {
    this.updateHeight();

    if (this.props.sortBy.prop) {
      this.handleSort(this.props.sortBy.prop, {toggle: false});
    }
  }

  checkFullCache() {
    if (this.cachedIDs.length < MAX_CACHE_SIZE) {
      return;
    }

    let lastID = this.cachedIDs.shift();
    delete this.cachedCells[lastID];
  }

  addToCache(id, element) {
    this.cachedCells[id] = element;
    this.cachedIDs.push(id);
    this.checkFullCache();
  }

  updateHeight() {
    let {props, state, refs} = this;

    if (props.containerSelector && this.container === window) {
      this.container = DOMUtil.closest(
        ReactDOM.findDOMNode(this), props.containerSelector
      ) || window;
    }

    if (props.itemHeight == null &&
      state.itemHeight == null &&
      refs.itemHeightContainer != null) {
      // Calculate content height only once and when node is ready
      let itemHeight = DOMUtil.getComputedDimensions(
        ReactDOM.findDOMNode(refs.itemHeightContainer).querySelector('tr')
      ).height;
      this.setState({itemHeight});
    }
  }

  buildUniqueID(cellClassName, cellValue, prop) {
    return prop + cellClassName + cellValue;
  }

  getHeaders(headers, sortBy) {
    let buildSortAttributes = (header) => {
      let sortEvent = this.handleSort.bind(this, header.prop);
      return {
        onClick: sortEvent,
        tabIndex: 0,
        'aria-sort': this.state.sortBy.order,
        'aria-label':
          `${header.prop}: activate to sort column ${this.state.sortBy.order}`
      };
    };

    return headers.map((header, index) => {
      let order, heading;
      let attributes = {};

      // Only add sorting events if the column has a value for 'prop'
      // and the 'sorting' property is true.
      if (header.sortable !== false && 'prop' in header) {
        attributes = buildSortAttributes(header);
        order = this.state.sortBy.order;
      }

      // If the heading property is a method, then pass to it the options and
      // render the result. Otherwise, display the value.
      if (Util.isFunction(header.heading)) {
        heading = header.heading(header.prop, order, sortBy);
      } else {
        heading = header.heading;
      }

      attributes.className = getClassName(
        header, this.state.sortBy, null, this.props.columns
      );
      attributes.key = index;

      return (

          {heading}

      );
    });
  }

  getBufferItem(columns, styles) {
    return

;
  }

  getEmptyRowCell(columns) {
    return (

          {this.props.emptyMessage}

    );
  }

  getCellValue(row, prop, column) {
    let {getValue} = column;
    if (getValue && typeof getValue === 'function') {
      return getValue(row, prop);
    }

    return row[prop];
  }

  getRowCells(columns, sortBy, buildRowOptions, row, rowIndex) {
    let rowCells = columns.map((column, index) => {
      let cellClassName = getClassName(column, sortBy, row, columns);
      let prop = column.prop;
      let cellValue = this.getCellValue(row, prop, column);
      let cellID;

      if (column.cacheCell === true) {
        cellID = this.buildUniqueID(cellClassName, cellValue, prop);
      }

      // Skip build cell if we have it memoized
      if (cellID === undefined || this.cachedCells[cellID] == null) {
        if (column.render) {
          cellValue = column.render(prop, row);
        }

        if (cellValue === undefined) {
          cellValue = column.defaultContent;
          cellClassName += ' empty-cell';
        }

        let cellElement = (

            {cellValue}

        );

        if (!column.cacheCell) {
          return cellElement;
        }

        this.addToCache(cellID, cellElement);
      }

      return this.cachedCells[cellID];
    });

    return (

        {rowCells}

    );
  }

  handleSort(prop, options) {
    let sortBy = this.state.sortBy;
    let onSortCallback = this.props.onSortCallback;
    options = Util.extend({
      toggle: true
    }, options);

    if (options.toggle) {
      let order;

      if (sortBy.order === 'desc' || sortBy.prop !== prop) {
        order = 'asc';
      } else {
        order = 'desc';
      }

      this.setState({
        sortBy: {order, prop}
      });
    }

    if (Util.isFunction(onSortCallback)) {
      onSortCallback(sortBy);
    }
  }

  getTBody(columns, data, sortBy, itemHeight) {
    let buildRowOptions = this.props.buildRowOptions;
    let childToMeasure;

    if (itemHeight === 0 && data.length) {
      childToMeasure = this.getRowCells(columns, sortBy, buildRowOptions, data[0], -1);
      return (

          {childToMeasure}

      );
    }

    if (data.length === 0) {
      return (

          {this.getEmptyRowCell(columns)}

      );
    }

    return (
      <VirtualList
        container={this.container}
        itemBuffer={70}
        itemHeight={itemHeight}
        items={sortData(columns, data, sortBy)}
        renderBufferItem={this.getBufferItem.bind(this, columns)}
        renderItem={this.getRowCells.bind(this, columns, sortBy, buildRowOptions)}
        scrollDelay={200}
        tagName="tbody" />
    );
  }

  render() {
    let {props, state} = this;
    let {columns, data} = props;
    let classes = classNames(props.className, 'flush-bottom');
    let sortBy = state.sortBy;
    let itemHeight = state.itemHeight || props.itemHeight || 0;

    return (

          {props.colGroup}

              {this.getHeaders(columns, sortBy)}

          {this.getTBody(columns, data, sortBy, itemHeight)}

    );
  }
}

Table.defaultProps = {
  buildRowOptions: () => { return {}; },
  sortBy: {},
  emptyMessage: 'No data'
};

Table.propTypes = {
  // Optional attributes to be passed to the row elements.
  buildRowOptions: PropTypes.func,

  className: PropTypes.string,

  // Optional colgroup component.
  colGroup: PropTypes.object,

  // Define how columns should be rendered and if they are sortable.
  columns: PropTypes.arrayOf(
    PropTypes.shape({
      // Attributes to pass down to each column item.
      attributes: PropTypes.object,

      // Class to give to each column item.
      // Can be a function to programmatically create a class.
      className: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func
      ]),

      // Content to default to in the case of no data for the prop.
      defaultContent: PropTypes.string,

      // Enable caching of cells for better performance. Not cached by default.
      cacheCell: PropTypes.bool,

      // Function to render the header of the column. Can also be a string.
      // The arguments to the function will be:
      // prop (prop to sort by), order (asc/desc), sortBy (the sort function)
      heading: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func
      ]).isRequired,

      // What prop of the data object to use.
      prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

      // If true, the column will sort on column heading click.
      sortable: PropTypes.bool,

      // Custom sorting function. If this function returns null,
      // it will fallback to default sorting.
      sortFunction: PropTypes.func
    })
  ).isRequired,

  // Optional selector of the parent element that has a scrollbar in order to
  // listen to its scroll event.
  containerSelector: PropTypes.string,

  // Data to display in the table.
  // Make sure to clone the data, cannot be modified!
  data: PropTypes.array.isRequired,

  // Text to show if there is no data.
  emptyMessage: PropTypes.string,

  // Optional item height for the scroll table. If not provided, it will render
  // once to measure the height of the first child.
  // NB: Initial render will stop any ongoing animation, if this is not provided
  itemHeight: PropTypes.number,

  // Optional callback function when sorting is complete.
  onSortCallback: PropTypes.func,

  // Optional default sorting criteria.
  sortBy: PropTypes.shape({
    order: PropTypes.oneOf(['asc', 'desc']),
    prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
  })
};

module.exports = Table;
<|endoftext|>