<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOrderBooks': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'tickers': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'tickers': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                        'fullorderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
        });
    }

    commonCurrencyCode (currency) {
        if (currency === 'IOT')
            return 'IoTcoin';
        if (currency === 'BLC')
            return 'Cryptobullcoin';
        if (currency === 'XID')
            return 'InternationalDiamond';
        return currency;
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets['result'].length; p++) {
            let market = markets['result'][p];
            let id = market['MarketName'];
            let base = market['MarketCurrency'];
            let quote = market['BaseCurrency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = base + '/' + quote;
            result.push (this.extend (this.fees['trading'], {
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            }));
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetBalances ();
        let balances = response['result'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let code = balance['Currency'];
            let currency = this.commonCurrencyCode (code);
            let account = {
                'free': balance['Available'],
                'used': balance['Pending'],
                'total': balance['Balance'],
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'market': this.marketId (symbol),
            'type': 'both',
        };
        if (typeof limit !== 'undefined')
            request['depth'] = limit; // 100
        let response = await this.publicGetOrderbook (this.extend (request, params));
        let orderbook = response['result'];
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    async fetchOrderBooks (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let orderbooks = {};
        let response = await this.publicGetFullorderbook ();
        let types = Object.keys (response['result']);
        for (let i = 0; i < types.length; i++) {
            let type = types[i];
            let bidasks = response['result'][type];
            let bidasksByMarketId = this.groupBy (bidasks, 'Market');
            let marketIds = Object.keys (bidasksByMarketId);
            for (let j = 0; j < marketIds.length; j++) {
                let marketId = marketIds[j];
                let symbol = marketId.toUpperCase ();
                let side = type;
                if (symbol in this.markets_by_id) {
                    let market = this.markets_by_id[symbol];
                    symbol = market['symbol'];
                } else {
                    let [ base, quote ] = symbol.split ('-');
                    let invertedId = quote + '-' + base;
                    if (invertedId in this.marketsById) {
                        let market = this.marketsById[invertedId];
                        symbol = market['symbol'];
                        side = (type === 'buy') ? 'sell' : 'buy';
                    }
                }
                if (!(symbol in orderbooks)) {
                    orderbooks[symbol] = {};
                }
                //     if (side in orderbooks[symbol]) {
                //         console.log ('DEBUG');
                //         process.exit ();
                //     }
                orderbooks[symbol][side] = bidasksByMarketId[marketId];
            }
        }
        let result = {};
        let keys = Object.keys (orderbooks);
        for (let k = 0; k < keys.length; k++) {
            let key = keys[k];
            result[key] = this.parseOrderBook (orderbooks[key], undefined, 'buy', 'sell', 'Rate', 'Quantity');
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['updated'] * 1000;
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['buy']),
            'ask': parseFloat (ticker['sell']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['lastprice']),
            'change': undefined,
            'percentage': undefined,
            'average': parseFloat (ticker['avg']),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.tickersGetPrices (params);
        let result = { 'info': tickers };
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let ticker = tickers[id];
            let uppercase = id.toUpperCase ();
            let market = undefined;
            let symbol = undefined;
            if (uppercase in this.markets_by_id) {
                market = this.markets_by_id[uppercase];
                symbol = market['symbol'];
            } else {
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.tickersGetMarket (this.extend ({
            'market': market['id'].toLowerCase (),
        }, params));
        let ticker = response['ticker'];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TimeStamp']);
        return {
            'id': trade['Id'].toString (),
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['OrderType'].toLowerCase (),
            'price': trade['Price'],
            'amount': trade['Quantity'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarkethistory (this.extend ({
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        }, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'privateGet' + this.capitalize (side) + type;
        let response = await this[method] (this.extend ({
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privateGetCancel ({ 'uuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api === 'private') {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api === 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'tickers')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<commit_msg>fixed fetchOrderBooks for ccex #1050<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOrderBooks': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'tickers': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'tickers': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                        'fullorderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
        });
    }

    commonCurrencyCode (currency) {
        if (currency === 'IOT')
            return 'IoTcoin';
        if (currency === 'BLC')
            return 'Cryptobullcoin';
        if (currency === 'XID')
            return 'InternationalDiamond';
        return currency;
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets['result'].length; p++) {
            let market = markets['result'][p];
            let id = market['MarketName'];
            let base = market['MarketCurrency'];
            let quote = market['BaseCurrency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = base + '/' + quote;
            result.push (this.extend (this.fees['trading'], {
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            }));
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetBalances ();
        let balances = response['result'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let code = balance['Currency'];
            let currency = this.commonCurrencyCode (code);
            let account = {
                'free': balance['Available'],
                'used': balance['Pending'],
                'total': balance['Balance'],
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'market': this.marketId (symbol),
            'type': 'both',
        };
        if (typeof limit !== 'undefined')
            request['depth'] = limit; // 100
        let response = await this.publicGetOrderbook (this.extend (request, params));
        let orderbook = response['result'];
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    async fetchOrderBooks (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let orderbooks = {};
        let response = await this.publicGetFullorderbook ();
        let types = Object.keys (response['result']);
        const log = require ('ololog');
        for (let i = 0; i < types.length; i++) {
            let type = types[i];
            let bidasks = response['result'][type];
            let bidasksByMarketId = this.groupBy (bidasks, 'Market');
            let marketIds = Object.keys (bidasksByMarketId);
            for (let j = 0; j < marketIds.length; j++) {
                let marketId = marketIds[j];
                let symbol = marketId.toUpperCase ();
                let side = type;
                if (symbol in this.markets_by_id) {
                    let market = this.markets_by_id[symbol];
                    symbol = market['symbol'];
                } else {
                    let [ base, quote ] = symbol.split ('-');
                    let invertedId = quote + '-' + base;
                    if (invertedId in this.markets_by_id) {
                        let market = this.markets_by_id[invertedId];
                        symbol = market['symbol'];
                    }
                }
                if (!(symbol in orderbooks))
                    orderbooks[symbol] = {};
                orderbooks[symbol][side] = bidasksByMarketId[marketId];
            }
        }
        let result = {};
        let keys = Object.keys (orderbooks);
        for (let k = 0; k < keys.length; k++) {
            let key = keys[k];
            result[key] = this.parseOrderBook (orderbooks[key], undefined, 'buy', 'sell', 'Rate', 'Quantity');
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['updated'] * 1000;
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['buy']),
            'ask': parseFloat (ticker['sell']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['lastprice']),
            'change': undefined,
            'percentage': undefined,
            'average': parseFloat (ticker['avg']),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.tickersGetPrices (params);
        let result = { 'info': tickers };
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let ticker = tickers[id];
            let uppercase = id.toUpperCase ();
            let market = undefined;
            let symbol = undefined;
            if (uppercase in this.markets_by_id) {
                market = this.markets_by_id[uppercase];
                symbol = market['symbol'];
            } else {
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.tickersGetMarket (this.extend ({
            'market': market['id'].toLowerCase (),
        }, params));
        let ticker = response['ticker'];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TimeStamp']);
        return {
            'id': trade['Id'].toString (),
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['OrderType'].toLowerCase (),
            'price': trade['Price'],
            'amount': trade['Quantity'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarkethistory (this.extend ({
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        }, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'privateGet' + this.capitalize (side) + type;
        let response = await this[method] (this.extend ({
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privateGetCancel ({ 'uuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api === 'private') {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api === 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'tickers')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<|endoftext|>


<commit_before>var React = require('react');
var Button = require('elemental').Button;
var Spinner = require('elemental').Spinner;

var Buttons = React.createClass({
	displayName: 'VIEW_Spinner',
	render () {
		return (

Spinner

Default

							<Spinner type="default" />

Primary

							<Spinner type="primary" />

Inverted

							<Spinner type="inverted" />

Use in Buttons

				<Button type="default">
					<Spinner />
				</Button>

				<Button type="default" disabled>
					<Spinner type="primary" />
					Saving
				</Button>

				<Button type="primary" disabled>
					<Spinner type="inverted" />
					Saving
				</Button>

		);
	}
});

module.exports = Buttons;
<commit_msg>document Spinner<commit_after>var React = require('react');
var Button = require('elemental').Button;
var Spinner = require('elemental').Spinner;

var ExampleSource = require('../components/ExampleSource');

var Buttons = React.createClass({
	displayName: 'VIEW_Spinner',
	render () {
		return (

Spinner

Independent

							<Spinner />

							<Spinner type="primary" />

							<Spinner type="inverted" />

					<ExampleSource>
						{`<Spinner />\n<Spinner type="primary" />\n<Spinner type="inverted" />`}
					</ExampleSource>

Inside Buttons

							<Button disabled>
								<Spinner />
							</Button>

							<Button disabled>
								<Spinner type="primary" />
								Saving
							</Button>

							<Button type="primary" disabled>
								<Spinner type="inverted" />
								Saving
							</Button>

					<ExampleSource>
						{`<Button disabled><Spinner /></Button>\n<Button disabled><Spinner type="primary" />Saving</Button>\n<Button type="primary" disabled><Spinner type="inverted" />Saving</Button>`}
					</ExampleSource>

Usage

							Name
							Type
							Default
							Description

							size
							string
							''

Declare the size of the dots in the spinner. Possible options:

								sm lg

								Spinners automatically become small when inside of buttons

							type
							string
							default

								Declare the colour of the dots in the spinner. Possible options:

								default primary inverted

		);
	}
});

module.exports = Buttons;
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOrderBooks': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'web': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'web': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                        'fullorderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
            'commonCurrencies': {
                'BLC': 'Cryptobullcoin',
                'CRC': 'CoreCoin',
                'IOT': 'IoTcoin',
                'LUX': 'Luxmi',
                'VIT': 'VitalCoin',
                'XID': 'InternationalDiamond',
            },
        });
    }

    async fetchMarkets (params = {}) {
        let result = {};
        let response = await this.webGetPairs ();
        let markets = response['pairs'];
        for (let i = 0; i < markets.length; i++) {
            let id = markets[i];
            let [ baseId, quoteId ] = id.split ('-');
            let base = baseId.toUpperCase ();
            let quote = quoteId.toUpperCase ();
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = base + '/' + quote;
            result[symbol] = {
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'info': id,
            };
        }
        // an alternative documented parser
        //     let markets = await this.publicGetMarkets ();
        //     for (let p = 0; p < markets['result'].length; p++) {
        //         let market = markets['result'][p];
        //         let id = market['MarketName'];
        //         let base = market['MarketCurrency'];
        //         let quote = market['BaseCurrency'];
        //         base = this.commonCurrencyCode (base);
        //         quote = this.commonCurrencyCode (quote);
        //         let symbol = base + '/' + quote;
        //         result.push ({
        //             'id': id,
        //             'symbol': symbol,
        //             'base': base,
        //             'quote': quote,
        //             'info': market,
        //         });
        //     }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetGetbalances ();
        let balances = response['result'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let code = balance['Currency'];
            let currency = this.commonCurrencyCode (code);
            let account = {
                'free': balance['Available'],
                'used': balance['Pending'],
                'total': balance['Balance'],
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'market': this.marketId (symbol),
            'type': 'both',
        };
        if (limit !== undefined)
            request['depth'] = limit; // 100
        let response = await this.publicGetOrderbook (this.extend (request, params));
        let orderbook = response['result'];
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    async fetchOrderBooks (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let orderbooks = {};
        let response = await this.publicGetFullorderbook ();
        let sides = Object.keys (response['result']);
        for (let i = 0; i < sides.length; i++) {
            let side = sides[i];
            let bidasks = response['result'][side];
            let bidasksByMarketId = this.groupBy (bidasks, 'Market');
            let marketIds = Object.keys (bidasksByMarketId);
            for (let j = 0; j < marketIds.length; j++) {
                let marketId = marketIds[j];
                let symbol = marketId;
                if (marketId in this.markets_by_id) {
                    let market = this.markets_by_id[symbol];
                    symbol = market['symbol'];
                } else {
                    let [ baseId, quoteId ] = symbol.split ('-');
                    let invertedId = quoteId + '-' + baseId;
                    if (invertedId in this.markets_by_id) {
                        let market = this.markets_by_id[invertedId];
                        symbol = market['symbol'];
                    }
                }
                if (!(symbol in orderbooks))
                    orderbooks[symbol] = {};
                orderbooks[symbol][side] = bidasksByMarketId[marketId];
            }
        }
        let result = {};
        let keys = Object.keys (orderbooks);
        for (let k = 0; k < keys.length; k++) {
            let key = keys[k];
            result[key] = this.parseOrderBook (orderbooks[key], undefined, 'buy', 'sell', 'Rate', 'Quantity');
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['updated'] * 1000;
        let symbol = undefined;
        if (market !== undefined)
            symbol = market['symbol'];
        let last = this.safeFloat (ticker, 'lastprice');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high'),
            'low': this.safeFloat (ticker, 'low'),
            'bid': this.safeFloat (ticker, 'buy'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'sell'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': this.safeFloat (ticker, 'avg'),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.webGetPrices (params);
        let result = {};
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let ticker = tickers[id];
            let market = undefined;
            let symbol = undefined;
            if (id in this.markets_by_id) {
                market = this.markets_by_id[id];
                symbol = market['symbol'];
            } else {
                let uppercase = id.toUpperCase ();
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.webGetMarket (this.extend ({
            'market': market['id'].toLowerCase (),
        }, params));
        let ticker = response['ticker'];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TimeStamp']);
        return {
            'id': trade['Id'].toString (),
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['OrderType'].toLowerCase (),
            'price': trade['Price'],
            'amount': trade['Quantity'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarkethistory (this.extend ({
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        }, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'privateGet' + this.capitalize (side) + type;
        let response = await this[method] (this.extend ({
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privateGetCancel ({ 'uuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api === 'private') {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api === 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'web')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<commit_msg>ccex cleanup for eslint curly<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOrderBooks': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'web': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'web': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                        'fullorderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
            'commonCurrencies': {
                'BLC': 'Cryptobullcoin',
                'CRC': 'CoreCoin',
                'IOT': 'IoTcoin',
                'LUX': 'Luxmi',
                'VIT': 'VitalCoin',
                'XID': 'InternationalDiamond',
            },
        });
    }

    async fetchMarkets (params = {}) {
        const result = {};
        const response = await this.webGetPairs (params);
        const markets = this.safeValue (response, 'pairs');
        for (let i = 0; i < markets.length; i++) {
            const id = markets[i];
            const [ baseId, quoteId ] = id.split ('-');
            let base = baseId.toUpperCase ();
            let quote = quoteId.toUpperCase ();
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            const symbol = base + '/' + quote;
            result[symbol] = {
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'info': id,
            };
        }
        // an alternative documented parser
        //     let markets = await this.publicGetMarkets ();
        //     for (let p = 0; p < markets['result'].length; p++) {
        //         let market = markets['result'][p];
        //         let id = market['MarketName'];
        //         let base = market['MarketCurrency'];
        //         let quote = market['BaseCurrency'];
        //         base = this.commonCurrencyCode (base);
        //         quote = this.commonCurrencyCode (quote);
        //         let symbol = base + '/' + quote;
        //         result.push ({
        //             'id': id,
        //             'symbol': symbol,
        //             'base': base,
        //             'quote': quote,
        //             'info': market,
        //         });
        //     }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const response = await this.privateGetGetbalances (params);
        const balances = this.safeValue (response, 'result');
        const result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            const balance = balances[i];
            const currencyId = this.safeString (balance, 'Currency');
            const code = this.commonCurrencyCode (currencyId);
            const account = {
                'free': this.safeFloat (balance, 'Available'),
                'used': this.safeFloat (balance, 'Pending'),
                'total': this.safeFloat (balance, 'Balance'),
            };
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'market': this.marketId (symbol),
            'type': 'both',
        };
        if (limit !== undefined) {
            request['depth'] = limit; // 100
        }
        const response = await this.publicGetOrderbook (this.extend (request, params));
        const orderbook = this.safeValue (response, 'result');
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    async fetchOrderBooks (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        const orderbooks = {};
        const response = await this.publicGetFullorderbook ();
        const sides = Object.keys (response['result']);
        for (let i = 0; i < sides.length; i++) {
            const side = sides[i];
            const bidasks = response['result'][side];
            const bidasksByMarketId = this.groupBy (bidasks, 'Market');
            const marketIds = Object.keys (bidasksByMarketId);
            for (let j = 0; j < marketIds.length; j++) {
                const marketId = marketIds[j];
                let symbol = marketId;
                if (marketId in this.markets_by_id) {
                    const market = this.markets_by_id[symbol];
                    symbol = market['symbol'];
                } else {
                    const [ baseId, quoteId ] = symbol.split ('-');
                    const invertedId = quoteId + '-' + baseId;
                    if (invertedId in this.markets_by_id) {
                        const market = this.markets_by_id[invertedId];
                        symbol = market['symbol'];
                    }
                }
                if (!(symbol in orderbooks)) {
                    orderbooks[symbol] = {};
                }
                orderbooks[symbol][side] = bidasksByMarketId[marketId];
            }
        }
        const result = {};
        const keys = Object.keys (orderbooks);
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            result[key] = this.parseOrderBook (orderbooks[key], undefined, 'buy', 'sell', 'Rate', 'Quantity');
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.safeInteger (ticker, 'updated');
        if (timestamp !== undefined) {
            timestamp *= 1000;
        }
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        const last = this.safeFloat (ticker, 'lastprice');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high'),
            'low': this.safeFloat (ticker, 'low'),
            'bid': this.safeFloat (ticker, 'buy'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'sell'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': this.safeFloat (ticker, 'avg'),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        const response = await this.webGetPrices (params);
        const result = {};
        const ids = Object.keys (response);
        for (let i = 0; i < ids.length; i++) {
            const id = ids[i];
            const ticker = response[id];
            let market = undefined;
            let symbol = undefined;
            if (id in this.markets_by_id) {
                market = this.markets_by_id[id];
                symbol = market['symbol'];
            } else {
                const uppercase = id.toUpperCase ();
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'market': market['id'].toLowerCase (),
        };
        const response = await this.webGetMarket (this.extend (request, params));
        const ticker = this.safeValue (response, 'ticker');
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        const timestamp = this.parse8601 (this.safeString (trade, 'TimeStamp'));
        const id = this.safeString (trade, 'id');
        let side = this.safeString (trade, 'OrderType');
        if (side !== undefined) {
            side = side.toLowerCase ();
        }
        const price = this.safeFloat (trade, 'Price');
        const amount = this.safeFloat (trade, 'Quantity');
        let cost = undefined;
        if (amount !== undefined) {
            if (price !== undefined) {
                cost = amount * price;
            }
        }
        return {
            'id': id,
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        };
        const response = await this.publicGetMarkethistory (this.extend (request, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const method = 'privateGet' + this.capitalize (side) + type;
        const request = {
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        };
        const response = await this[method] (this.extend (request, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'uuid': id,
        };
        return await this.privateGetCancel (this.extend (request, params));
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api === 'private') {
            this.checkRequiredCredentials ();
            const nonce = this.nonce ().toString ();
            const query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api === 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        const response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'web') {
            return response;
        }
        if ('success' in response) {
            if (response['success']) {
                return response;
            }
        }
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<|endoftext|>


<commit_before>var socket = io();
var usuarios = {}
let dom = [
	[0,0],
	[0,1],
	[0,2],
	[0,3],
	[0,4],
	[0,5],
	[0,6],
	[1,1],
	[1,2],
	[1,3],
	[1,4],
	[1,5],
	[1,6],
	[2,2],
	[2,3],
	[2,4],
	[2,5],
	[2,6],
	[3,3],
	[3,4],
	[3,5],
	[3,6],
	[4,4],
	[4,5],
	[4,6],
	[5,5],
	[5,6],
	[6,6]
];
let fichas = []

function submitfunction(){
  var from = $('#user').val();
  var message = $('#m').val();
  if(message != '') {
	  if(message == "start") {
		domino();
	  }
	  if(message == "giveme") {
		getDomino(from);
	  }
	socket.emit('chatMessage', from, message);
	}
	$('#m').val('').focus();
	return false;
}

function notifyTyping() {
  var user = $('#user').val();
  socket.emit('notifyUser', user);
}

socket.on('chatMessage', function(from, msg){
  var me = $('#user').val();
  var color = (from == me) ? 'green' : '#009afd';
  var from = (from == me) ? 'Me' : from;
  $('#messages').append('
' + from + ': ' + msg + '
');
});

socket.on('notifyUser', function(user){
  var me = $('#user').val();
  if(user != me) {
    $('#notifyUser').text(user + ' is typing ...');
  }
  setTimeout(function(){ $('#notifyUser').text(''); }, 10000);;
});

$(document).ready(function(){
  var name = makeid();
  $('#user').val(name);
	socket.emit('chatMessage', 'System', '' + name + ' has joined the discussion ---> to play domino use this commands, '+''+'start'+''+' to start the game, '+''+'giveme'+''+' to recieve dominoes.');
  // usuarios.username = name;
  // usuarios.number = Math.floor(Math.random()* (10 - 0)) + 0;
	socket.emit('saveUser',name)
});

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for( var i=0; i < 5; i++ ) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}
 socket.on('saveUser', function(user) {
	 Object.defineProperty(usuarios, user, {
		 enumerable: false,
		 configurable: true,
		 writable: true,
		 value: 'static'
	 });
	 console.log(usuarios)
 })
 function domino() {
	for(let i=0; i <= 28; i++) {
		console.log('++ Fichas Creadas')
	}
 }

 function getDomino(user) {
	 for(let i =0; i<5; i++) {
		let a = Math.floor(Math.random() * (29 -0)) - 0;
		console.log(dom[a])
		for (let x of fichas) {
			if(x === a) console.log('Ya la di')
			else {
				fichas.push(a);
			}
		}
	 }
 }
<commit_msg>some issues resolved<commit_after>var socket = io();
var cont = 0;
var usuarios = {}
let dom = [
	[0,0],
	[0,1],
	[0,2],
	[0,3],
	[0,4],
	[0,5],
	[0,6],
	[1,1],
	[1,2],
	[1,3],
	[1,4],
	[1,5],
	[1,6],
	[2,2],
	[2,3],
	[2,4],
	[2,5],
	[2,6],
	[3,3],
	[3,4],
	[3,5],
	[3,6],
	[4,4],
	[4,5],
	[4,6],
	[5,5],
	[5,6],
	[6,6]
];
let fichasS = [], fichas =[];

function submitfunction(){
  var from = $('#user').val();
  var message = $('#m').val();
  if(message != '') {
	  if(message == "start") {
		domino();
	  }
	  if(message == "giveme") {
		getDomino(from);
	  }
	socket.emit('chatMessage', from, message);
	}
	$('#m').val('').focus();
	return false;
}

function notifyTyping() {
  var user = $('#user').val();
  socket.emit('notifyUser', user);
}

socket.on('chatMessage', function(from, msg){
  var me = $('#user').val();
  var color = (from == me) ? 'green' : '#009afd';
  var from = (from == me) ? 'Me' : from;
  $('#messages').append('
' + from + ': ' + msg + '
');
});

socket.on('notifyUser', function(user){
  var me = $('#user').val();
  if(user != me) {
    $('#notifyUser').text(user + ' is typing ...');
  }
  setTimeout(function(){ $('#notifyUser').text(''); }, 10000);;
});

$(document).ready(function(){
  var name = makeid();
  $('#user').val(name);
	socket.emit('chatMessage', 'System', '' + name + ' has joined the discussion ---> to play domino use this commands, '+''+'start'+''+' to start the game, '+''+'giveme'+''+' to recieve dominoes.');
  // usuarios.username = name;
  // usuarios.number = Math.floor(Math.random()* (10 - 0)) + 0;
	socket.emit('saveUser',name)
});

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for( var i=0; i < 5; i++ ) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}
 socket.on('saveUser', function(user) {
	 Object.defineProperty(usuarios, user, {
		 enumerable: false,
		 configurable: true,
		 writable: true,
		 value: 'static'
	 });
	 console.log(usuarios)
 })
 function domino() {
	for(let i=0; i <= 28; i++) {
		console.log('++ Fichas Creadas')
	}
 }

 function getDomino(user) {
	 console.log('Start')
	 let a = Math.floor(Math.random()*(29-0))-0;
	 fichas.push(5)
	 console.log(fichas.find(5))
	 // while(cont < 5) {
		 // let a = Math.floor(Math.random()*(29-0))-0;
		 // fichas.find(a)
	 // }
 }
<|endoftext|>


<commit_before>var maxFeedItems;
if(localStorage["reddit_max_events"]==null) {maxFeedItems=10;}
else {maxFeedItems = parseInt(localStorage["reddit_max_events"]);}
var selected_subreddit = localStorage["reddit_subreddit"];

var req;
var buildPopupAfterResponse = false;
var OnFeedSuccess = null;
var OnFeedFail = null;
var retryMilliseconds = 120000;

function init_options(key, value) {
	if (localStorage[key] == null) {
		localStorage[key] = value;
	}
}

function update_if_ready(force) {
	var lastRefresh = parseFloat(localStorage["reddit_last_refresh"]);
	var interval = parseFloat(localStorage["reddit_request_interval"]);
	var nextRefresh = lastRefresh + interval;
	var curTime = parseFloat((new Date()).getTime());
	var isReady = (curTime > nextRefresh);
	var isNull = (localStorage["reddit_last_refresh"] == null);
	if ((force == true) || (localStorage["reddit_last_refresh"] == null)) {
		update_feed();
	}
	else {
	  if (isReady) {
	    update_feed();
	  }
	}
}

function update_feed() {
  $.ajax({type:'GET', dataType:'xml', url: 'https://www.reddit.com/'+selected_subreddit+'.rss', timeout:5000, success:rss_success, error:feed_err, async: false});
}

function get_num_comments(link) {
  var num_comments;
  var address = link + ".json?";
  $.ajax({
    url: address,
    dataType: 'json',
    async: false,
    success: function(data) {
      num_comments = parseInt(data[0].data.children[0].data.num_comments);
    },
    error: feed_err
  });
  return num_comments;
}

function rss_success(doc) {
  if (!doc) {
    rss_parse_err("Not a valid feed.");
    return;
  }
 	links = parse_post_links(doc);
	save_links(links);
	if (buildPopupAfterResponse == true) {
		build_popup(links);
		buildPopupAfterResponse = false;
	}
	localStorage["reddit_last_refresh"] = (new Date()).getTime();
}

function update_refresh_time() {
  localStorage["reddit_last_refresh"] = (new Date()).getTime();
}

function feed_err(xhr, type, error) {
  rss_parse_err('Failed to fetch feed.');
}

function rss_parse_err(error) {
  var feed = document.getElementById("feed");
  feed.className = "error"
  feed.innerText = "Error: " + error;
  localStorage["reddit_last_refresh"] = localStorage["reddit_last_refresh"] + retryMilliseconds;
}

function parse_post_links(doc) {
	var entries = doc.getElementsByTagName('entry');
	if (entries.length == 0) {
	  entries = doc.getElementsByTagName('item');
	}
  var count = Math.min(entries.length, maxFeedItems);
  var links = new Array();
  for (var i=0; i< count; i++) {
    item = entries.item(i);
    var post_link = new Object();
    //Grab the title
    var itemTitle = item.getElementsByTagName('title')[0];
    if (itemTitle) {
      post_link.Title = itemTitle.textContent;
    } else {
      post_link.Title = "Unknown Title";
    }

    //Grab the post link
    var item_description = item.getElementsByTagName('description')[0].textContent;
    var regex = /(?:<a href=")([^<]*?)(?:">)(?=\[link\])/g;
    var link = (regex.exec(item_description))[1]; // grab link from description text w/ regex and conver to dom object
    var xmlString = "<link>" + link + "</link>" // I should make a function for this
      , parser = new DOMParser()
      , doc = parser.parseFromString(xmlString, "text/xml");
    itemLink = doc.firstChild;

    if (!itemLink) {
      itemLink = item.getElementsByTagName('link')[0];
    }
    if (itemLink) {
      post_link.Link = itemLink.textContent;
    } else {
      post_link.Link = '';
    }

    //Grab the comments link
    var commentsLink = item.getElementsByTagName('link')[0];
    var commentsLinkText = commentsLink.textContent;
    if (commentsLink) {
      post_link.CommentsLink = commentsLinkText;
    } else {
      post_link.CommentsLink = '';
    }

    post_link.num_comments = get_num_comments(commentsLinkText);

    links.push(post_link);
  }
  return links;
}

function save_links(links) {
	localStorage["reddit_num_links"] = links.length;
	for (var i=0; i<links.length; i++) {
		localStorage["reddit_link" + i] = JSON.stringify(links[i]);
	}
}

function retrieve_links() {
	var numLinks = localStorage["reddit_num_links"];
	if (numLinks == null) {
		return null;
	}
	else {
		var links = new Array();
		for (var i=0; i<numLinks; i++) {
			links.push(JSON.parse(localStorage["reddit_link" + i]))
		}
		return links;
	}
}

function open_options() {
	var optionsUrl = chrome.extension.getURL('options.html');
	chrome.tabs.create({url: optionsUrl});
}

function open_link(e) {
  e.preventDefault();
  open_url(this.href, (localStorage['reddit_background_tabs'] == 'false'));
}

function open_link_front(e) {
	e.preventDefault();
	open_url(this.href, true);
}

// Show url in a new tab.
function open_url(url, take_focus) {
  if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
    return;
  }
  chrome.tabs.create({url: url, selected: take_focus});
}

function hide_element(id) {
	var e = document.getElementById(id);
	e.style.display = 'none';
}

function display_element(id) {
	var e = document.getElementById(id);
	e.style.display = 'block';
}

function toggle(id) {
	var e = document.getElementById(id);
	if(e.style.display == 'block')
		e.style.display = 'none';
	else
		e.style.display = 'block';
}
<commit_msg>reduce number of ajax calls<commit_after>var maxFeedItems;
if(localStorage["reddit_max_events"]==null) {maxFeedItems=10;}
else {maxFeedItems = parseInt(localStorage["reddit_max_events"]);}
var selected_subreddit = localStorage["reddit_subreddit"];

var req;
var buildPopupAfterResponse = false;
var OnFeedSuccess = null;
var OnFeedFail = null;
var retryMilliseconds = 120000;

function init_options(key, value) {
	if (localStorage[key] == null) {
		localStorage[key] = value;
	}
}

function update_if_ready(force) {
	var lastRefresh = parseFloat(localStorage["reddit_last_refresh"]);
	var interval = parseFloat(localStorage["reddit_request_interval"]);
	var nextRefresh = lastRefresh + interval;
	var curTime = parseFloat((new Date()).getTime());
	var isReady = (curTime > nextRefresh);
	var isNull = (localStorage["reddit_last_refresh"] == null);
	if ((force == true) || (localStorage["reddit_last_refresh"] == null)) {
		update_feed();
	}
	else {
	  if (isReady) {
	    update_feed();
	  }
	}
}

function update_feed() {
  $.ajax({type:'GET', dataType:'xml', url: 'https://www.reddit.com/'+selected_subreddit+'.rss', timeout:5000, success:rss_success, error:feed_err, async: false});
}

function get_num_comments(link) {
  var address = "https://www.reddit.com/" + link + ".json?";
  var x = new Array();
    $.ajax({
      url: address,
      dataType: 'json',
      async: false,
      success: function(data) {
        for (var i=0; i<20; i++) {
          x[i] = data.data.children[i].data.num_comments;
        }
      }
    });
    return x;
}

function rss_success(doc) {
  if (!doc) {
    rss_parse_err("Not a valid feed.");
    return;
  }
 	links = parse_post_links(doc);
	save_links(links);
	if (buildPopupAfterResponse == true) {
		build_popup(links);
		buildPopupAfterResponse = false;
	}
	localStorage["reddit_last_refresh"] = (new Date()).getTime();
}

function update_refresh_time() {
  localStorage["reddit_last_refresh"] = (new Date()).getTime();
}

function feed_err(xhr, type, error) {
  rss_parse_err('Failed to fetch feed.');
}

function rss_parse_err(error) {
  var feed = document.getElementById("feed");
  feed.className = "error"
  feed.innerText = "Error: " + error;
  localStorage["reddit_last_refresh"] = localStorage["reddit_last_refresh"] + retryMilliseconds;
}

function parse_post_links(doc) {
	var entries = doc.getElementsByTagName('entry');
	if (entries.length == 0) {
	  entries = doc.getElementsByTagName('item');
	}
  var count = Math.min(entries.length, maxFeedItems);
  var links = new Array();
  var num_comments = get_num_comments(localStorage["reddit_subreddit"]);
  for (var i=0; i< count; i++) {
    item = entries.item(i);
    var post_link = new Object();
    //Grab the title
    var itemTitle = item.getElementsByTagName('title')[0];
    if (itemTitle) {
      post_link.Title = itemTitle.textContent;
    } else {
      post_link.Title = "Unknown Title";
    }

    //Grab the post link
    var item_description = item.getElementsByTagName('description')[0].textContent;
    var regex = /(?:<a href=")([^<]*?)(?:">)(?=\[link\])/g;
    var link = (regex.exec(item_description))[1]; // grab link from description text w/ regex and conver to dom object
    var xmlString = "<link>" + link + "</link>" // I should make a function for this
      , parser = new DOMParser()
      , doc = parser.parseFromString(xmlString, "text/xml");
    itemLink = doc.firstChild;

    if (!itemLink) {
      itemLink = item.getElementsByTagName('link')[0];
    }
    if (itemLink) {
      post_link.Link = itemLink.textContent;
    } else {
      post_link.Link = '';
    }

    //Grab the comments link
    var commentsLink = item.getElementsByTagName('link')[0];
    var commentsLinkText = commentsLink.textContent;
    if (commentsLink) {
      post_link.CommentsLink = commentsLinkText;
    } else {
      post_link.CommentsLink = '';
    }

    post_link.num_comments = num_comments[i];

    links.push(post_link);
  }
  return links;
}

function save_links(links) {
	localStorage["reddit_num_links"] = links.length;
	for (var i=0; i<links.length; i++) {
		localStorage["reddit_link" + i] = JSON.stringify(links[i]);
	}
}

function retrieve_links() {
	var numLinks = localStorage["reddit_num_links"];
	if (numLinks == null) {
		return null;
	}
	else {
		var links = new Array();
		for (var i=0; i<numLinks; i++) {
			links.push(JSON.parse(localStorage["reddit_link" + i]))
		}
		return links;
	}
}

function open_options() {
	var optionsUrl = chrome.extension.getURL('options.html');
	chrome.tabs.create({url: optionsUrl});
}

function open_link(e) {
  e.preventDefault();
  open_url(this.href, (localStorage['reddit_background_tabs'] == 'false'));
}

function open_link_front(e) {
	e.preventDefault();
	open_url(this.href, true);
}

// Show url in a new tab.
function open_url(url, take_focus) {
  if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
    return;
  }
  chrome.tabs.create({url: url, selected: take_focus});
}

function hide_element(id) {
	var e = document.getElementById(id);
	e.style.display = 'none';
}

function display_element(id) {
	var e = document.getElementById(id);
	e.style.display = 'block';
}

function toggle(id) {
	var e = document.getElementById(id);
	if(e.style.display == 'block')
		e.style.display = 'none';
	else
		e.style.display = 'block';
}
<|endoftext|>


<commit_before>const ConnectHandler = require('@jeneric/core/app/handler/server/io/connect');

class CustomDisconnectHandler extends ConnectHandler {
    constructor() {
        super();
    }

    handle(socket) {

        super.handle(socket);

        this.services.speaker.say('Gerät abgemeldet.');

    }
}

module.exports = CustomDisconnectHandler;
<commit_msg>bugfix- disconnect handler<commit_after>const DisconnectHandler = require('@jeneric/core/app/handler/server/io/disconnect');

class CustomDisconnectHandler extends DisconnectHandler {
    constructor() {
        super();
    }

    handle(socket) {

        super.handle(socket);

        this.services.speaker.say('Gerät abgemeldet.');

    }
}

module.exports = CustomDisconnectHandler;
<|endoftext|>


<commit_before>// Copyright (c) 2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

"use strict";
var options = require('options');
var Raven = require('raven-js');
var $ = require('jquery');

if (options.raven) {
    Raven.config(options.raven, {
        release: options.release,
        environment: options.environment.join("/")
    }).install();
}

var gaProxy;
/* eslint-disable */
if (options.googleAnalyticsEnabled) {
    (function (i, s, o, g, r, a, m) {
        i.GoogleAnalyticsObject = r;
        i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments);
        };
        i[r].l = 1 * new Date();
        a = s.createElement(o);
        m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m);
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
    ga('create', options.googleAnalyticsAccount, 'auto');
    ga('send', 'pageview');
    gaProxy = function () {
        window.ga.apply(window.ga, arguments);
    };
    // fullstory stuff:
    window['_fs_debug'] = false;
    window['_fs_host'] = 'www.fullstory.com';
    window['_fs_org'] = '2F4NV';
    window['_fs_namespace'] = 'FS';
    (function (m, n, e, t, l, o, g, y) {
        if (e in m && m.console && m.console.log) {
            m.console.log('FullStory namespace conflict. Please set window["_fs_namespace"].');
            return;
        }
        g = m[e] = function (a, b) {
            g.q ? g.q.push([a, b]) : g._api(a, b);
        };
        g.q = [];
        o = n.createElement(t);
        o.async = 1;
        o.src = 'https://' + _fs_host + '/s/fs.js';
        y = n.getElementsByTagName(t)[0];
        y.parentNode.insertBefore(o, y);
        g.identify = function (i, v) {
            g(l, {uid: i});
            if (v) g(l, v);
        };
        g.setUserVars = function (v) {
            g(l, v);
        };
        g.identifyAccount = function (i, v) {
            o = 'account';
            v = v || {};
            v.acctId = i;
            g(o, v);
        };
        g.clearUserCookie = function (c, d, i) {
            if (!c || document.cookie.match('fs_uid=[`;`]*`[`;`]*`[`;`]*`')) {
                d = n.domain;
                while (1) {
                    n.cookie = 'fs_uid=;domain=' + d +
                        ';path=/;expires=' + new Date(0).toUTCString();
                    i = d.indexOf('.');
                    if (i < 0) break;
                    d = d.slice(i + 1);
                }
            }
        };
    })(window, document, window['_fs_namespace'], 'script', 'user');
} else {
    gaProxy = function () {};
}
/* eslint-enable */

function initialise() {
    if (options.embedded) return;
    $(function () {
        function create_script_element(id, url) {
            var el = document.createElement('script');
            el.type = 'text/javascript';
            el.async = true;
            el.id = id;
            el.src = url;
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(el, s);
        }

        if (options.sharingEnabled) {
            create_script_element('twitter-wjs', 'https://platform.twitter.com/widgets.js');
        }
    });
}

module.exports = {
    ga: gaProxy,
    initialise: initialise
};
<commit_msg>Disable FullStory as per #973<commit_after>// Copyright (c) 2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

"use strict";
var options = require('options');
var Raven = require('raven-js');
var $ = require('jquery');

if (options.raven) {
    Raven.config(options.raven, {
        release: options.release,
        environment: options.environment.join("/")
    }).install();
}

var gaProxy;
/* eslint-disable */
if (options.googleAnalyticsEnabled) {
    (function (i, s, o, g, r, a, m) {
        i.GoogleAnalyticsObject = r;
        i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments);
        };
        i[r].l = 1 * new Date();
        a = s.createElement(o);
        m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m);
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
    ga('create', options.googleAnalyticsAccount, 'auto');
    ga('send', 'pageview');
    gaProxy = function () {
        window.ga.apply(window.ga, arguments);
    };
} else {
    gaProxy = function () {};
}
/* eslint-enable */

function initialise() {
    if (options.embedded) return;
    $(function () {
        function create_script_element(id, url) {
            var el = document.createElement('script');
            el.type = 'text/javascript';
            el.async = true;
            el.id = id;
            el.src = url;
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(el, s);
        }

        if (options.sharingEnabled) {
            create_script_element('twitter-wjs', 'https://platform.twitter.com/widgets.js');
        }
    });
}

module.exports = {
    ga: gaProxy,
    initialise: initialise
};
<|endoftext|>


<commit_before>/* global angular */
import {Chess} from '../../contract/Chess.sol';
angular.module('dappChess').factory('gameStates', function () {
  let gameStates = {
    selfMoves: {},
    opponentMoves: {},
    lastMoveNumber: {}
  };

  gameStates.getMoveNumberFromState = function(state) {
    return state[8] * 128 + state[9];
  };

  gameStates.initializeGame = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      gameStates.selfMoves[gameId] = [];
    }
    if(typeof(gameStates.opponentMoves[gameId]) === 'undefined') {
      gameStates.opponentMoves[gameId] = [];
    }
    if(typeof(gameStates.lastMoveNumber[gameId]) === 'undefined') {
      gameStates.lastMoveNumber[gameId] = 0;
    }
  };

  gameStates.addSelfMove = function(gameId, moveFrom, moveTo, newState) {
    gameStates.initializeGame(gameId);

    let moveNumber = gameStates.getMoveNumberFromState(newState);

    // If we already stored this move, don't do anything
    if(gameStates.lastMoveNumber[gameId] === moveNumber) {
      return;
    }
    if(gameStates.lastMoveNumber[gameId] > moveNumber) {
      throw 'Invalid move: The last store move number is higher';
    }

    gameStates.selfMoves[gameId].push({
      moveFrom: moveFrom,
      moveTo: moveTo,
      newState: newState
    });
    gameStates.lastMoveNumber[gameId] = moveNumber;

    gameStates.updateLocalStorage();
  };
  gameStates.addOpponentMove = function(gameId, moveFrom, moveTo,
                                        moveSignature, newState, newStateSignature) {
    gameStates.initializeGame(gameId);

    let moveNumber = gameStates.getMoveNumberFromState(newState);

    // If we already stored this move, don't do anything
    if(gameStates.lastMoveNumber[gameId] === moveNumber) {
      return;
    }
    if(gameStates.lastMoveNumber[gameId] > moveNumber) {
      throw 'Invalid move: The last store move number is higher';
    }

    gameStates.opponentMoves[gameId].push({
      moveFrom: moveFrom,
      moveTo: moveTo,
      moveSignature: moveSignature,
      newState: newState,
      newStateSignature: newStateSignature
    });
    gameStates.lastMoveNumber[gameId] = moveNumber;

    gameStates.updateLocalStorage();
  };

  /**
   * Delete a game from the local storage
   * @param gameId
     */
  gameStates.delete = function(gameId) {
    delete gameStates.selfMoves[gameId];
    delete gameStates.opponentMoves[gameId];
    delete gameStates.lastMoveNumber[gameId];

    gameStates.updateLocalStorage();
  };

  gameStates.getSelfMoves = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      return [];
    }

    return gameStates.selfMoves[gameId];
  };
  gameStates.getLastSelfMove = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      return [];
    }
    if(gameStates.selfMoves[gameId].length === 0) {
      throw 'This game has no self moves yet';
    }

    return gameStates.selfMoves[gameId][gameStates.selfMoves[gameId].length - 1];
  };
  gameStates.getSelfMove = function(gameId, moveNumber) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.selfMoves[gameId].length === 0) {
      throw 'This game has no self moves yet';
    }

    for(let currentMove of gameStates.selfMoves[gameId]) {
      let currentMoveNumber = gameStates.getMoveNumberFromState(currentMove.newState);

      if(currentMoveNumber === moveNumber) {
        return currentMove;
      }
    }
  };

  gameStates.getPreviousOpponentMove = function(gameId) {
    if(typeof(gameStates.opponentMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.opponentMoves[gameId].length === 0) {
      throw 'This game has no opponent moves yet';
    }
    if(gameStates.opponentMoves[gameId].length < 2) {
      throw 'This game has no previous opponent move';
    }
  };
  gameStates.getLastOpponentMove = function(gameId) {
    if(typeof(gameStates.opponentMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.opponentMoves[gameId].length === 0) {
      throw 'This game has no opponent moves yet';
    }

    return gameStates.opponentMoves[gameId][gameStates.opponentMoves[gameId].length - 1];
  };

  /**
   *
   * @param gameId
   * @return boolean
     */
  gameStates.isBlockchainStateNewer = function(gameId) {
    let blockchainState = Chess.getCurrentGameState(gameId);

    if(blockchainState) {
      if(typeof(gameStates.lastMoveNumber[gameId]) === 'undefined') {
        // No state in the local states, so return true
        return true;
      }

      let blockchainMoveNumber = gameStates.getMoveNumberFromState(blockchainState);

      return blockchainMoveNumber > gameStates.lastMoveNumber[gameId];
    }
    // No state in the blockchain, so return false
    return false;
  };

  /**
   * Get an array with all parameters needed to send them to the blockchain.
   * Throws if the last move was not done by oneself.
   * @param gameId
   * @return [oldOpponentState, oldOpponentStateSignature, moveSelfFrom, moveSelfTo]
     */
  gameStates.getSelfMovePackage = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.selfMoves[gameId].length === 0) {
      throw 'This game has no self moves yet';
    }

    let lastSelfMove = gameStates.selfMoves[gameId][gameStates.selfMoves[gameId].length - 1];
    let lastSelfMoveNumber = gameStates.getMoveNumberFromState(lastSelfMove.newState);

    if(lastSelfMoveNumber !== gameStates.lastMoveNumber[gameId]) {
      throw 'The self move was not the last move';
    }

    // There was only one move, and it was the self move => this was our first move as white
    if(gameStates.lastMoveNumber[gameId] === 1) {
      return [null, null, lastSelfMove.moveFrom, lastSelfMove.moveTo];
    }

    let lastOpponentMove = gameStates.opponentMoves[gameId][
      gameStates.opponentMoves[gameId].length - 1
      ];

    return [
      lastOpponentMove.newState,
      lastOpponentMove.newStateSignature,
      lastSelfMove.moveFrom,
      lastSelfMove.moveTo
      ];
  };

  /**
   * Get last state from local storage
   * @param gameId
   * @returns state | false if not in local storage
     */
  gameStates.getLastLocalState = function(game) {
    if(typeof(gameStates.lastMoveNumber[game.gameId]) === 'undefined') {
      return false;
    }

    let lastSelfMove = gameStates.selfMoves[game.gameId][
      gameStates.selfMoves[game.gameId].length - 1];
    let lastSelfMoveNumber = gameStates.getMoveNumberFromState(lastSelfMove.newState);

    if(lastSelfMoveNumber === gameStates.lastMoveNumber[game.gameId]) {
      return lastSelfMove.newState;
    }

    let lastOpponentMove = gameStates.opponentMoves[game.gameId][
      gameStates.opponentMoves[game.gameId].length - 1
    ];
    let lastOpponentMoveNumber = gameStates.getMoveNumberFromState(lastOpponentMove.newState);

    if(lastOpponentMoveNumber === gameStates.lastMoveNumber[game.gameId]) {
      return lastOpponentMove.newState;
    }

    throw 'Could not find last move in self or opponent moves';
  };

  gameStates.getLastBlockchainState = function(game) {
    let blockchainGameState = Chess.getCurrentGameState(game.gameId,
      {from: game.self.accountId});

    blockchainGameState = blockchainGameState.map(function(element) {
      if(typeof(element) === 'object' && typeof(element.toNumber) === 'function') {
        if(element.toNumber() === null) console.log('null: ', element);
        return element.toNumber();
      }

      return element;
    });

    return blockchainGameState;
  };

  gameStates.updateLocalStorage = function() {
    window.localStorage.setItem('gameStates.selfMoves',
      angular.toJson(gameStates.selfMoves));
    window.localStorage.setItem('gameStates.opponentMoves',
      angular.toJson(gameStates.opponentMoves));
    window.localStorage.setItem('gameStates.lastMoveNumber',
      angular.toJson(gameStates.lastMoveNumber));
  };
  gameStates.fetchFromLocalStorage = function() {
    if(typeof(window.localStorage['gameStates.selfMoves']) !== 'undefined') {
      try {
        let movesInLocalStorage = JSON.parse(window.localStorage['gameStates.selfMoves']);
        if(typeof(movesInLocalStorage) === 'object') {
          gameStates.selfMoves = movesInLocalStorage;
        }
        else {
          throw 'Invalid data format of selfMoves';
        }
      }
      catch(e) {
        console.log('Could not parse selfMoves from local storage', e);
      }
    }
    if(typeof(window.localStorage['gameStates.opponentMoves']) !== 'undefined') {
      try {
        let movesInLocalStorage = JSON.parse(window.localStorage['gameStates.opponentMoves']);
        if(typeof(movesInLocalStorage) === 'object') {
          gameStates.opponentMoves = movesInLocalStorage;
        }
        else {
          throw 'Invalid data format of opponentMoves';
        }
      }
      catch(e) {
        console.log('Could not parse opponentMoves from local storage', e);
      }
    }
    if(typeof(window.localStorage['gameStates.lastMoveNumber']) !== 'undefined') {
      try {
        let lastMoveNumber = JSON.parse(window.localStorage['gameStates.lastMoveNumber']);
        if(typeof(lastMoveNumber) === 'object') {
          gameStates.lastMoveNumber = lastMoveNumber;
        }
        else {
          throw 'Invalid data format of lastMoveNumber';
        }
      }
      catch(e) {
        console.log('Could not parse lastMoveNumber from local storage', e);
      }
    }
  };

  gameStates.fetchFromLocalStorage();

  return gameStates;
});
<commit_msg>Fix blamed code of merge request<commit_after>/* global angular */
import {Chess} from '../../contract/Chess.sol';
angular.module('dappChess').factory('gameStates', function () {
  let gameStates = {
    selfMoves: {},
    opponentMoves: {},
    lastMoveNumber: {}
  };

  gameStates.getMoveNumberFromState = function(state) {
    return state[8] * 128 + state[9];
  };

  gameStates.initializeGame = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      gameStates.selfMoves[gameId] = [];
    }
    if(typeof(gameStates.opponentMoves[gameId]) === 'undefined') {
      gameStates.opponentMoves[gameId] = [];
    }
    if(typeof(gameStates.lastMoveNumber[gameId]) === 'undefined') {
      gameStates.lastMoveNumber[gameId] = 0;
    }
  };

  gameStates.addSelfMove = function(gameId, moveFrom, moveTo, newState) {
    gameStates.initializeGame(gameId);

    let moveNumber = gameStates.getMoveNumberFromState(newState);

    // If we already stored this move, don't do anything
    if(gameStates.lastMoveNumber[gameId] === moveNumber) {
      return;
    }
    if(gameStates.lastMoveNumber[gameId] > moveNumber) {
      throw 'Invalid move: The last store move number is higher';
    }

    gameStates.selfMoves[gameId].push({
      moveFrom: moveFrom,
      moveTo: moveTo,
      newState: newState
    });
    gameStates.lastMoveNumber[gameId] = moveNumber;

    gameStates.updateLocalStorage();
  };
  gameStates.addOpponentMove = function(gameId, moveFrom, moveTo,
                                        moveSignature, newState, newStateSignature) {
    gameStates.initializeGame(gameId);

    let moveNumber = gameStates.getMoveNumberFromState(newState);

    // If we already stored this move, don't do anything
    if(gameStates.lastMoveNumber[gameId] === moveNumber) {
      return;
    }
    if(gameStates.lastMoveNumber[gameId] > moveNumber) {
      throw 'Invalid move: The last store move number is higher';
    }

    gameStates.opponentMoves[gameId].push({
      moveFrom: moveFrom,
      moveTo: moveTo,
      moveSignature: moveSignature,
      newState: newState,
      newStateSignature: newStateSignature
    });
    gameStates.lastMoveNumber[gameId] = moveNumber;

    gameStates.updateLocalStorage();
  };

  /**
   * Delete a game from the local storage
   * @param gameId
     */
  gameStates.delete = function(gameId) {
    delete gameStates.selfMoves[gameId];
    delete gameStates.opponentMoves[gameId];
    delete gameStates.lastMoveNumber[gameId];

    gameStates.updateLocalStorage();
  };

  gameStates.getSelfMoves = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      return [];
    }

    return gameStates.selfMoves[gameId];
  };
  gameStates.getLastSelfMove = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      return [];
    }
    if(gameStates.selfMoves[gameId].length === 0) {
      throw 'This game has no self moves yet';
    }

    return gameStates.selfMoves[gameId][gameStates.selfMoves[gameId].length - 1];
  };
  gameStates.getSelfMove = function(gameId, moveNumber) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.selfMoves[gameId].length === 0) {
      throw 'This game has no self moves yet';
    }

    for(let currentMove of gameStates.selfMoves[gameId]) {
      let currentMoveNumber = gameStates.getMoveNumberFromState(currentMove.newState);

      if(currentMoveNumber === moveNumber) {
        return currentMove;
      }
    }
    throw 'Could not find moveNumber ' + moveNumber + ' for the game ' + gameId;
  };

  gameStates.getPreviousOpponentMove = function(gameId) {
    if(typeof(gameStates.opponentMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.opponentMoves[gameId].length === 0) {
      throw 'This game has no opponent moves yet';
    }
    if(gameStates.opponentMoves[gameId].length < 2) {
      throw 'This game has no previous opponent move';
    }

    return gameStates.opponentMoves[gameId][gameStates.opponentMoves[gameId].length - 2];
  };
  gameStates.getLastOpponentMove = function(gameId) {
    if(typeof(gameStates.opponentMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.opponentMoves[gameId].length === 0) {
      throw 'This game has no opponent moves yet';
    }

    return gameStates.opponentMoves[gameId][gameStates.opponentMoves[gameId].length - 1];
  };

  /**
   *
   * @param gameId
   * @return boolean
     */
  gameStates.isBlockchainStateNewer = function(gameId) {
    let blockchainState = Chess.getCurrentGameState(gameId);

    if(blockchainState) {
      if(typeof(gameStates.lastMoveNumber[gameId]) === 'undefined') {
        // No state in the local states, so return true
        return true;
      }

      let blockchainMoveNumber = gameStates.getMoveNumberFromState(blockchainState);

      return blockchainMoveNumber > gameStates.lastMoveNumber[gameId];
    }
    // No state in the blockchain, so return false
    return false;
  };

  /**
   * Get an array with all parameters needed to send them to the blockchain.
   * Throws if the last move was not done by oneself.
   * @param gameId
   * @return [oldOpponentState, oldOpponentStateSignature, moveSelfFrom, moveSelfTo]
     */
  gameStates.getSelfMovePackage = function(gameId) {
    if(typeof(gameStates.selfMoves[gameId]) === 'undefined') {
      throw 'This game has no moves yet';
    }
    if(gameStates.selfMoves[gameId].length === 0) {
      throw 'This game has no self moves yet';
    }

    // gameStates.selfMoves[gameId][gameStates.selfMoves[gameId].length - 1];
    let lastSelfMove = gameStates.getLastSelfMove(gameId);
    let lastSelfMoveNumber = gameStates.getMoveNumberFromState(lastSelfMove.newState);

    // There was only one move, and it was the self move => this was our first move as white
    if (gameStates.lastMoveNumber[gameId] === 1) {
      return [null, null, lastSelfMove.moveFrom, lastSelfMove.moveTo];
    }

    let opponentMove = gameStates.getLastOpponentMove(gameId);
    let opponentMoveNumber = gameStates.getMoveNumberFromState(opponentMove.newState);

    if (opponentMoveNumber + 1 !== lastSelfMoveNumber) {
      opponentMove = gameStates.getPreviousOpponentMove(gameId);
      opponentMoveNumber = gameStates.getMoveNumberFromState(opponentMove.newState);
      if (opponentMoveNumber + 1 !== lastSelfMoveNumber) {
        throw 'No move package found for last self move.';
      }
    }

    return [
      opponentMove.newState,
      opponentMove.newStateSignature,
      lastSelfMove.moveFrom,
      lastSelfMove.moveTo
    ];
  };

  /**
   * Get last state from local storage
   * @param gameId
   * @returns state | false if not in local storage
     */
  gameStates.getLastLocalState = function (game) {
    if (typeof gameStates.lastMoveNumber[game.gameId] === 'undefined') {
      return false;
    }

    if (gameStates.selfMoves[game.gameId] !== 'undefined' &&
        gameStates.selfMoves[game.gameId].length > 0) {
      let lastSelfMove = gameStates.getLastSelfMove(game.gameId);
      let lastSelfMoveNumber = gameStates.getMoveNumberFromState(lastSelfMove.newState);

      if (lastSelfMoveNumber === gameStates.lastMoveNumber[game.gameId]) {
        return lastSelfMove.newState;
      }
    }

    if (gameStates.opponentMoves[game.gameId] !== 'undefined' &&
        gameStates.opponentMoves[game.gameId].length > 0) {
      let lastOpponentMove = gameStates.getLastOpponentMove(game.gameId);
      let lastOpponentMoveNumber = gameStates.getMoveNumberFromState(lastOpponentMove.newState);

      if (lastOpponentMoveNumber === gameStates.lastMoveNumber[game.gameId]) {
        return lastOpponentMove.newState;
      }
    }

    throw 'Could not find last move in self or opponent moves';
  };

  gameStates.getLastBlockchainState = function(game) {
    let blockchainGameState = Chess.getCurrentGameState(game.gameId,
      {from: game.self.accountId});

    blockchainGameState = blockchainGameState.map(function(element) {
      if(typeof(element) === 'object' && typeof(element.toNumber) === 'function') {
        return element.toNumber();
      }

      return element;
    });

    return blockchainGameState;
  };

  gameStates.updateLocalStorage = function() {
    window.localStorage.setItem('gameStates.selfMoves',
      angular.toJson(gameStates.selfMoves));
    window.localStorage.setItem('gameStates.opponentMoves',
      angular.toJson(gameStates.opponentMoves));
    window.localStorage.setItem('gameStates.lastMoveNumber',
      angular.toJson(gameStates.lastMoveNumber));
  };
  gameStates.fetchFromLocalStorage = function() {
    if(typeof(window.localStorage['gameStates.selfMoves']) !== 'undefined') {
      try {
        let movesInLocalStorage = JSON.parse(window.localStorage['gameStates.selfMoves']);
        if(typeof(movesInLocalStorage) === 'object') {
          gameStates.selfMoves = movesInLocalStorage;
        }
        else {
          throw 'Invalid data format of selfMoves';
        }
      }
      catch(e) {
        console.log('Could not parse selfMoves from local storage', e);
      }
    }
    if(typeof(window.localStorage['gameStates.opponentMoves']) !== 'undefined') {
      try {
        let movesInLocalStorage = JSON.parse(window.localStorage['gameStates.opponentMoves']);
        if(typeof(movesInLocalStorage) === 'object') {
          gameStates.opponentMoves = movesInLocalStorage;
        }
        else {
          throw 'Invalid data format of opponentMoves';
        }
      }
      catch(e) {
        console.log('Could not parse opponentMoves from local storage', e);
      }
    }
    if(typeof(window.localStorage['gameStates.lastMoveNumber']) !== 'undefined') {
      try {
        let lastMoveNumber = JSON.parse(window.localStorage['gameStates.lastMoveNumber']);
        if(typeof(lastMoveNumber) === 'object') {
          gameStates.lastMoveNumber = lastMoveNumber;
        }
        else {
          throw 'Invalid data format of lastMoveNumber';
        }
      }
      catch(e) {
        console.log('Could not parse lastMoveNumber from local storage', e);
      }
    }
  };

  gameStates.fetchFromLocalStorage();

  return gameStates;
});
<|endoftext|>


<commit_before>var staff =
{
	data : "",
	init : function() {
		$.getJSON("js/staff.json", function(json) {
			staff.data = json;
		}).done(function() { staff.output(); });
	},
	output : function() {
		$page = $('#staff').children('.people');
		for(i=0; i<this.data.length; i++) {
			for(j=0; j<this.data[i].length; j++) {
				dir = 'data/' + (i+1) + '/' + this.data[i][j].name;
				label = '
' + this.data[i][j].name + '
';
				column = '

'
				$page.eq(i).append('
' + label + column + '
')
				$('.description').last().load(dir+'.txt');
			}
		}
	}
};
jQuery(document).ready(function($) {
	staff.init();
	var $NavBar = $('#NavBar'), NavOffset = $NavBar.offset().top;
	$(window).scroll(function () {
		if($(this).scrollTop() > NavOffset) {
			$NavBar
				.removeClass('item')
				.addClass('Float')
				.addClass('secondary')
				.addClass('vertical');
		}
		else {
			$NavBar
				.addClass('item')
				.removeClass('Float')
				.removeClass('secondary')
				.removeClass('vertical')
				.children('.item')
				.removeClass('active');
		}
	});
	$('#slides').slidesjs({
		width: 680,
		height: 453,
		play: {
			active: true,
			auto: false,
			interval: 4000,
			swap: true,
			pauseOnHover: true,
			restartDelay: 2500
		}
	});
	$('.popup').popup({
		transition: "vertical flip"
	});
});
<commit_msg>core.js bug fixed<commit_after>var staff =
{
	data : "",
	init : function() {
		$.getJSON("js/staff.json", function(json) {
			staff.data = json;
		}).done(function() { staff.output(); });
	},
	output : function() {
		$page = $('#staff').children('.people');
		for(i=0; i<this.data.length; i++) {
			for(j=0; j<this.data[i].length; j++) {
				dir = 'data/' + (i+1) + '/' + this.data[i][j].name;
				label = '
' + this.data[i][j].name + '
';
				column = '

'
				$page.eq(i).append('
' + label + column + '
')
				$('.description').last().load(dir+'.txt');
			}
		}
	}
};
jQuery(document).ready(function($) {
	staff.init();
	var $NavBar = $('#NavBar'), NavOffset = $NavBar.offset().top;
	if($(window).scrollTop() > NavOffset) {
		$NavBar
			.removeClass('item')
			.addClass('Float')
			.addClass('secondary')
			.addClass('vertical');
	}
	else {
		$NavBar
			.addClass('item')
			.removeClass('Float')
			.removeClass('secondary')
			.removeClass('vertical')
			.children('.item')
			.removeClass('active');
	}
	$(window).scroll(function () {
		if($(this).scrollTop() > NavOffset) {
			$NavBar
				.removeClass('item')
				.addClass('Float')
				.addClass('secondary')
				.addClass('vertical');
		}
		else {
			$NavBar
				.addClass('item')
				.removeClass('Float')
				.removeClass('secondary')
				.removeClass('vertical')
				.children('.item')
				.removeClass('active');
		}
	});
	$('#slides').slidesjs({
		width: 680,
		height: 453,
		play: {
			active: true,
			auto: false,
			interval: 4000,
			swap: true,
			pauseOnHover: true,
			restartDelay: 2500
		}
	});
	$('.popup').popup({
		transition: "vertical flip"
	});
});
<|endoftext|>