<commit_before>'use strict';

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

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

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

module.exports = class ice3x extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ice3x',
            'name': 'ICE3X',
            'countries': 'ZA',
            'rateLimit': 1000,
            'has': {
                'fetchCurrencies': true,
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchDepositAddress': true,
            },
            'urls': {
                'logo': 'https://ice3x.com/topleftcorner',
                'api': 'https://ice3x.com/api/v1',
                'www': [
                    'https://ice3x.com/',
                    'https://ice3x.co.za/',
                ],
                'doc': 'https://ice3x.co.za/ice-cubed-bitcoin-exchange-api-documentation-1-june-2017/',
                'fees': [
                    'https://help.ice3.com/support/solutions/articles/11000033293-trading-fees',
                    'https://help.ice3.com/support/solutions/articles/11000033288-fees-explained',
                    'https://help.ice3.com/support/solutions/articles/11000008131-what-are-your-fiat-deposit-and-withdrawal-fees-',
                    'https://help.ice3.com/support/solutions/articles/11000033289-deposit-fees',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        'currency/list',
                        'currency/info',
                        'pair/list',
                        'pair/info',
                        'stats/marketdepthfull',
                        'stats/marketdepthbtcav',
                        'stats/marketdepth',
                        'orderbook/info',
                        'trade/list',
                        'trade/info',
                    ],
                },
                'private': {
                    'post': [
                        'balance/list',
                        'balance/info',
                        'order/new',
                        'order/cancel',
                        'order/list',
                        'order/info',
                        'trade/list',
                        'trade/info',
                        'transaction/list',
                        'transaction/info',
                        'invoice/list',
                        'invoice/info',
                        'invoice/pdf',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.01,
                    'taker': 0.01,
                },
            },
            'precision': {
                'amount': 8,
                'price': 8,
            },
        });
    }

    async fetchCurrencies (params = {}) {
        let currencies = await this.publicGetCurrencyList (params);
        currencies = currencies['entities'];
        let precision = this.precision['amount'];
        let result = {};
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let id = currency['currency_id'];
            let code = this.commonCurrencyCode (currency['iso'].toUpperCase ());
            result[code] = {
                'id': id,
                'code': code,
                'name': currency['name'],
                'active': true,
                'status': 'ok',
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': undefined,
                        'max': Math.pow (10, precision),
                    },
                    'price': {
                        'min': Math.pow (10, -precision),
                        'max': Math.pow (10, precision),
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': currency,
            };
        }
        return result;
    }

    async fetchMarkets () {
        if (!Object.keys (this.currencies).length) {
            this.currencies = await this.fetchCurrencies ();
        }
        this.currenciesById = this.indexBy (this.currencies, 'id');
        let markets = await this.publicGetPairList ();
        markets = markets['entities'];
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['pair_id'];
            let baseId = market['currency_id_from'];
            let quoteId = market['currency_id_to'];
            let baseCurrency = this.currenciesById[baseId];
            let quoteCurrency = this.currenciesById[quoteId];
            let base = this.commonCurrencyCode (baseCurrency['code']);
            let quote = this.commonCurrencyCode (quoteCurrency['code']);
            let symbol = base + '/' + quote;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'lot': undefined,
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'max'),
            'low': this.safeFloat (ticker, 'min'),
            'bid': this.safeFloat (ticker, 'max_bid'),
            'ask': this.safeFloat (ticker, 'min_ask'),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['last_price']),
            'change': undefined,
            'percentage': undefined,
            'average': this.safeFloat (ticker, 'avg'),
            'baseVolume': undefined,
            'quoteVolume': parseFloat (ticker['vol']),
            'info': ticker,
        };
    }

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

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetStatsMarketdepthfull (params);
        tickers = tickers['entities'];
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = tickers[i];
            let market = this.marketsById[ticker['pair_id']];
            let symbol = market['symbol'];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let orderbook = await this.publicGetOrderbookInfo (this.extend ({
            'pair_id': this.marketId (symbol),
        }, params));
        orderbook = orderbook['entities'];
        return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'amount');
    }

    parseTrade (trade, market = undefined) {
        let timestamp = parseInt (trade['created']) * 1000;
        let price = parseFloat (trade['price']);
        let amount = parseFloat (trade['volume']);
        let symbol = market['symbol'];
        let cost = parseFloat (this.costToPrecision (symbol, price * amount));
        let fee = this.safeFloat (trade, 'fee');
        if (fee) {
            fee = {
                'cost': fee,
                'currency': market['quote'],
            };
        }
        return {
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': this.safeString (trade, 'trade_id'),
            'order': undefined,
            'type': 'limit',
            'side': trade['type'],
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': fee,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let trades = await this.publicGetTradeList (this.extend ({
            'pair_id': market['id'],
        }, params));
        return this.parseTrades (trades['entities'], market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privatePostBalanceList (params);
        balances = balances['entities'];
        let result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let id = balance['currency_id'];
            if (id in this.currencies_by_id) {
                let currency = this.currencies_by_id[id];
                let code = currency['code'];
                result[code] = {
                    'free': 0.0,
                    'used': 0.0,
                    'total': parseFloat (balance['balance']),
                };
            }
        }
        return this.parseBalance (result);
    }

    parseOrder (order, market = undefined) {
        let pairId = this.safeInteger (order, 'pair_id');
        let symbol = undefined;
        if (pairId && !market && (pairId in this.marketsById)) {
            market = this.marketsById[pairId];
            symbol = market['symbol'];
        }
        let timestamp = this.safeInteger (order, 'created') * 1000;
        let price = parseFloat (order['price']);
        let amount = this.safeFloat (order, 'volume');
        let status = this.safeInteger (order, 'active');
        let remaining = this.safeFloat (order, 'remaining');
        let filled = undefined;
        if (status === 1) {
            status = 'open';
        } else {
            status = 'closed';
            remaining = 0;
            filled = amount;
        }
        let fee = this.safeFloat (order, 'fee');
        if (fee) {
            fee = { 'cost': fee };
            if (market)
                fee['currency'] = market['quote'];
        }
        return {
            'id': this.safeString (order, 'order_id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'status': status,
            'symbol': symbol,
            'type': 'limit',
            'side': order['type'],
            'price': price,
            'cost': undefined,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'trades': undefined,
            'fee': fee,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.privatePostOrderNew (this.extend ({
            'pair_id': market['id'],
            'type': side,
            'amount': amount,
            'price': price,
        }, params));
        let order = this.parseOrder ({
            'order_id': response['entity']['order_id'],
            'created': this.seconds (),
            'active': 1,
            'type': side,
            'price': price,
            'volume': amount,
            'remaining': amount,
            'info': response,
        }, market);
        let id = order['id'];
        this.orders[id] = order;
        return order;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        let result = await this.privatePostOrderCancel (this.extend ({
            'order_id': id,
        }, params));
        return result;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let order = await this.privatePostOrderInfo (this.extend ({
            'order _id': id,
        }, params));
        return this.parseOrder (order['entity']);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let orders = await this.privatePostOrderList ();
        return this.parseOrders (orders['entities'], undefined, since, limit);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'pair_id': market['id'],
        };
        if (limit)
            request['items_per_page'] = limit;
        if (since)
            request['date_from'] = parseInt (since / 1000);
        let trades = await this.privatePostTradeList (this.extend (request, params));
        return this.parseTrades (trades['entities'], market, since, limit);
    }

    async fetchDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (code);
        let response = await this.privatePostBalanceInfo (this.extend ({
            'currency_id': currency['id'],
        }, params));
        let balance = response['entity'];
        let address = this.safeString (balance, 'address');
        let status = address ? 'ok' : 'none';
        return {
            'currency': code,
            'address': address,
            'tag': undefined,
            'status': status,
            'info': response,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + path;
        if (api === 'public') {
            params = this.urlencode (params);
            if (params.length)
                url += '?' + params;
        } else {
            this.checkRequiredCredentials ();
            body = this.urlencode (this.extend ({
                'nonce': this.nonce (),
            }, params));
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Key': this.apiKey,
                'Sign': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'),
            };
        }
        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);
        let errors = this.safeValue (response, 'errors');
        if (errors || !response['response']) {
            let authErrorKeys = [ 'Key', 'user_id', 'Sign' ];
            for (let i = 0; i < authErrorKeys.length; i++ ) {
                let errorKey = authErrorKeys[i];
                let errorMessage = this.safeString (errors, errorKey);
                if (!errorMessage)
                    continue;
                if (errorKey === 'user_id' && errorMessage.indexOf ('authorization') < 0)
                    continue;
                throw new AuthenticationError (errorMessage);
            }
            throw new ExchangeError (this.json (response['errors']));
        }
        return response['response'];
    }
};
<commit_msg>ice3x: response<commit_after>'use strict';

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

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

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

module.exports = class ice3x extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ice3x',
            'name': 'ICE3X',
            'countries': 'ZA',
            'rateLimit': 1000,
            'has': {
                'fetchCurrencies': true,
                'fetchTickers': true,
                'fetchOpenOrders': true,
                'fetchDepositAddress': true,
            },
            'urls': {
                'logo': 'https://ice3x.com/topleftcorner',
                'api': 'https://ice3x.com/api/v1',
                'www': [
                    'https://ice3x.com/',
                    'https://ice3x.co.za/',
                ],
                'doc': 'https://ice3x.co.za/ice-cubed-bitcoin-exchange-api-documentation-1-june-2017/',
                'fees': [
                    'https://help.ice3.com/support/solutions/articles/11000033293-trading-fees',
                    'https://help.ice3.com/support/solutions/articles/11000033288-fees-explained',
                    'https://help.ice3.com/support/solutions/articles/11000008131-what-are-your-fiat-deposit-and-withdrawal-fees-',
                    'https://help.ice3.com/support/solutions/articles/11000033289-deposit-fees',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        'currency/list',
                        'currency/info',
                        'pair/list',
                        'pair/info',
                        'stats/marketdepthfull',
                        'stats/marketdepthbtcav',
                        'stats/marketdepth',
                        'orderbook/info',
                        'trade/list',
                        'trade/info',
                    ],
                },
                'private': {
                    'post': [
                        'balance/list',
                        'balance/info',
                        'order/new',
                        'order/cancel',
                        'order/list',
                        'order/info',
                        'trade/list',
                        'trade/info',
                        'transaction/list',
                        'transaction/info',
                        'invoice/list',
                        'invoice/info',
                        'invoice/pdf',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.01,
                    'taker': 0.01,
                },
            },
            'precision': {
                'amount': 8,
                'price': 8,
            },
        });
    }

    async fetchCurrencies (params = {}) {
        let response = await this.publicGetCurrencyList (params);
        let currencies = response['response']['entities'];
        let precision = this.precision['amount'];
        let result = {};
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let id = currency['currency_id'];
            let code = this.commonCurrencyCode (currency['iso'].toUpperCase ());
            result[code] = {
                'id': id,
                'code': code,
                'name': currency['name'],
                'active': true,
                'status': 'ok',
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': undefined,
                        'max': Math.pow (10, precision),
                    },
                    'price': {
                        'min': Math.pow (10, -precision),
                        'max': Math.pow (10, precision),
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': currency,
            };
        }
        return result;
    }

    async fetchMarkets () {
        if (!Object.keys (this.currencies).length) {
            this.currencies = await this.fetchCurrencies ();
        }
        this.currenciesById = this.indexBy (this.currencies, 'id');
        let response = await this.publicGetPairList ();
        let markets = response['response']['entities'];
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['pair_id'];
            let baseId = market['currency_id_from'];
            let quoteId = market['currency_id_to'];
            let baseCurrency = this.currenciesById[baseId];
            let quoteCurrency = this.currenciesById[quoteId];
            let base = this.commonCurrencyCode (baseCurrency['code']);
            let quote = this.commonCurrencyCode (quoteCurrency['code']);
            let symbol = base + '/' + quote;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'lot': undefined,
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'max'),
            'low': this.safeFloat (ticker, 'min'),
            'bid': this.safeFloat (ticker, 'max_bid'),
            'ask': this.safeFloat (ticker, 'min_ask'),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['last_price']),
            'change': undefined,
            'percentage': undefined,
            'average': this.safeFloat (ticker, 'avg'),
            'baseVolume': undefined,
            'quoteVolume': parseFloat (ticker['vol']),
            'info': ticker,
        };
    }

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

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetStatsMarketdepthfull (params);
        let tickers = response['response']['entities'];
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = tickers[i];
            let market = this.marketsById[ticker['pair_id']];
            let symbol = market['symbol'];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetOrderbookInfo (this.extend ({
            'pair_id': this.marketId (symbol),
        }, params));
        let orderbook = response['response']['entities'];
        return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'amount');
    }

    parseTrade (trade, market = undefined) {
        let timestamp = parseInt (trade['created']) * 1000;
        let price = parseFloat (trade['price']);
        let amount = parseFloat (trade['volume']);
        let symbol = market['symbol'];
        let cost = parseFloat (this.costToPrecision (symbol, price * amount));
        let fee = this.safeFloat (trade, 'fee');
        if (fee) {
            fee = {
                'cost': fee,
                'currency': market['quote'],
            };
        }
        return {
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': this.safeString (trade, 'trade_id'),
            'order': undefined,
            'type': 'limit',
            'side': trade['type'],
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': fee,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetTradeList (this.extend ({
            'pair_id': market['id'],
        }, params));
        let trades = response['response']['entities'];
        return this.parseTrades (trades, market, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostBalanceList (params);
        let result = { 'info': response };
        let balances = response['response']['entities'];
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let id = balance['currency_id'];
            if (id in this.currencies_by_id) {
                let currency = this.currencies_by_id[id];
                let code = currency['code'];
                result[code] = {
                    'free': 0.0,
                    'used': 0.0,
                    'total': parseFloat (balance['balance']),
                };
            }
        }
        return this.parseBalance (result);
    }

    parseOrder (order, market = undefined) {
        let pairId = this.safeInteger (order, 'pair_id');
        let symbol = undefined;
        if (pairId && !market && (pairId in this.marketsById)) {
            market = this.marketsById[pairId];
            symbol = market['symbol'];
        }
        let timestamp = this.safeInteger (order, 'created') * 1000;
        let price = parseFloat (order['price']);
        let amount = this.safeFloat (order, 'volume');
        let status = this.safeInteger (order, 'active');
        let remaining = this.safeFloat (order, 'remaining');
        let filled = undefined;
        if (status === 1) {
            status = 'open';
        } else {
            status = 'closed';
            remaining = 0;
            filled = amount;
        }
        let fee = this.safeFloat (order, 'fee');
        if (fee) {
            fee = { 'cost': fee };
            if (market)
                fee['currency'] = market['quote'];
        }
        return {
            'id': this.safeString (order, 'order_id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'status': status,
            'symbol': symbol,
            'type': 'limit',
            'side': order['type'],
            'price': price,
            'cost': undefined,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'trades': undefined,
            'fee': fee,
            'info': order,
        };
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.privatePostOrderNew (this.extend ({
            'pair_id': market['id'],
            'type': side,
            'amount': amount,
            'price': price,
        }, params));
        let order = this.parseOrder ({
            'order_id': response['response']['entity']['order_id'],
            'created': this.seconds (),
            'active': 1,
            'type': side,
            'price': price,
            'volume': amount,
            'remaining': amount,
            'info': response,
        }, market);
        let id = order['id'];
        this.orders[id] = order;
        return order;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        let response = await this.privatePostOrderCancel (this.extend ({
            'order_id': id,
        }, params));
        return response;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostOrderInfo (this.extend ({
            'order _id': id,
        }, params));
        return this.parseOrder (response['response']['entity']);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostOrderList ();
        let orders = response['response']['entities'];
        return this.parseOrders (orders, undefined, since, limit);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'pair_id': market['id'],
        };
        if (limit)
            request['items_per_page'] = limit;
        if (since)
            request['date_from'] = parseInt (since / 1000);
        let response = await this.privatePostTradeList (this.extend (request, params));
        let trades = response['response']['entities'];
        return this.parseTrades (trades, market, since, limit);
    }

    async fetchDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (code);
        let response = await this.privatePostBalanceInfo (this.extend ({
            'currency_id': currency['id'],
        }, params));
        let balance = response['response']['entity'];
        let address = this.safeString (balance, 'address');
        let status = address ? 'ok' : 'none';
        return {
            'currency': code,
            'address': address,
            'tag': undefined,
            'status': status,
            'info': response,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + path;
        if (api === 'public') {
            params = this.urlencode (params);
            if (params.length)
                url += '?' + params;
        } else {
            this.checkRequiredCredentials ();
            body = this.urlencode (this.extend ({
                'nonce': this.nonce (),
            }, params));
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Key': this.apiKey,
                'Sign': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'),
            };
        }
        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);
        let errors = this.safeValue (response, 'errors');
        let data = this.safeValue (response, 'response');
        if (errors || !data) {
            let authErrorKeys = [ 'Key', 'user_id', 'Sign' ];
            for (let i = 0; i < authErrorKeys.length; i++ ) {
                let errorKey = authErrorKeys[i];
                let errorMessage = this.safeString (errors, errorKey);
                if (!errorMessage)
                    continue;
                if (errorKey === 'user_id' && errorMessage.indexOf ('authorization') < 0)
                    continue;
                throw new AuthenticationError (errorMessage);
            }
            throw new ExchangeError (this.json (errors));
        }
        return response;
    }
};
<|endoftext|>


<commit_before>const $ = require('jquery');
const Board = require('./board.js')
const Snake = require('./snake.js')

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext('2d');

let board = new Board(canvas, ctx);
let snake = new Snake();

function animate() {
  requestAnimationFrame(function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    snake.draw();
    snake.moveLeft;
    if (snake.wallDetection === true) {
    } else {
      requestAnimationFrame(gameLoop);
    }
  }
)};
animate();
<commit_msg>add keyDownListener - listener is working and moving snake node, but making large jumps and not maintaining new direction<commit_after>const $ = require('jquery');
const Board = require('./board.js')
const Snake = require('./snake.js')

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext('2d');

let board = new Board(canvas, ctx);
let snake = new Snake();

function animate() {
  requestAnimationFrame(function gameLoop() {
    keyDownListener();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    snake.draw();
    // snake.moveDown;
    if (snake.wallDetection === true) {
    } else {
      requestAnimationFrame(gameLoop);
    }
  }
)};

function keyDownListener() {
  $(document).keydown(function(e) {
    if (e.keyCode === 37) {
      console.log("Left")
      snake.moveLeft;
    } else if (e.keyCode == 38) {
      console.log("Up")
      snake.moveUp;
    } else if (e.keyCode == 39) {
      console.log("Right")
      snake.moveRight;
    } else if (e.keyCode = 40) {
      console.log("Down")
      snake.moveDown;
    }
  })
}

animate();
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Lo<commit_msg>AAAAAAAAAAARGH!<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Log<|endoftext|>


<commit_before>import h from 'virtual-dom/h'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import createElement from 'virtual-dom/create-element'

let debug = false;

class Thunk {
  constructor(renderFn, state, shouldUpdate, name) {
    this.type = 'Thunk';
    this.renderFn = renderFn;
    this.state = state;
    this.shouldUpdate = shouldUpdate;
    this.name = name;
  }

  render(previous) {
    var previousState = previous ? previous.state : null;
    if (this.shouldUpdate(this.state, previousState)) {
      if (debug) {
        console.log('call render of ', this.name);
      }
      return this.renderFn(this.state);
    }
    return previous.vnode;
  }
}

export class Component {
  constructor(state) {
    this.thunk = this.newThunk(state);
  }

  newThunk(state) {
    return new Thunk((state) => {
      let Hook = function(){}
      Hook.prototype.hook = (element) => {
        this.element = element;
        this.elementChanged(element);
      };
      let vnode = h(this.constructor.name, {
        'element-changed': new Hook(),
      }, [this.render(state)]);
      return vnode;
    }, state, this.shouldUpdate.bind(this), this.constructor.name);
  }

  // abstract
  render(state) {
    return h();
  }

  bind(parent) {
    this.element = createElement(this.thunk);
    parent.appendChild(this.element);
  }

  // abstract
  reduce(state, type, data) {
    return state;
  }

  emit(type, data) {
    let newState = this.reduce(this.thunk.state, type, data);
    let newThunk = this.newThunk(newState);
    let patches = diff(this.thunk, newThunk);
    this.element = patch(this.element, patches);
    this.thunk = newThunk;
  }

  // abstract
  elementChanged(element) {
    if (debug) {
      console.log('element changed', this.constructor.name);
    }
  }

  boundedEqual(a, b, n) {
    if (a === b) {
      return true;
    }
    if (n == 0) {
      return a === b;
    }
    let aType = typeof a;
    let bType = typeof b;
    if (aType != bType) {
      return false;
    }
    switch (aType) {
    case 'object':
      let aKeys = Object.keys(a);
      let bKeys = Object.keys(b);
      if (aKeys.length != bKeys.length) {
        return false;
      }
      let len = aKeys.length;
      for (let i = 0; i < len; i++) {
        let key = aKeys[i];
        if (!this.boundedEqual(a[key], b[key], n - 1)) {
          if (key.slice(0, 1) == 'on' && typeof a[key] == 'function' && typeof b[key] == 'function') {
            continue; // skip event handlers
          }
          return false;
        }
      }
      return true;
    default:
      return this.boundedEqual(a, b, n - 1);
    }
  }

  // abstract
  shouldUpdate(state, previousState) {
    if (previousState === undefined && state === undefined) {
      // no state
      return false;
    }
    if (!previousState || !state) {
      return true;
    }
    return !this.boundedEqual(state, previousState, 2);
  }
}

export function e(selector, properties, children) {
  switch (typeof selector) {
  case 'string':
    return h(selector, properties, children);
  default:
    return new selector(properties).thunk;
  }
}

export var none = h('div', { style: { display: 'none' } });
export var clear = h('div', { style: { clear: 'both' } });

export function div(...subs) {
  return h('div', {}, [...subs]);
}

export function merge(a, b) {
  let aType = typeof a;
  let bType = typeof b;
  if (aType == 'object' && bType == 'object') {
    let obj = {};
    if (b['>_<']) {
      for (let key in a) {
        obj[key] = merge(a[key], b['>_<']);
      }
    } else {
      for (let key in b) {
        if (a[key]) {
          obj[key] = merge(a[key], b[key]);
        } else {
          obj[key] = b[key];
        }
      }
      for (let key in a) {
        if (key in obj) {
          continue
        }
        obj[key] = a[key];
      }
    }
    return obj;
  } else {
    return b;
  }
}

/*
console.log(merge({
  categories: {
    1: {
      dishes: {
        1: {
          selected: 5,
        },
      },
      weekly_dishes: {
        1: {
          selected: 5,
        },
      },
    },
    2: {
      dishes: {
        1: {
          selected: 5,
        },
      },
      weekly_dishes: {
        1: {
          selected: 5,
        },
      },
    },
  },
}, {
  categories: {
    '>_<': {
      dishes: {
        '>_<': {
          selected: 0,
        },
      },
      weekly_dishes: {
        '>_<': {
          selected: 0,
        },
      },
    },
  },
}));
*/
<commit_msg>add Store<commit_after>import h from 'virtual-dom/h'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import createElement from 'virtual-dom/create-element'

let debug = false;

class Thunk {
  constructor(renderFn, state, shouldUpdate, name) {
    this.type = 'Thunk';
    this.renderFn = renderFn;
    this.state = state;
    this.shouldUpdate = shouldUpdate;
    this.name = name;
  }

  render(previous) {
    var previousState = previous ? previous.state : null;
    if (this.shouldUpdate(this.state, previousState)) {
      if (debug) {
        console.log('call render of ', this.name);
      }
      return this.renderFn(this.state);
    }
    return previous.vnode;
  }
}

export class Component {
  constructor(state) {
    this.thunk = this.newThunk(state);
  }

  newThunk(state) {
    return new Thunk((state) => {
      let Hook = function(){}
      Hook.prototype.hook = (element) => {
        this.element = element;
        this.elementChanged(element);
      };
      let vnode = h(this.constructor.name, {
        'element-changed': new Hook(),
      }, [this.render(state)]);
      return vnode;
    }, state, this.shouldUpdate.bind(this), this.constructor.name);
  }

  // abstract
  render(state) {
    return h();
  }

  bind(parent) {
    this.element = createElement(this.thunk);
    parent.appendChild(this.element);
  }

  setState(newState) {
    let newThunk = this.newThunk(newState);
    let patches = diff(this.thunk, newThunk);
    this.element = patch(this.element, patches);
    this.thunk = newThunk;
  }

  setStore(store) {
    store.setComponent(this);
  }

  // abstract
  elementChanged(element) {
    if (debug) {
      console.log('element changed', this.constructor.name);
    }
  }

  boundedEqual(a, b, n) {
    if (a === b) {
      return true;
    }
    if (n == 0) {
      return a === b;
    }
    let aType = typeof a;
    let bType = typeof b;
    if (aType != bType) {
      return false;
    }
    switch (aType) {
    case 'object':
      let aKeys = Object.keys(a);
      let bKeys = Object.keys(b);
      if (aKeys.length != bKeys.length) {
        return false;
      }
      let len = aKeys.length;
      for (let i = 0; i < len; i++) {
        let key = aKeys[i];
        if (!this.boundedEqual(a[key], b[key], n - 1)) {
          if (key.slice(0, 1) == 'on' && typeof a[key] == 'function' && typeof b[key] == 'function') {
            continue; // skip event handlers
          }
          return false;
        }
      }
      return true;
    default:
      return this.boundedEqual(a, b, n - 1);
    }
  }

  // abstract
  shouldUpdate(state, previousState) {
    if (previousState === undefined && state === undefined) {
      // no state
      return false;
    }
    if (!previousState || !state) {
      return true;
    }
    return !this.boundedEqual(state, previousState, 2);
  }
}

export class Store {
  constructor(initState, eventHandler) {
    this.state = initState;
    this.eventHandler = eventHandler;
  }

  emit(type, data) {
    this.state = this.eventHandler(this.state, type, data);
    if (this.component) {
      this.component.setState(this.state);
    }
  }

  setComponent(component) {
    this.component = component;
  }
}

export function e(selector, properties, children) {
  switch (typeof selector) {
  case 'string':
    return h(selector, properties, children);
  default:
    return new selector(properties).thunk;
  }
}

export var none = h('div', { style: { display: 'none' } });
export var clear = h('div', { style: { clear: 'both' } });

export function div(...subs) {
  return h('div', {}, [...subs]);
}

export function merge(a, b) {
  let aType = typeof a;
  let bType = typeof b;
  if (aType == 'object' && bType == 'object') {
    let obj = {};
    if (b['>_<']) {
      for (let key in a) {
        obj[key] = merge(a[key], b['>_<']);
      }
    } else {
      for (let key in b) {
        if (a[key]) {
          obj[key] = merge(a[key], b[key]);
        } else {
          obj[key] = b[key];
        }
      }
      for (let key in a) {
        if (key in obj) {
          continue
        }
        obj[key] = a[key];
      }
    }
    return obj;
  } else {
    return b;
  }
}

/*
console.log(merge({
  categories: {
    1: {
      dishes: {
        1: {
          selected: 5,
        },
      },
      weekly_dishes: {
        1: {
          selected: 5,
        },
      },
    },
    2: {
      dishes: {
        1: {
          selected: 5,
        },
      },
      weekly_dishes: {
        1: {
          selected: 5,
        },
      },
    },
  },
}, {
  categories: {
    '>_<': {
      dishes: {
        '>_<': {
          selected: 0,
        },
      },
      weekly_dishes: {
        '>_<': {
          selected: 0,
        },
      },
    },
  },
}));
*/
<|endoftext|>


<commit_before>$('form').one("submit", function(event) {
  event.preventDefault();

  var send = $(this).serialize()
    $.ajax({
      type: 'GET',
      url: './download.php',
      data: send,
      dataType: 'json',
      success: function(obj) {
        var value = obj[0];

          $("ul").append("
" + "Demand for power is " + value.demand + "GW" + "
");
          $("ul").append("
" + "Wind Power supplies " + value.wind + "GW" + "
");
          $("ul").append("
" + "Wind Power accounts for around " + ((value.wind / value.demand) * 100).toFixed(2) + "%" + " of the total Energy Supply" + "
");

          var wind = ((value.wind / value.demand) * 100).toFixed(2); // need this to be the output of our JSON func, ((value.wind / value.demand) * 100).toFixed(2)

          if (wind <= 3) {
            $('.rotor').css('-webkit-animation', 'rotate 40s infinite linear');
          }
          else if (wind > 3 && wind <= 8) {
            $('.rotor').css('-webkit-animation', 'rotate 20s infinite linear');
          }
          else {
            $('.rotor').css('-webkit-animation', 'rotate 2s infinite linear');
          }
        },
      error: function() {
        alert('Error');
      }
    });
});

$('#datetimepicker_start').datetimepicker({
  format: 'unixtime'
});
$('#datetimepicker_end').datetimepicker({
  format: 'unixtime'
});<commit_msg>correct indentation<commit_after>$('form').one("submit", function(event) {
  event.preventDefault();

  var send = $(this).serialize()

  $.ajax({
    type: 'GET',
    url: './download.php',
    data: send,
    dataType: 'json',
    success: function(obj) {
      var value = obj[0];

        $("ul").append("
" + "Demand for power is " + value.demand + "GW" + "
");
        $("ul").append("
" + "Wind Power supplies " + value.wind + "GW" + "
");
        $("ul").append("
" + "Wind Power accounts for around " + ((value.wind / value.demand) * 100).toFixed(2) + "%" + " of the total Energy Supply" + "
");

        var wind = ((value.wind / value.demand) * 100).toFixed(2); // need this to be the output of our JSON func, ((value.wind / value.demand) * 100).toFixed(2)

        if (wind <= 3) {
          $('.rotor').css('-webkit-animation', 'rotate 40s infinite linear');
        }
        else if (wind > 3 && wind <= 8) {
          $('.rotor').css('-webkit-animation', 'rotate 20s infinite linear');
        }
        else {
          $('.rotor').css('-webkit-animation', 'rotate 2s infinite linear');
        }
      },
    error: function() {
      alert('Error');
    }
  });
});

$('#datetimepicker_start').datetimepicker({
  format: 'unixtime'
});
$('#datetimepicker_end').datetimepicker({
  format: 'unixtime'
});<|endoftext|>


<commit_before>import React from 'react';

import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { object, select, number, text, boolean } from '@storybook/addon-knobs';
import { MuiThemeProvider } from 'material-ui';
import injectTapEventPlugin from 'react-tap-event-plugin';

import { Image, ImagePreviewer } from '../../src';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

const createUploadImage = ({
  log = action('upload image'),
  printable,
  willFail,
  delay = 1000,
} = {}) => {
  const succeed = url => new Promise((resolve) => {
    log(url);
    setTimeout(() => resolve({ url }), delay);
  });

  const fail = url => new Promise((resolve, reject) => {
    log(url);
    setTimeout(() => reject(new Error('failed')), delay);
  });

  const uploadImage = willFail ? fail : succeed;
  if (printable) {
    Object.defineProperty(uploadImage, 'name', { value: uploadImage.toString() });
  }
  return uploadImage;
};

const url = 'https://unsplash.it/500/500';
const image = { preview: url };

const stories = storiesOf('Image', module)
  .addDecorator(story => <MuiThemeProvider>{story()}</MuiThemeProvider>);

const description = 'Control point to start from with knobs panel';
stories.addWithInfo('presets', description, () => {
  const startFrom = select('start-from', ['upload', 'cropping', 'preview'], 'upload');
  return (

{`Start from ${startFrom}`}

      <Image
        image={startFrom === 'cropping' ? image : undefined}
        url={startFrom === 'preview' ? url : undefined}
        uploadImage={createUploadImage({
          printable: true,
          willFail: boolean('will fail', false),
          delay: number('delay', 1000),
        })}
        selectActionLabel={text('selectActionLabel', 'Select')}
        changeActionLabel={text('changeActionLabel', 'New')}
        cropActionLabel={text('cropActionLabel', 'Edit')}
        resetActionLabel={text('resetActionLabel', 'Clear')}
        retryActionLabel={text('retryActionLabel', 'Retry')}
        uploadActionLabel={text('uploadActionLabel', 'Submit')}
      />

  );
}, { inline: true });

stories.add('events', () => (
  <Image
    uploadImage={createUploadImage({
      willFail: boolean('will fail', true),
      log: dataURL => action('upload image size')(dataURL.length),
    })}
    onUploadSucceed={({ url: dataURL }) => action('upload succeed size')(dataURL.length)}
    onUploadFail={error => action('upload fail')(error.message)}
    onSetImage={file => action('select size')(file.size)}
  />
));

stories.add('initialState', () => (
  <Image
    uploadImage={createUploadImage()}
    initialState={object('initialState', {
      image,
      uploading: true,
    })}
  />
));

stories.addWithInfo('ImagePreviewer', '', () => {
  const src1 = text('src1', url);
  const src2 = text('src2', 'https://unsplash.it/600/600');
  const style = {
    width: number('width', 300),
    height: number('height', 300),
  };

  return (

      <ImagePreviewer
        src={src1}
        style={style}
        initialOpen
      />
      <ImagePreviewer
        src={src2}
        style={style}
      />

  );
}, { inline: false });
<commit_msg>fixStory(Image): withInfo instead of addWithInfo<commit_after>import React from 'react';

import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { object, select, number, text, boolean } from '@storybook/addon-knobs';
import { withInfo } from '@storybook/addon-info';
import { MuiThemeProvider } from 'material-ui';
import injectTapEventPlugin from 'react-tap-event-plugin';

import { Image, ImagePreviewer } from '../../src';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

const createUploadImage = ({
  log = action('upload image'),
  printable,
  willFail,
  delay = 1000,
} = {}) => {
  const succeed = url => new Promise((resolve) => {
    log(url);
    setTimeout(() => resolve({ url }), delay);
  });

  const fail = url => new Promise((resolve, reject) => {
    log(url);
    setTimeout(() => reject(new Error('failed')), delay);
  });

  const uploadImage = willFail ? fail : succeed;
  if (printable) {
    Object.defineProperty(uploadImage, 'name', { value: uploadImage.toString() });
  }
  return uploadImage;
};

const url = 'https://unsplash.it/500/500';
const image = { preview: url };

const stories = storiesOf('Image', module)
  .addDecorator(story => <MuiThemeProvider>{story()}</MuiThemeProvider>);

const description = 'Control point to start from with knobs panel';
stories.add('presets', withInfo({
  text: description,
  inline: true,
})(() => {
  const startFrom = select('start-from', ['upload', 'cropping', 'preview'], 'upload');
  return (

{`Start from ${startFrom}`}

      <Image
        image={startFrom === 'cropping' ? image : undefined}
        url={startFrom === 'preview' ? url : undefined}
        uploadImage={createUploadImage({
          printable: true,
          willFail: boolean('will fail', false),
          delay: number('delay', 1000),
        })}
        selectActionLabel={text('selectActionLabel', 'Select')}
        changeActionLabel={text('changeActionLabel', 'New')}
        cropActionLabel={text('cropActionLabel', 'Edit')}
        resetActionLabel={text('resetActionLabel', 'Clear')}
        retryActionLabel={text('retryActionLabel', 'Retry')}
        uploadActionLabel={text('uploadActionLabel', 'Submit')}
      />

  );
}));

stories.add('events', () => (
  <Image
    uploadImage={createUploadImage({
      willFail: boolean('will fail', true),
      log: dataURL => action('upload image size')(dataURL.length),
    })}
    onUploadSucceed={({ url: dataURL }) => action('upload succeed size')(dataURL.length)}
    onUploadFail={error => action('upload fail')(error.message)}
    onSetImage={file => action('select size')(file.size)}
  />
));

stories.add('initialState', () => (
  <Image
    uploadImage={createUploadImage()}
    initialState={object('initialState', {
      image,
      uploading: true,
    })}
  />
));

stories.add('ImagePreviewer', withInfo({
  inline: false,
})(() => {
  const src1 = text('src1', url);
  const src2 = text('src2', 'https://unsplash.it/600/600');
  const style = {
    width: number('width', 300),
    height: number('height', 300),
  };

  return (

      <ImagePreviewer
        src={src1}
        style={style}
        initialOpen
      />
      <ImagePreviewer
        src={src2}
        style={style}
      />

  );
}));
<|endoftext|>


<commit_before>/*
Theme: Flatfy Theme
Author: Andrea Galanti
Bootstrap Version
Build: 1.0
http://www.andreagalanti.it
*/

$(window).load(function() {
	//Preloader
	$('#status').delay(300).fadeOut();
	$('#preloader').delay(300).fadeOut('slow');
	$('body').delay(550).css({'overflow':'visible'});
})

$(document).ready(function() {
		//animated logo
		$(".navbar-brand").hover(function () {
			$(this).toggleClass("animated shake");
		});

		//animated scroll_arrow
		$(".img_scroll").hover(function () {
			$(this).toggleClass("animated infinite bounce");
		});

		//Wow Animation DISABLE FOR ANIMATION MOBILE/TABLET
		wow = new WOW(
		{
			mobile: false
		});
		wow.init();

		//MagnificPopup
		$('.image-link').magnificPopup({type:'image'});

		// OwlCarousel N1
		$("#owl-demo").owlCarousel({
			autoPlay: 3000,
			items : 3,
			itemsDesktop : [1199,3],
			itemsDesktopSmall : [979,3]
		});

		// OwlCarousel N2
		$("#owl-demo-1").owlCarousel({
			  navigation : false, // Show next and prev buttons
			  slideSpeed : 300,
			  paginationSpeed : 400,
			  singleItem:true
		});

		//SmothScroll
		$('a[href*=#]').click(function() {
			if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
			&& location.hostname == this.hostname) {
					var $target = $(this.hash);
					$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
					if ($target.length) {
							var targetOffset = $target.offset().top;
							$('html,body').animate({scrollTop: targetOffset}, 600);
							return false;
					}
			}
		});

		//Subscribe
		new UIMorphingButton( document.querySelector( '.morph-button' ) );
		// for demo purposes only
		[].slice.call( document.querySelectorAll( 'form button' ) ).forEach( function( bttn ) {
			bttn.addEventListener( 'click', function( ev ) { ev.preventDefault(); } );
		} );

});

<commit_msg>Fix Syntax error<commit_after>/*
Theme: Flatfy Theme
Author: Andrea Galanti
Bootstrap Version
Build: 1.0
http://www.andreagalanti.it
*/

$(window).load(function() {
	//Preloader
	$('#status').delay(300).fadeOut();
	$('#preloader').delay(300).fadeOut('slow');
	$('body').delay(550).css({'overflow':'visible'});
})

$(document).ready(function() {
		//animated logo
		$(".navbar-brand").hover(function () {
			$(this).toggleClass("animated shake");
		});

		//animated scroll_arrow
		$(".img_scroll").hover(function () {
			$(this).toggleClass("animated infinite bounce");
		});

		//Wow Animation DISABLE FOR ANIMATION MOBILE/TABLET
		wow = new WOW(
		{
			mobile: false
		});
		wow.init();

		//MagnificPopup
		$('.image-link').magnificPopup({type:'image'});

		// OwlCarousel N1
		$("#owl-demo").owlCarousel({
			autoPlay: 3000,
			items : 3,
			itemsDesktop : [1199,3],
			itemsDesktopSmall : [979,3]
		});

		// OwlCarousel N2
		$("#owl-demo-1").owlCarousel({
			  navigation : false, // Show next and prev buttons
			  slideSpeed : 300,
			  paginationSpeed : 400,
			  singleItem:true
		});

		//SmothScroll
		$('a[href*=\\#]').click(function() {
			if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
			&& location.hostname == this.hostname) {
					var $target = $(this.hash);
					$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
					if ($target.length) {
							var targetOffset = $target.offset().top;
							$('html,body').animate({scrollTop: targetOffset}, 600);
							return false;
					}
			}
		});

		//Subscribe
		new UIMorphingButton( document.querySelector( '.morph-button' ) );
		// for demo purposes only
		[].slice.call( document.querySelectorAll( 'form button' ) ).forEach( function( bttn ) {
			bttn.addEventListener( 'click', function( ev ) { ev.preventDefault(); } );
		} );

});

<|endoftext|>


<commit_before>/* Try to reload the image with a 3 second interval, max 3 times.
Do this by replacing the image source. */
jQuery(document).ready(function() {
    $retries = 3;
    jQuery('.field-items .field-item img, div > div > div > div > p > img').error(function() {
        $img = jQuery(this);
        setTimeout(function() {
            $img.attr('src', $img.attr('src'));
        }, 3000);
        $retries--;

        if($retries <= 0) {
            $img.unbind('error');
        }
    });
});
<commit_msg>preview selector<commit_after>/* Try to reload the image with a 3 second interval, max 3 times.
Do this by replacing the image source. */
jQuery(document).ready(function() {
    $retries = 5;
    jQuery('.field-items .field-item img').error(function() {
        $img = jQuery(this);
        reloadImage($img);
    });

    jQuery("iframe").contents().find('div.preview img').error(function() {
        $img = jQuery(this);
        reloadImage($img);
    });

    jQuery("iframe").contents().find('iframe').contents().find('body[contenteditable] img').error(function() {
        $img = jQuery(this);
        reloadImage($img);
    });

    function reloadImage($img) {
        setTimeout(function() {
            $img.attr('src', $img.attr('src'));
        }, 3000);
        $retries--;

        if($retries <= 0) {
            $img.unbind('error');
        }
    }
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes",
  "Merging in private branch",
  "Time machines are real man!"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 10% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.1;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(<commit_msg>Reverting changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes",
  "Merging in private branch",
  "Time machines are real man!"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 10% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.1;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return<|endoftext|>


<commit_before>var stream = require('stream')
var cadence = require('cadence')
var delta = require('delta')
var Destructible = require('destructible')
var interrupt = require('interrupt').createInterrupter('staccato')

function Staccato (stream, opening) {
    this.stream = stream
    this._destructible = new Destructible(interrupt)
    this._listeners = {
        open: this._open.bind(this),
        error: this.destroy.bind(this)
    }
    this._destructible.markDestroyed(this)
    this._delta = null
    this._readable = false
    if (opening) {
        this._destructible.addDestructor('open', this, '_open')
    } else {
        this._open()
    }
    this.stream.once('error', this._listeners.error)
    this._destructible.addDestructor('error', this, '_uncatch')
    this.destroyed = false
}

Staccato.prototype._open = function () {
    this.stream.removeListener('open', this._listeners.open)
    this._opened = true
}

Staccato.prototype._uncatch = function () {
    this.stream.removeListener('error', this._listeners.error)
}

Staccato.prototype._cancel = function () {
    if (this._delta != null) {
        this._delta.cancel([])
        this._delta = null
    }
}

Staccato.prototype.destroy = function () {
    this._destructible.destroy()
}

Staccato.prototype.ready = cadence(function (async) {
    interrupt.assert(!this.destroyed, 'destroyed')
    if (!this._opened) {
        async(function () {
            this._destructible.invokeDestructor('open')
            this._destructible.invokeDestructor('error')
            this._destructible.addDestructor('delta', this, '_cancel')
            this._delta = delta(async()).ee(this.stream).on('open')
        }, function () {
            this._delta = null
            this._destructible.invokeDestructor('delta')
            this.stream.once('error', this._listeners.error)
            this._destructible.addDestructor('error', this, '_uncatch')
        })
    }
})

module.exports = Staccato
<commit_msg>Create Staccato with string key.<commit_after>var stream = require('stream')
var cadence = require('cadence')
var delta = require('delta')
var Destructible = require('destructible')
var interrupt = require('interrupt').createInterrupter('staccato')

function Staccato (stream, opening) {
    this.stream = stream
    this._destructible = new Destructible('staccato')
    this._listeners = {
        open: this._open.bind(this),
        error: this.destroy.bind(this)
    }
    this._destructible.markDestroyed(this)
    this._delta = null
    this._readable = false
    if (opening) {
        this._destructible.addDestructor('open', this, '_open')
    } else {
        this._open()
    }
    this.stream.once('error', this._listeners.error)
    this._destructible.addDestructor('error', this, '_uncatch')
    this.destroyed = false
}

Staccato.prototype._open = function () {
    this.stream.removeListener('open', this._listeners.open)
    this._opened = true
}

Staccato.prototype._uncatch = function () {
    this.stream.removeListener('error', this._listeners.error)
}

Staccato.prototype._cancel = function () {
    if (this._delta != null) {
        this._delta.cancel([])
        this._delta = null
    }
}

Staccato.prototype.destroy = function () {
    this._destructible.destroy()
}

Staccato.prototype.ready = cadence(function (async) {
    interrupt.assert(!this.destroyed, 'destroyed')
    if (!this._opened) {
        async(function () {
            this._destructible.invokeDestructor('open')
            this._destructible.invokeDestructor('error')
            this._destructible.addDestructor('delta', this, '_cancel')
            this._delta = delta(async()).ee(this.stream).on('open')
        }, function () {
            this._delta = null
            this._destructible.invokeDestructor('delta')
            this.stream.once('error', this._listeners.error)
            this._destructible.addDestructor('error', this, '_uncatch')
        })
    }
})

module.exports = Staccato
<|endoftext|>


<commit_before>/*!
 * @author:    Divio AG
 * @copyright: http://www.divio.ch
 */

'use strict';

// #####################################################################################################################
// #IMPORTS#
var browserSync = require('browser-sync');
var cache = require('gulp-cached');
var gulp = require('gulp');
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var karma = require('karma').server;
var scsslint = require('gulp-scss-lint');
var yuidoc = require('gulp-yuidoc');

// #####################################################################################################################
// #SETTINGS#
var paths = {
    'css': './site/static/css/',
    'html': './site/templates/',
    'images': './site/static/img/',
    'js': './site/static/js/',
    'sass': './site/private/sass/',
    'docs': './site/static/docs',
    'tests': './site/tests'
};

var patterns = {
    'images': [
        paths.images + '*',
        paths.images + '**/*',
        '!' + paths.images + 'dummy/*/**'
    ],
    'js': [
        paths.js + '*.js',
        paths.js + '**/*.js',
        paths.tests + '*.js',
        '!' + paths.js + '*.min.js',
        '!' + paths.js + '**/*.min.js'
    ],
    'sass': [
        paths.sass + '*',
        paths.sass + '**/*',
        '!' + paths.sass + 'libs/*.scss',
        '!' + paths.sass + 'settings/*.scss',
        '!' + paths.sass + 'layout/_print.scss'
    ]
};
patterns.jshint = patterns.js.concat(['!' + paths.js + 'libs/*.js', './gulpfile.js']);

var port = parseInt(process.env.PORT, 10) || 8000;

// #####################################################################################################################
// #LINTING#
gulp.task('lint', ['jslint', 'scsslint']);

gulp.task('jslint', function () {
    gulp.src(patterns.jshint)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('scsslint', function () {
    // DOCS: https://github.com/brigade/scss-lint/
    gulp.src(patterns.sass)
        .pipe(cache('scsslint'))
        .pipe(scsslint({
            'config': './scss-lint.json'
        }));
    // FIXME: tests currently pass even if there is a linting error, the reporter stops all remaining issues :(
    // .pipe(scsslint.failReporter());
});

// #########################################################
// #PREPROCESSING#
gulp.task('preprocess', ['images', 'docs']);

gulp.task('images', function () {
    var options = {
        'interlaced': true,
        'optimizationLevel': 5,
        'progressive': true
    };

    gulp.src(patterns.images)
        .pipe(cache(imagemin(options)))
        .pipe(gulp.dest(paths.images)).on('error', function (error) {
            gutil.log('\n' + error.message);
        });
});

gulp.task('docs', function () {
    gulp.src(patterns.js)
        .pipe(yuidoc())
        .pipe(gulp.dest(paths.docs));
});

// #########################################################
// #SERVICES#
gulp.task('browser', function () {
    var files = [
        paths.css + '*.css',
        paths.html + '**/*.html',
        paths.js + '**/*.js'
    ];

    // DOCS: http://www.browsersync.io/docs/options/
    setTimeout(function () {
        browserSync.init(files, {
            'proxy': '0.0.0.0:' + port,
            'port': port + 1,
            'ui': {
                'port': port + 2
            }
        });
    }, 1000);
});

// #########################################################
// #TESTS#
gulp.task('tests', ['lint'], function () {
    // run javascript tests
    karma.start({
        'configFile': __dirname + '/.site/tests/karma.conf.js',
        'singleRun': true
    });
});

gulp.task('karma', function () {
    // run javascript tests
    karma.start({
        'configFile': __dirname + '/.site/tests/karma.conf.js'
    });
});

// #####################################################################################################################
// #COMMANDS#
gulp.task('watch', function () {
    gulp.watch(patterns.jshint, ['lint']);
});

gulp.task('default', ['lint', 'browser', 'watch']);
<commit_msg>disable browser on default call<commit_after>/*!
 * @author:    Divio AG
 * @copyright: http://www.divio.ch
 */

'use strict';

// #####################################################################################################################
// #IMPORTS#
var browserSync = require('browser-sync');
var cache = require('gulp-cached');
var gulp = require('gulp');
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var karma = require('karma').server;
var scsslint = require('gulp-scss-lint');
var yuidoc = require('gulp-yuidoc');

// #####################################################################################################################
// #SETTINGS#
var paths = {
    'css': './site/static/css/',
    'html': './site/templates/',
    'images': './site/static/img/',
    'js': './site/static/js/',
    'sass': './site/private/sass/',
    'docs': './site/static/docs',
    'tests': './site/tests'
};

var patterns = {
    'images': [
        paths.images + '*',
        paths.images + '**/*',
        '!' + paths.images + 'dummy/*/**'
    ],
    'js': [
        paths.js + '*.js',
        paths.js + '**/*.js',
        paths.tests + '*.js',
        '!' + paths.js + '*.min.js',
        '!' + paths.js + '**/*.min.js'
    ],
    'sass': [
        paths.sass + '*',
        paths.sass + '**/*',
        '!' + paths.sass + 'libs/*.scss',
        '!' + paths.sass + 'settings/*.scss',
        '!' + paths.sass + 'layout/_print.scss'
    ]
};
patterns.jshint = patterns.js.concat(['!' + paths.js + 'libs/*.js', './gulpfile.js']);

var port = parseInt(process.env.PORT, 10) || 8000;

// #####################################################################################################################
// #LINTING#
gulp.task('lint', ['jslint', 'scsslint']);

gulp.task('jslint', function () {
    gulp.src(patterns.jshint)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('scsslint', function () {
    // DOCS: https://github.com/brigade/scss-lint/
    gulp.src(patterns.sass)
        .pipe(cache('scsslint'))
        .pipe(scsslint({
            'config': './scss-lint.json'
        }));
    // FIXME: tests currently pass even if there is a linting error, the reporter stops all remaining issues :(
    // .pipe(scsslint.failReporter());
});

// #########################################################
// #PREPROCESSING#
gulp.task('preprocess', ['images', 'docs']);

gulp.task('images', function () {
    var options = {
        'interlaced': true,
        'optimizationLevel': 5,
        'progressive': true
    };

    gulp.src(patterns.images)
        .pipe(cache(imagemin(options)))
        .pipe(gulp.dest(paths.images)).on('error', function (error) {
            gutil.log('\n' + error.message);
        });
});

gulp.task('docs', function () {
    gulp.src(patterns.js)
        .pipe(yuidoc())
        .pipe(gulp.dest(paths.docs));
});

// #########################################################
// #SERVICES#
gulp.task('browser', function () {
    var files = [
        paths.css + '*.css',
        paths.html + '**/*.html',
        paths.js + '**/*.js'
    ];

    // DOCS: http://www.browsersync.io/docs/options/
    setTimeout(function () {
        browserSync.init(files, {
            'proxy': '0.0.0.0:' + port,
            'port': port + 1,
            'ui': {
                'port': port + 2
            }
        });
    }, 1000);
});

// #########################################################
// #TESTS#
gulp.task('tests', ['lint'], function () {
    // run javascript tests
    karma.start({
        'configFile': __dirname + '/.site/tests/karma.conf.js',
        'singleRun': true
    });
});

gulp.task('karma', function () {
    // run javascript tests
    karma.start({
        'configFile': __dirname + '/.site/tests/karma.conf.js'
    });
});

// #####################################################################################################################
// #COMMANDS#
gulp.task('watch', function () {
    gulp.watch(patterns.jshint, ['lint']);
});

gulp.task('default', ['lint', 'watch']);
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
// import { linkTo } from '@storybook/addon-links';
import { Components } from 'meteor/vulcan:core';
import 'meteor/vulcan:forms';
import { withKnobs, boolean, text } from '@storybook/addon-knobs';

const vulcan_forms = storiesOf('Core/Forms/CoreComponents', module);
vulcan_forms.addDecorator(withKnobs);

vulcan_forms
  .add('FormError - message', () => (
    <Components.FormError
      error={{
        message: 'An error message',
      }}
    />
  ))
  .add('FormError intl - no properties', () => (
    <Components.FormError
      error={{
        id: 'intl-id',
      }}
    />
  ))
  .add('FormError intl', () => (
    <Components.FormError
      error={{
        id: 'intl-id',
        properties: {
          name: 'address.street',
        },
      }}
    />
  ));

vulcan_forms
  .add('FormGroupHeader', () => {
    const label = text('Header label', 'myLabel');
    const collapsed = boolean('collapsed', false);
    const hidden = boolean('hidden', false);
    const hasErrors = boolean('hasErrors', false);
    const textInside = text('Text inside', 'My text inside');
    const groupName = text('Group name', 'admin');
    const collapsible = boolean('collapsible', true);
    const group = { name: [groupName], collapsible: collapsible };
    return (

        <Components.FormGroupHeader label={label} group={group} />
        <Components.FormGroupLayout
          label="labelInner"
          anchorName="anchorNameInner"
          collapsed={collapsed}
          hidden={hidden}
          hasErrors={hasErrors}
          group={group}>
          {textInside}
        </Components.FormGroupLayout>

    );
  })
  .add('FormGroupLine', () => {
    const label = text('Header label', 'myLabel');
    const collapsed = boolean('collapsed', false);
    const hidden = boolean('hidden', false);
    const hasErrors = boolean('hasErrors', false);
    const textInside = text('Text inside', 'My text inside');
    const groupName = text('Group name', 'admin');
    const collapsible = boolean('collapsible', true);
    const group = { name: [groupName], collapsible: collapsible };
    return (

        <Components.FormGroupHeaderLine label={label} group={group} />
        <Components.FormGroupLayoutLine
          label="labelInner"
          anchorName="anchorNameInner"
          collapsed={collapsed}
          hidden={hidden}
          hasErrors={hasErrors}
          group={group}>
          {textInside}
        </Components.FormGroupLayoutLine>

    );
  })
  .add('FormGroupNone', () => {
    const collapsed = boolean('collapsed', false);
    const hidden = boolean('hidden', false);
    const hasErrors = boolean('hasErrors', false);
    const textInside = text('Text inside', 'My text inside');
    const groupName = text('Group name', 'admin');
    const collapsible = boolean('collapsible', true);
    const group = { name: [groupName], collapsible: collapsible };
    return (

        <Components.FormGroupHeaderNone />
        <Components.FormGroupLayoutNone
          label="labelInner"
          anchorName="anchorNameInner"
          collapsed={collapsed}
          hidden={hidden}
          hasErrors={hasErrors}
          group={group}>
          {textInside}
        </Components.FormGroupLayoutNone>

    );
  });

vulcan_forms.add('FormNestedArrayLayout - nested item before/after components', () => (
  <Components.FormNestedArray
    value={[{ name: 'Jane' }, { name: 'DELETED' }, { name: 'John' }]}
    deletedValues={['peoples.1']}
    path="peoples"
    formComponents={{
      ...Components,
      FormNestedItem: () => (

          <input />

      ),
    }}
    errors={[]}
    updateCurrentValues={action('updateCurrentValues')}
    arrayField={{
      beforeComponent: props => (

          BEFORE {props.itemIndex} {props.visibleItemIndex}

      ),
      afterComponent: props =>
AFTER
,
    }}
  />
));
<commit_msg>add story of FormSubmit<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
// import { linkTo } from '@storybook/addon-links';
import { Components } from 'meteor/vulcan:core';
import 'meteor/vulcan:forms';
import { withKnobs, boolean, text } from '@storybook/addon-knobs';

const vulcanForms = storiesOf('Core/Forms/CoreComponents', module);
vulcanForms.addDecorator(withKnobs);

vulcanForms
  .add('FormError - message', () => (
    <Components.FormError
      error={{
        message: 'An error message',
      }}
    />
  ))
  .add('FormError intl - no properties', () => (
    <Components.FormError
      error={{
        id: 'intl-id',
      }}
    />
  ))
  .add('FormError intl', () => (
    <Components.FormError
      error={{
        id: 'intl-id',
        properties: {
          name: 'address.street',
        },
      }}
    />
  ));

vulcanForms
  .add('FormGroupHeader', () => {
    const label = text('Header label', 'myLabel');
    const collapsed = boolean('collapsed', false);
    const hidden = boolean('hidden', false);
    const hasErrors = boolean('hasErrors', false);
    const textInside = text('Text inside', 'My text inside');
    const groupName = text('Group name', 'admin');
    const collapsible = boolean('collapsible', true);
    const group = { name: [groupName], collapsible: collapsible };
    return (

        <Components.FormGroupHeader label={label} group={group} />
        <Components.FormGroupLayout
          label="labelInner"
          anchorName="anchorNameInner"
          collapsed={collapsed}
          hidden={hidden}
          hasErrors={hasErrors}
          group={group}>
          {textInside}
        </Components.FormGroupLayout>

    );
  })
  .add('FormGroupLine', () => {
    const label = text('Header label', 'myLabel');
    const collapsed = boolean('collapsed', false);
    const hidden = boolean('hidden', false);
    const hasErrors = boolean('hasErrors', false);
    const textInside = text('Text inside', 'My text inside');
    const groupName = text('Group name', 'admin');
    const collapsible = boolean('collapsible', true);
    const group = { name: [groupName], collapsible: collapsible };
    return (

        <Components.FormGroupHeaderLine label={label} group={group} />
        <Components.FormGroupLayoutLine
          label="labelInner"
          anchorName="anchorNameInner"
          collapsed={collapsed}
          hidden={hidden}
          hasErrors={hasErrors}
          group={group}>
          {textInside}
        </Components.FormGroupLayoutLine>

    );
  })
  .add('FormGroupNone', () => {
    const collapsed = boolean('collapsed', false);
    const hidden = boolean('hidden', false);
    const hasErrors = boolean('hasErrors', false);
    const textInside = text('Text inside', 'My text inside');
    const groupName = text('Group name', 'admin');
    const collapsible = boolean('collapsible', true);
    const group = { name: [groupName], collapsible: collapsible };
    return (

        <Components.FormGroupHeaderNone />
        <Components.FormGroupLayoutNone
          label="labelInner"
          anchorName="anchorNameInner"
          collapsed={collapsed}
          hidden={hidden}
          hasErrors={hasErrors}
          group={group}>
          {textInside}
        </Components.FormGroupLayoutNone>

    );
  });

vulcanForms.add('FormNestedArrayLayout - nested item before/after components', () => (
  <Components.FormNestedArray
    value={[{ name: 'Jane' }, { name: 'DELETED' }, { name: 'John' }]}
    deletedValues={['peoples.1']}
    path="peoples"
    formComponents={{
      ...Components,
      FormNestedItem: () => (

          <input />

      ),
    }}
    errors={[]}
    updateCurrentValues={action('updateCurrentValues')}
    arrayField={{
      beforeComponent: props => (

          BEFORE {props.itemIndex} {props.visibleItemIndex}

      ),
      afterComponent: props =>
AFTER
,
    }}
  />
));

vulcanForms.add('FormSubmit', () => {
  const submitLabel = text('Submit Label', 'Submit Label');
  return <Components.FormSubmit submitLabel={submitLabel} />;
});
<|endoftext|>