<commit_before>'use strict';

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

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

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

module.exports = class bit2c extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bit2c',
            'name': 'Bit2C',
            'countries': [ 'IL' ], // Israel
            'rateLimit': 3000,
            'has': {
                'CORS': false,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766119-3593220e-5ece-11e7-8b3a-5a041f6bcc3f.jpg',
                'api': 'https://bit2c.co.il',
                'www': 'https://www.bit2c.co.il',
                'doc': [
                    'https://www.bit2c.co.il/home/api',
                    'https://github.com/OferE/bit2c',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        'Exchanges/{pair}/Ticker',
                        'Exchanges/{pair}/orderbook',
                        'Exchanges/{pair}/trades',
                        'Exchanges/{pair}/lasttrades',
                    ],
                },
                'private': {
                    'post': [
                        'Merchant/CreateCheckout',
                        'Order/AddCoinFundsRequest',
                        'Order/AddFund',
                        'Order/AddOrder',
                        'Order/AddOrderMarketPriceBuy',
                        'Order/AddOrderMarketPriceSell',
                        'Order/CancelOrder',
                        'Order/AddCoinFundsRequest',
                        'Order/AddStopOrder',
                        'Payment/GetMyId',
                        'Payment/Send',
                        'Payment/Pay',
                    ],
                    'get': [
                        'Account/Balance',
                        'Account/Balance/v2',
                        'Order/MyOrders',
                        'Order/GetById',
                        'Order/AccountHistory',
                        'Order/OrderHistory',
                    ],
                },
            },
            'markets': {
                'BTC/NIS': { 'id': 'BtcNis', 'symbol': 'BTC/NIS', 'base': 'BTC', 'quote': 'NIS' },
                'BCH/NIS': { 'id': 'BchNis', 'symbol': 'BCH/NIS', 'base': 'BCH', 'quote': 'NIS' },
                'LTC/NIS': { 'id': 'LtcNis', 'symbol': 'LTC/NIS', 'base': 'LTC', 'quote': 'NIS' },
                'BTG/NIS': { 'id': 'BtgNis', 'symbol': 'BTG/NIS', 'base': 'BTG', 'quote': 'NIS' },
            },
            'fees': {
                'trading': {
                    'maker': 0.5 / 100,
                    'taker': 0.5 / 100,
                },
            },
        });
    }

    async fetchBalance (params = {}) {
        let balance = await this.privateGetAccountBalanceV2 ();
        let result = { 'info': balance };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let account = this.account ();
            if (currency in balance) {
                let available = 'AVAILABLE_' + currency;
                account['free'] = balance[available];
                account['total'] = balance[currency];
                account['used'] = account['total'] - account['free'];
            }
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        let orderbook = await this.publicGetExchangesPairOrderbook (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (orderbook);
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetExchangesPairTicker (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        let timestamp = this.milliseconds ();
        let averagePrice = this.safeFloat (ticker, 'av');
        let baseVolume = this.safeFloat (ticker, 'a');
        let quoteVolume = baseVolume * averagePrice;
        let last = this.safeFloat (ticker, 'll');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': this.safeFloat (ticker, 'h'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'l'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': averagePrice,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        };
    }

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

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let method = 'privatePostOrderAddOrder';
        let order = {
            'Amount': amount,
            'Pair': this.marketId (symbol),
        };
        if (type === 'market') {
            method += 'MarketPrice' + this.capitalize (side);
        } else {
            order['Price'] = price;
            order['Total'] = amount * price;
            order['IsBid'] = (side === 'buy');
        }
        let result = await this[method] (this.extend (order, params));
        return {
            'info': result,
            'id': result['NewOrder']['id'],
        };
    }

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

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.implodeParams (path, params);
        if (api === 'public') {
            // lasttrades is the only endpoint that doesn't require the .json extension/suffix
            if (path.indexOf ('lasttrades') < 0) {
                url += '.json';
            }
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            let query = this.extend ({ 'nonce': nonce }, params);
            body = this.urlencode (query);
            let signature = this.hmac (this.encode (body), this.encode (this.secret), 'sha512', 'base64');
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'key': this.apiKey,
                'sign': this.decode (signature),
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        if (typeof symbol === 'undefined')
            throw new ExchangeError (this.id + ' fetchOpenOrders() requires a symbol argument');
        let market = this.market (symbol);
        let response = await this.privateGetOrderMyOrders (this.extend ({
            'pair': market['id'],
        }, params));
        let orders = this.safeValue (response, market['id'], {});
        let asks = this.safeValue (orders, 'ask');
        let bids = this.safeValue (orders, 'bid');
        return this.parseOrders (this.arrayConcat (asks, bids), market, since, limit);
    }

    parseOrder (order, market = undefined) {
        let timestamp = order['created'];
        let price = order['price'];
        let amount = order['amount'];
        let cost = price * amount;
        let symbol = undefined;
        if (typeof market !== 'undefined')
            symbol = market['symbol'];
        let side = this.safeValue (order, 'type');
        if (side === 0) {
            side = 'buy';
        } else if (side === 1) {
            side = 'sell';
        }
        let id = this.safeString (order, 'id');
        let status = this.safeString (order, 'status');
        return {
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'lastTradeTimestamp': undefined,
            'status': status,
            'symbol': symbol,
            'type': undefined,
            'side': side,
            'price': price,
            'amount': amount,
            'filled': undefined,
            'remaining': undefined,
            'cost': cost,
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = undefined;
        let method = 'privateGetOrderOrderhistory';
        let request = {};
        if (typeof limit !== 'undefined')
            request['take'] = limit;
        request['take'] = limit;
        if (typeof since !== 'undefined') {
            request['toTime'] = this.ymd (this.milliseconds (), '.');
            request['fromTime'] = this.ymd (since, '.');
        }
        if (typeof symbol !== 'undefined') {
            market = this.market (symbol);
            request['pair'] = market['id'];
        }
        let response = await this[method] (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = undefined;
        let id = undefined;
        let price = undefined;
        let amount = undefined;
        let orderId = undefined;
        let feeCost = undefined;
        let side = undefined;
        let reference = this.safeString (trade, 'reference');
        if (typeof reference !== 'undefined') {
            timestamp = this.safeInteger (trade, 'ticks') * 1000;
            price = this.safeFloat (trade, 'price');
            amount = this.safeFloat (trade, 'firstAmount');
            let reference_parts = reference.split ('|'); // reference contains: 'pair|orderId|tradeId'
            if (typeof market === 'undefined') {
                let marketId = this.safeString (trade, 'pair');
                if (marketId in this.markets_by_id[marketId]) {
                    market = this.markets_by_id[marketId];
                } else if (reference_parts[0] in this.markets_by_id) {
                    market = this.markets_by_id[reference_parts[0]];
                }
            }
            orderId = reference_parts[1];
            id = reference_parts[2];
            side = this.safeInteger (trade, 'action');
            if (side === 0) {
                side = 'buy';
            } else if (side === 1) {
                side = 'sell';
            }
            feeCost = this.safeFloat (trade, 'feeAmount');
        } else {
            timestamp = this.safeInteger (trade, 'date') * 1000;
            id = this.safeInteger (trade, 'tid');
            price = this.safeFloat (trade, 'price');
            amount = this.safeFloat (trade, 'amount');
        }
        let symbol = undefined;
        if (typeof market !== 'undefined')
            symbol = market['symbol'];
        return {
            'info': trade,
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'order': orderId,
            'type': undefined,
            'side': side,
            'takerOrMaker': undefined,
            'price': price,
            'amount': amount,
            'cost': price * amount,
            'fee': {
                'cost': feeCost,
                'currency': 'NIS',
                'rate': undefined,
            },
        };
    }
};

<commit_msg>bit2c made the trades endpoint overrideable<commit_after>'use strict';

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

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

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

module.exports = class bit2c extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bit2c',
            'name': 'Bit2C',
            'countries': [ 'IL' ], // Israel
            'rateLimit': 3000,
            'has': {
                'CORS': false,
                'fetchOpenOrders': true,
                'fetchMyTrades': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766119-3593220e-5ece-11e7-8b3a-5a041f6bcc3f.jpg',
                'api': 'https://bit2c.co.il',
                'www': 'https://www.bit2c.co.il',
                'doc': [
                    'https://www.bit2c.co.il/home/api',
                    'https://github.com/OferE/bit2c',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        'Exchanges/{pair}/Ticker',
                        'Exchanges/{pair}/orderbook',
                        'Exchanges/{pair}/trades',
                        'Exchanges/{pair}/lasttrades',
                    ],
                },
                'private': {
                    'post': [
                        'Merchant/CreateCheckout',
                        'Order/AddCoinFundsRequest',
                        'Order/AddFund',
                        'Order/AddOrder',
                        'Order/AddOrderMarketPriceBuy',
                        'Order/AddOrderMarketPriceSell',
                        'Order/CancelOrder',
                        'Order/AddCoinFundsRequest',
                        'Order/AddStopOrder',
                        'Payment/GetMyId',
                        'Payment/Send',
                        'Payment/Pay',
                    ],
                    'get': [
                        'Account/Balance',
                        'Account/Balance/v2',
                        'Order/MyOrders',
                        'Order/GetById',
                        'Order/AccountHistory',
                        'Order/OrderHistory',
                    ],
                },
            },
            'markets': {
                'BTC/NIS': { 'id': 'BtcNis', 'symbol': 'BTC/NIS', 'base': 'BTC', 'quote': 'NIS' },
                'BCH/NIS': { 'id': 'BchNis', 'symbol': 'BCH/NIS', 'base': 'BCH', 'quote': 'NIS' },
                'LTC/NIS': { 'id': 'LtcNis', 'symbol': 'LTC/NIS', 'base': 'LTC', 'quote': 'NIS' },
                'BTG/NIS': { 'id': 'BtgNis', 'symbol': 'BTG/NIS', 'base': 'BTG', 'quote': 'NIS' },
            },
            'fees': {
                'trading': {
                    'maker': 0.5 / 100,
                    'taker': 0.5 / 100,
                },
            },
            'options': {
                'fetchTradesMethod': 'public_get_exchanges_pair_lasttrades',
            },
        });
    }

    async fetchBalance (params = {}) {
        let balance = await this.privateGetAccountBalanceV2 ();
        let result = { 'info': balance };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let account = this.account ();
            if (currency in balance) {
                let available = 'AVAILABLE_' + currency;
                account['free'] = balance[available];
                account['total'] = balance[currency];
                account['used'] = account['total'] - account['free'];
            }
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        let orderbook = await this.publicGetExchangesPairOrderbook (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (orderbook);
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetExchangesPairTicker (this.extend ({
            'pair': this.marketId (symbol),
        }, params));
        let timestamp = this.milliseconds ();
        let averagePrice = this.safeFloat (ticker, 'av');
        let baseVolume = this.safeFloat (ticker, 'a');
        let quoteVolume = baseVolume * averagePrice;
        let last = this.safeFloat (ticker, 'll');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': this.safeFloat (ticker, 'h'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'l'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': averagePrice,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let method = this.options['fetchTradesMethod'];
        let response = await this[method] (this.extend ({
            'pair': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let method = 'privatePostOrderAddOrder';
        let order = {
            'Amount': amount,
            'Pair': this.marketId (symbol),
        };
        if (type === 'market') {
            method += 'MarketPrice' + this.capitalize (side);
        } else {
            order['Price'] = price;
            order['Total'] = amount * price;
            order['IsBid'] = (side === 'buy');
        }
        let result = await this[method] (this.extend (order, params));
        return {
            'info': result,
            'id': result['NewOrder']['id'],
        };
    }

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

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.implodeParams (path, params);
        if (api === 'public') {
            // lasttrades is the only endpoint that doesn't require the .json extension/suffix
            if (path.indexOf ('lasttrades') < 0) {
                url += '.json';
            }
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            let query = this.extend ({ 'nonce': nonce }, params);
            body = this.urlencode (query);
            let signature = this.hmac (this.encode (body), this.encode (this.secret), 'sha512', 'base64');
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'key': this.apiKey,
                'sign': this.decode (signature),
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        if (typeof symbol === 'undefined')
            throw new ExchangeError (this.id + ' fetchOpenOrders() requires a symbol argument');
        let market = this.market (symbol);
        let response = await this.privateGetOrderMyOrders (this.extend ({
            'pair': market['id'],
        }, params));
        let orders = this.safeValue (response, market['id'], {});
        let asks = this.safeValue (orders, 'ask');
        let bids = this.safeValue (orders, 'bid');
        return this.parseOrders (this.arrayConcat (asks, bids), market, since, limit);
    }

    parseOrder (order, market = undefined) {
        let timestamp = order['created'];
        let price = order['price'];
        let amount = order['amount'];
        let cost = price * amount;
        let symbol = undefined;
        if (typeof market !== 'undefined')
            symbol = market['symbol'];
        let side = this.safeValue (order, 'type');
        if (side === 0) {
            side = 'buy';
        } else if (side === 1) {
            side = 'sell';
        }
        let id = this.safeString (order, 'id');
        let status = this.safeString (order, 'status');
        return {
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'lastTradeTimestamp': undefined,
            'status': status,
            'symbol': symbol,
            'type': undefined,
            'side': side,
            'price': price,
            'amount': amount,
            'filled': undefined,
            'remaining': undefined,
            'cost': cost,
            'trades': undefined,
            'fee': undefined,
            'info': order,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = undefined;
        let method = 'privateGetOrderOrderhistory';
        let request = {};
        if (typeof limit !== 'undefined')
            request['take'] = limit;
        request['take'] = limit;
        if (typeof since !== 'undefined') {
            request['toTime'] = this.ymd (this.milliseconds (), '.');
            request['fromTime'] = this.ymd (since, '.');
        }
        if (typeof symbol !== 'undefined') {
            market = this.market (symbol);
            request['pair'] = market['id'];
        }
        let response = await this[method] (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = undefined;
        let id = undefined;
        let price = undefined;
        let amount = undefined;
        let orderId = undefined;
        let feeCost = undefined;
        let side = undefined;
        let reference = this.safeString (trade, 'reference');
        if (typeof reference !== 'undefined') {
            timestamp = this.safeInteger (trade, 'ticks') * 1000;
            price = this.safeFloat (trade, 'price');
            amount = this.safeFloat (trade, 'firstAmount');
            let reference_parts = reference.split ('|'); // reference contains: 'pair|orderId|tradeId'
            if (typeof market === 'undefined') {
                let marketId = this.safeString (trade, 'pair');
                if (marketId in this.markets_by_id[marketId]) {
                    market = this.markets_by_id[marketId];
                } else if (reference_parts[0] in this.markets_by_id) {
                    market = this.markets_by_id[reference_parts[0]];
                }
            }
            orderId = reference_parts[1];
            id = reference_parts[2];
            side = this.safeInteger (trade, 'action');
            if (side === 0) {
                side = 'buy';
            } else if (side === 1) {
                side = 'sell';
            }
            feeCost = this.safeFloat (trade, 'feeAmount');
        } else {
            timestamp = this.safeInteger (trade, 'date') * 1000;
            id = this.safeInteger (trade, 'tid');
            price = this.safeFloat (trade, 'price');
            amount = this.safeFloat (trade, 'amount');
        }
        let symbol = undefined;
        if (typeof market !== 'undefined')
            symbol = market['symbol'];
        return {
            'info': trade,
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'order': orderId,
            'type': undefined,
            'side': side,
            'takerOrMaker': undefined,
            'price': price,
            'amount': amount,
            'cost': price * amount,
            'fee': {
                'cost': feeCost,
                'currency': 'NIS',
                'rate': undefined,
            },
        };
    }
};

<|endoftext|>


<commit_before>/*
  All Emoncms code is released under the GNU Affero General Public License.
  See COPYRIGHT.txt and LICENSE.txt.
    ---------------------------------------------------------------------
    Part of the OpenEnergyMonitor project:
    http://openenergymonitor.org

    Author: Vikas Lamba: vikas13jun@gmail.com
    If you have any questions please get in touch, try the forums here:
    http://openenergymonitor.org/emon/forum
 */

// Convenience function for shoving things into the widget object
// I'm not sure about calling optionKey "optionKey", but I don't want to just use "options" (because that's what this whole function returns), and it's confusing enough as it is.
function addOption(widget, optionKey, optionType, optionName, optionHint, optionData){
  widget["options"    ].push(optionKey);
  widget["optionstype"].push(optionType);
  widget["optionsname"].push(optionName);
  widget["optionshint"].push(optionHint);
  widget["optionsdata"].push(optionData);
}

function sun_widgetlist(){
  var widgets =
  {
    "sun":
    {
      "offsetx":-80,"offsety":-80,"width":160,"height":160,
      "menu":"Widgets",
      "options":    [],
      "optionstype":[],
      "optionsname":[],
      "optionshint":[],
      "optionsdata":[]

    }
  };

  var decimalsDropBoxOptions = [        // Options for the type combobox. Each item is [typeID, "description"]
    [-1,   _Tr("Automatic")],
    [0,    "0"],
    [1,    "1"],
    [2,    "2"],
    [3,    "3"],
    [4,    "4"],
    [5,    "5"],
    [6,    "6"]
    ];
  var fontoptions = [
    [8, "Arial Black"],
    [7, "Arial Narrow"],
    [6, "sans-serif"],
    [5, "Helvetica"],
    [4, "Comic Sans MS"],
    [3, "Courier New"],
    [2, "Arial"],
    [1, "Georgia"],
    [0, "Impact"]
  ];
  var fstyleoptions = [
    [2, _Tr("Normal")],
    [1, _Tr("Italic")],
    [0, _Tr("Oblique")]
  ];

  var fweightoptions = [
    [0, _Tr("Normal")],
    [1, _Tr("Bold")]
  ];

  var unitEndOptions = [
    [0, _Tr("Back")],
    [1, _Tr("Front")]
  ];

  addOption(widgets["sun"],   "feedid",                "feedid",          _Tr("Feed"),          _Tr("Feed value"),                                            []);
  addOption(widgets["sun"],   "max",                   "value",           _Tr("Max value"),     _Tr("Max value to show"),                                     []);
  addOption(widgets["sun"],   "scale",                 "value",           _Tr("Scale"),         _Tr("Value is multiplied by scale before display"),           []);
  addOption(widgets["sun"],   "units",                 "dropbox_other",   _Tr("Units"),         _Tr("Units to show"),                                         _SI);
  addOption(widgets["sun"],   "unitend",               "dropbox",         _Tr("Unit position"), _Tr("Where should the unit be shown"),                        unitEndOptions);
  addOption(widgets["sun"],   "decimals",              "dropbox",         _Tr("Decimals"),      _Tr("Decimals to show"),                                      decimalsDropBoxOptions);
  addOption(widgets["sun"],   "offset",                "value",           _Tr("Offset"),        _Tr("Static offset. Subtracted from value before computing"), []);
  addOption(widgets["sun"],   "solar_title",           "value",           _Tr("solar title"),   _Tr("Solar title"),                                           []);
  addOption(widgets["sun"],   "colour",                "colour_picker",   _Tr("Colour label"),  _Tr("Color of the label"),                                    []);
  addOption(widgets["sun"],   "font",                  "dropbox",         _Tr("Font"),          _Tr("Label font"),                                            fontoptions);
  addOption(widgets["sun"],   "fstyle",                "dropbox",         _Tr("Font style"),    _Tr("Font style used for display"),                           fstyleoptions);
  addOption(widgets["sun"],   "fweight",               "dropbox",         _Tr("Font weight"),   _Tr("Font weight used for display"),                          fweightoptions);
  addOption(widgets["sun"],   "timeout",               "value",           _Tr("Timeout"),       _Tr("Timeout without feed update in seconds (empty is never)"),[]);
  addOption(widgets["sun"],   "errormessagedisplayed", "value",           _Tr("Error Message"), _Tr("Error message displayed when timeout is reached"),        []);

  return widgets;
}

function sun_init(){
  setup_widget_canvas('sun');
}

function sun_draw(){
  $('.sun').each(function(index) {
    var errorMessage = $(this).attr("errormessagedisplayed");
        if (errorMessage === "" || errorMessage === undefined){            //Error Message parameter is empty
          errorMessage = "TO Error";
        }
    var errorTimeout = $(this).attr("timeout");
        if (errorTimeout === "" || errorTimeout === undefined){            //Timeout parameter is empty
          errorTimeout = 0;
        }

    var errorCode = "0";

    var feedid = $(this).attr("feedid");
    if (assocfeed[feedid]!=undefined) feedid = assocfeed[feedid]; // convert tag:name to feedid
    if (associd[feedid] === undefined) { console.log("Review config for feed id of " + $(this).attr("class")); return; }
    var val = curve_value(feedid,dialrate).toFixed(3);

    if (errorTimeout !== 0)
      {
        if (((new Date()).getTime() / 1000 - offsetofTime - (associd[feedid]["time"] * 1)) > errorTimeout)
        {
          errorCode = "1";
        }
      }
    // ONLY UPDATE ON CHANGE
    if (val != (associd[feedid]['value'] * 1).toFixed(3) || redraw == 1 || errorTimeout != 0)
    {
      var id = "can-"+$(this).attr("id");
      var scale = 1*$(this).attr("scale") || 1;
      var offset = 1*$(this).attr("offset") || 0;
      var max_val = 1*$(this).attr("max") || 100;
      var units = $(this).attr("units");
      var decimals = $(this).attr("decimals");
      var unitend = $(this).attr("unitend") || "0";
      var font = $(this).attr("font");
      var fstyle = $(this).attr("fstyle") || "2";
      var fweight = $(this).attr("fweight") || "0";
      var color = $(this).attr("colour") || "000";
      var title = $(this).attr("solar_title");

      var fontname;
      if (font === "0"){fontname = "Impact";}
      if (font === "1"){fontname = "Georgia";}
      if (font === "2"){fontname = "Arial";}
      if (font === "3"){fontname = "Courier New";}
      if (font === "4"){fontname = "Comic Sans MS";}
      if (font === "5"){fontname = "Helvetica";}
      if (font === "6"){fontname = "sans-serif";}
      if (font === "7"){fontname = "Arial Narrow";}
      if (font === "8"){fontname = "Arial Black";}
      else if (typeof(font) === "undefined") {fontname = "Arial Black";}

      var fontstyle;

      if (fstyle === "0"){fontstyle = "oblique";}
      if (fstyle === "1"){fontstyle = "italic";}
      if (fstyle === "2"){fontstyle = "normal";}

      var fontweight;

      if (fweight === "0"){fontweight = "normal";}
      if (fweight === "1"){fontweight = "bold";}

      if (color.indexOf("#") === -1) color = "#" + color;

      var start_x = 0, start_y = 0;
      var sun_height = $(this).height();
      var sun_width = $(this).width();
      var line_width = 2;
      var margin = 1;
      var number_of_blocks = 5;

      var data = val*scale + offset;

      if(data > max_val)
        data = max_val;

      if (decimals<0){
        if (data>=100) {
            data = data.toFixed(0);
        } else if (data>=10) {
            data = data.toFixed(1);
        } else  {
            data = data.toFixed(2);
        }
        data = parseFloat(data);
      }
      else {
           data = data.toFixed(decimals);
      }

      var context = widgetcanvas[id];

      context.globalAlpha = 1;

      var bar_length = 10;
      var bar_width = 5;
      var number_of_bars = 5;

      var radius = Math.max(Math.min(sun_width/2,sun_height) - bar_length - bar_width,0);

      var centerX = sun_width / 2;
      var centerY = sun_height;

      context.beginPath();
      context.arc(start_x + centerX, start_y + centerY, radius, 1 * Math.PI, 2 * Math.PI, false);
      context.closePath();

      var fill = 255;//Math.floor(data/240*100 + 100);
      if(fill > 255)
        fill = 255;

      context.fillStyle = 'rgb('+fill+', '+(fill-27)+', 124)';
      context.fill();
      context.lineWidth = line_width+2;
      context.strokeStyle = '#ffffff';
      context.stroke();

      //Draw the bars

      context.lineWidth = line_width;
      context.strokeStyle = '#FFE87C';//'#FDB813';
      context.beginPath();
      var lxs, lys, lxe, lye;
      var theta = 1;
      for(var i=180;i<360;i+=theta)
      {
        lxs = (radius+line_width)*Math.cos(i);
        lys = (radius+line_width)*Math.sin(i);

        lxe = (radius+line_width + bar_length)*Math.cos(i);
        lye = (radius+line_width + + bar_length)*Math.sin(i);

        context.moveTo(start_x + centerX + lxs, start_y + centerY + lys);
        context.lineTo(start_x + centerX + lxe, start_y + centerY + lye);
      }
      context.stroke();

      var size = radius;

      if(errorCode == "1")
      {
      data = errorMessage;
      }
      var unitsandval = data +units;
      var valsize;
      if (unitsandval.length >4){ valsize = (size / (unitsandval.length+2)) * 5.5;}
      else {valsize = (size / 6) * 5.5;}
      var titlesize ;
      if (title.length >10) {titlesize = (size / (title.length+2)) * 9;}
      else {titlesize = (size / 12) * 9.5;}

      context.fillStyle = color;
      context.textAlign = "center";
      context.font = (fontstyle+ " "+ fontweight+ " "+(valsize*0.50)+"px "+ fontname);
      if (unitend ==="0"){context.fillText(data + units, start_x + sun_width/2, start_y + centerY - radius*0.2);}
      if (unitend ==="1"){context.fillText(units + data, start_x + sun_width/2, start_y + centerY - radius*0.2);}

      if(title)
      {
        context.fillStyle = color;
        context.textAlign = "center";
        context.font = (fontstyle+ " "+ fontweight+ " "+(titlesize*0.25)+"px "+ fontname);
        context.fillText(title, start_x + sun_width/2, start_y + centerY - radius*0.6);
      }
    }
  });
}

function sun_slowupdate(){}

function sun_fastupdate(){
  sun_draw();
}
<commit_msg>better management of error message<commit_after>/*
  All Emoncms code is released under the GNU Affero General Public License.
  See COPYRIGHT.txt and LICENSE.txt.
    ---------------------------------------------------------------------
    Part of the OpenEnergyMonitor project:
    http://openenergymonitor.org

    Author: Vikas Lamba: vikas13jun@gmail.com
    If you have any questions please get in touch, try the forums here:
    http://openenergymonitor.org/emon/forum
 */

// Convenience function for shoving things into the widget object
// I'm not sure about calling optionKey "optionKey", but I don't want to just use "options" (because that's what this whole function returns), and it's confusing enough as it is.
function addOption(widget, optionKey, optionType, optionName, optionHint, optionData){
  widget["options"    ].push(optionKey);
  widget["optionstype"].push(optionType);
  widget["optionsname"].push(optionName);
  widget["optionshint"].push(optionHint);
  widget["optionsdata"].push(optionData);
}

function sun_widgetlist(){
  var widgets =
  {
    "sun":
    {
      "offsetx":-80,"offsety":-80,"width":160,"height":160,
      "menu":"Widgets",
      "options":    [],
      "optionstype":[],
      "optionsname":[],
      "optionshint":[],
      "optionsdata":[]

    }
  };

  var decimalsDropBoxOptions = [        // Options for the type combobox. Each item is [typeID, "description"]
    [-1,   _Tr("Automatic")],
    [0,    "0"],
    [1,    "1"],
    [2,    "2"],
    [3,    "3"],
    [4,    "4"],
    [5,    "5"],
    [6,    "6"]
    ];
  var fontoptions = [
    [8, "Arial Black"],
    [7, "Arial Narrow"],
    [6, "sans-serif"],
    [5, "Helvetica"],
    [4, "Comic Sans MS"],
    [3, "Courier New"],
    [2, "Arial"],
    [1, "Georgia"],
    [0, "Impact"]
  ];
  var fstyleoptions = [
    [2, _Tr("Normal")],
    [1, _Tr("Italic")],
    [0, _Tr("Oblique")]
  ];

  var fweightoptions = [
    [0, _Tr("Normal")],
    [1, _Tr("Bold")]
  ];

  var unitEndOptions = [
    [0, _Tr("Back")],
    [1, _Tr("Front")]
  ];

  addOption(widgets["sun"],   "feedid",                "feedid",          _Tr("Feed"),          _Tr("Feed value"),                                            []);
  addOption(widgets["sun"],   "max",                   "value",           _Tr("Max value"),     _Tr("Max value to show"),                                     []);
  addOption(widgets["sun"],   "scale",                 "value",           _Tr("Scale"),         _Tr("Value is multiplied by scale before display"),           []);
  addOption(widgets["sun"],   "units",                 "dropbox_other",   _Tr("Units"),         _Tr("Units to show"),                                         _SI);
  addOption(widgets["sun"],   "unitend",               "dropbox",         _Tr("Unit position"), _Tr("Where should the unit be shown"),                        unitEndOptions);
  addOption(widgets["sun"],   "decimals",              "dropbox",         _Tr("Decimals"),      _Tr("Decimals to show"),                                      decimalsDropBoxOptions);
  addOption(widgets["sun"],   "offset",                "value",           _Tr("Offset"),        _Tr("Static offset. Subtracted from value before computing"), []);
  addOption(widgets["sun"],   "solar_title",           "value",           _Tr("solar title"),   _Tr("Solar title"),                                           []);
  addOption(widgets["sun"],   "colour",                "colour_picker",   _Tr("Colour label"),  _Tr("Color of the label"),                                    []);
  addOption(widgets["sun"],   "font",                  "dropbox",         _Tr("Font"),          _Tr("Label font"),                                            fontoptions);
  addOption(widgets["sun"],   "fstyle",                "dropbox",         _Tr("Font style"),    _Tr("Font style used for display"),                           fstyleoptions);
  addOption(widgets["sun"],   "fweight",               "dropbox",         _Tr("Font weight"),   _Tr("Font weight used for display"),                          fweightoptions);
  addOption(widgets["sun"],   "timeout",               "value",           _Tr("Timeout"),       _Tr("Timeout without feed update in seconds (empty is never)"),[]);
  addOption(widgets["sun"],   "errormessagedisplayed", "value",           _Tr("Error Message"), _Tr("Error message displayed when timeout is reached"),        []);

  return widgets;
}

function sun_init(){
  setup_widget_canvas('sun');
}

function sun_draw(){
  $('.sun').each(function(index) {
    var errorMessage = $(this).attr("errormessagedisplayed");
        if (errorMessage === "" || errorMessage === undefined){            //Error Message parameter is empty
          errorMessage = "TO Error";
        }
    var errorTimeout = $(this).attr("timeout");
        if (errorTimeout === "" || errorTimeout === undefined){            //Timeout parameter is empty
          errorTimeout = 0;
        }

    var errorCode = "0";

    var feedid = $(this).attr("feedid");
    if (assocfeed[feedid]!=undefined) feedid = assocfeed[feedid]; // convert tag:name to feedid
    if (associd[feedid] === undefined) { console.log("Review config for feed id of " + $(this).attr("class")); return; }
    var val = curve_value(feedid,dialrate).toFixed(3);

    if (errorTimeout !== 0)
      {
        if (((new Date()).getTime() / 1000 - offsetofTime - (associd[feedid]["time"] * 1)) > errorTimeout)
        {
          errorCode = "1";
        }
      }
    // ONLY UPDATE ON CHANGE
    if (val != (associd[feedid]['value'] * 1).toFixed(3) || redraw == 1 || errorTimeout != 0)
    {
      var id = "can-"+$(this).attr("id");
      var scale = 1*$(this).attr("scale") || 1;
      var offset = 1*$(this).attr("offset") || 0;
      var max_val = 1*$(this).attr("max") || 100;
      var units = $(this).attr("units");
      var decimals = $(this).attr("decimals");
      var unitend = $(this).attr("unitend") || "0";
      var font = $(this).attr("font");
      var fstyle = $(this).attr("fstyle") || "2";
      var fweight = $(this).attr("fweight") || "0";
      var color = $(this).attr("colour") || "000";
      var title = $(this).attr("solar_title");

      var fontname;
      if (font === "0"){fontname = "Impact";}
      if (font === "1"){fontname = "Georgia";}
      if (font === "2"){fontname = "Arial";}
      if (font === "3"){fontname = "Courier New";}
      if (font === "4"){fontname = "Comic Sans MS";}
      if (font === "5"){fontname = "Helvetica";}
      if (font === "6"){fontname = "sans-serif";}
      if (font === "7"){fontname = "Arial Narrow";}
      if (font === "8"){fontname = "Arial Black";}
      else if (typeof(font) === "undefined") {fontname = "Arial Black";}

      var fontstyle;

      if (fstyle === "0"){fontstyle = "oblique";}
      if (fstyle === "1"){fontstyle = "italic";}
      if (fstyle === "2"){fontstyle = "normal";}

      var fontweight;

      if (fweight === "0"){fontweight = "normal";}
      if (fweight === "1"){fontweight = "bold";}

      if (color.indexOf("#") === -1) color = "#" + color;

      var start_x = 0, start_y = 0;
      var sun_height = $(this).height();
      var sun_width = $(this).width();
      var line_width = 2;
      var margin = 1;
      var number_of_blocks = 5;

      var data = val*scale + offset;

      if(data > max_val)
        data = max_val;

      if (decimals<0){
        if (data>=100) {
            data = data.toFixed(0);
        } else if (data>=10) {
            data = data.toFixed(1);
        } else  {
            data = data.toFixed(2);
        }
        data = parseFloat(data);
      }
      else {
           data = data.toFixed(decimals);
      }

      var context = widgetcanvas[id];

      context.globalAlpha = 1;

      var bar_length = 10;
      var bar_width = 5;
      var number_of_bars = 5;

      var radius = Math.max(Math.min(sun_width/2,sun_height) - bar_length - bar_width,0);

      var centerX = sun_width / 2;
      var centerY = sun_height;

      context.beginPath();
      context.arc(start_x + centerX, start_y + centerY, radius, 1 * Math.PI, 2 * Math.PI, false);
      context.closePath();

      var fill = 255;//Math.floor(data/240*100 + 100);
      if(fill > 255)
        fill = 255;

      context.fillStyle = 'rgb('+fill+', '+(fill-27)+', 124)';
      context.fill();
      context.lineWidth = line_width+2;
      context.strokeStyle = '#ffffff';
      context.stroke();

      //Draw the bars

      context.lineWidth = line_width;
      context.strokeStyle = '#FFE87C';//'#FDB813';
      context.beginPath();
      var lxs, lys, lxe, lye;
      var theta = 1;
      for(var i=180;i<360;i+=theta)
      {
        lxs = (radius+line_width)*Math.cos(i);
        lys = (radius+line_width)*Math.sin(i);

        lxe = (radius+line_width + bar_length)*Math.cos(i);
        lye = (radius+line_width + + bar_length)*Math.sin(i);

        context.moveTo(start_x + centerX + lxs, start_y + centerY + lys);
        context.lineTo(start_x + centerX + lxe, start_y + centerY + lye);
      }
      context.stroke();

      var size = radius;

      if(errorCode == "1")
      {
      data = errorMessage;
      }
      var unitsandval = data +units;
      var valsize;
      if (unitsandval.length >4){ valsize = (size / (unitsandval.length+2)) * 5.5;}
      else {valsize = (size / 6) * 5.5;}
      var titlesize ;
      if (title.length >10) {titlesize = (size / (title.length+2)) * 9;}
      else {titlesize = (size / 12) * 9.5;}

      context.fillStyle = color;
      context.textAlign = "center";
      context.font = (fontstyle+ " "+ fontweight+ " "+(valsize*0.50)+"px "+ fontname);
      if (errorCode === "1"){context.fillText(errorMessage, start_x + sun_width/2, start_y + centerY - radius*0.2);}
      else{
      if (unitend ==="0"){context.fillText(data + units, start_x + sun_width/2, start_y + centerY - radius*0.2);}
      if (unitend ==="1"){context.fillText(units + data, start_x + sun_width/2, start_y + centerY - radius*0.2);}
      }
      if(title)
      {
        context.fillStyle = color;
        context.textAlign = "center";
        context.font = (fontstyle+ " "+ fontweight+ " "+(titlesize*0.25)+"px "+ fontname);
        context.fillText(title, start_x + sun_width/2, start_y + centerY - radius*0.6);
      }
    }
  });
}

function sun_slowupdate(){}

function sun_fastupdate(){
  sun_draw();
}
<|endoftext|>


<commit_before>var
    stream = require('stream'),
    util = require('util'),
    TTLPool = require('ttl-pool')
    ;

var DEFAULT_TTL = 60 * 1000; // 60 seconds

var IncidentManager = module.exports = function(options)
{
    this.ttl = options.ttl || DEFAULT_TTL;
    this.incidents = {};
    this._pool = new TTLPool(this._handleExpire.bind(this));
    stream.Duplex.call(this, { objectMode: true });
};
util.inherits(IncidentManager, stream.Duplex);

IncidentManager.DEFAULT_TTL = DEFAULT_TTL;

IncidentManager.prototype._write = function(event, encoding, callback)
{
    // Construct a unique incident ID.
    var id = event.host + '.' + event.name;
    // If we have a TTL for the event, make the incident TTL double of the
    // event TTL, if not, use the default TTL.
    var ttl = event.ttl ? event.ttl * 2 : this.ttl;
    this._pool.add(id, ttl);
    if (this.incidents[id])
    {
        this._pool.ping(id, ttl);
    }
    else
    {
        event.id = id;
        this.incidents[id] = event;
        this.push(event);
    }
    callback();
};

IncidentManager.prototype._handleExpire = function(id)
{
    var incident = this.incidents[id];
    incident.status = 'ok';
    this.push(incident);
    delete this.incidents[id];
};

IncidentManager.prototype._read = function(){};
<commit_msg>Always let expiries through<commit_after>var
    stream = require('stream'),
    util = require('util'),
    TTLPool = require('ttl-pool')
    ;

var DEFAULT_TTL = 60 * 1000; // 60 seconds

var IncidentManager = module.exports = function(options)
{
    this.ttl = options.ttl || DEFAULT_TTL;
    this.incidents = {};
    this._pool = new TTLPool(this._handleExpire.bind(this));
    stream.Duplex.call(this, { objectMode: true });
};
util.inherits(IncidentManager, stream.Duplex);

IncidentManager.DEFAULT_TTL = DEFAULT_TTL;

IncidentManager.prototype._write = function(event, encoding, callback)
{
    // Construct a unique incident ID.
    var id = event.host + '.' + event.name;
    // If we have a TTL for the event, make the incident TTL double of the
    // event TTL, if not, use the default TTL.
    var ttl = event.ttl ? event.ttl * 2 : this.ttl;
    this._pool.add(id, ttl);
    if (this.incidents[id] && event.status !== 'ok')
    {
        this._pool.ping(id, ttl);
    }
    else
    {
        event.id = id;
        this.incidents[id] = event;
        this.push(event);
    }
    callback();
};

IncidentManager.prototype._handleExpire = function(id)
{
    var incident = this.incidents[id];
    incident.status = 'ok';
    this.push(incident);
    delete this.incidents[id];
};

IncidentManager.prototype._read = function(){};
<|endoftext|>


<commit_before>var Transform = require('pipestream').Transform;
var util = require('../../util');
var HTTPS_FLAG = require('../../package.json').whistleSsl + '.';
var HTTPS_FLAG_LEN = HTTPS_FLAG.length;
var HTTPS_RE = /https:(\/\/|\\\/\\\/)/ig;
var RESET_COOKIE_RE = /secure;?|domain=([^;]*);?/ig;

function getTransform() {
	var transform = new Transform();
	var rest = '';
	transform._transform = function(chunk, encoding, callback) {
		if (chunk) {
			rest = chunk = (rest + chunk).replace(HTTPS_RE, 'http:$1' + HTTPS_FLAG);
			var len = chunk.length - 7;
			if (len > 0) {
				rest = chunk.substring(len);
				chunk = chunk.substring(0, len);
			} else {
				chunk = null;
			}
		} else {
			chunk = rest || null;
		}
		callback(null, chunk);
	};
	return transform;
}

module.exports = function(req, res, next) {
	if (req.headers[util.HTTPS_FIELD] || req.socket.isHttps) {//防止socket长连接导致头部无法修改
		req.socket.isHttps = true;
		req.isHttps = true;
		delete req.headers[util.HTTPS_FIELD];
	} else {
		var host = req.headers.host;
		var isHttps = host && host.indexOf(HTTPS_FLAG) == 0 && host.indexOf('.', HTTPS_FLAG_LEN) != -1;
		if (isHttps) {
			host = req.headers.host = host.substring(HTTPS_FLAG_LEN);
			req.isHttps = true;
			var referer = req.headers.referer;
			if (referer) {
				req.headers.referer = referer.replace('http://' + HTTPS_FLAG, 'https://');
			}

			res.on('src', function(_res) {
				var headers = _res.headers;
				if (/^https:\/\//i.test(headers.location)) {
					headers.location = 'http:' + HTTPS_FLAG + util.removeProtocol(headers.location, true);
				}

				var cookies = headers['set-cookie'];
				if (Array.isArray(cookies)) {
					host = host.split(':')[0].split('.');
					host = '.' + host.slice(host.length - 2).join('.');
					headers['set-cookie'] = cookies.map(function(cookie) {
						return cookie.replace(RESET_COOKIE_RE, '') + '; DOMAIN=' + host + ';';
					});
				}

				if (util.supportHtmlTransform(_res)) {
					res.addTextTransform(getTransform(), true);
				}
			});
		}
	}

	next();
};<commit_msg>add comments<commit_after>var Transform = require('pipestream').Transform;
var util = require('../../util');
var HTTPS_FLAG = require('../../package.json').whistleSsl + '.';
var HTTPS_FLAG_LEN = HTTPS_FLAG.length;
var HTTPS_RE = /https:(\/\/|\\\/\\\/)/ig;
var RESET_COOKIE_RE = /secure;?|domain=([^;]*);?/ig;

function getTransform() {
	var transform = new Transform();
	var rest = '';
	transform._transform = function(chunk, encoding, callback) {
		if (chunk) {
			rest = chunk = (rest + chunk).replace(HTTPS_RE, 'http:$1' + HTTPS_FLAG);
			var len = chunk.length - 7;
			if (len > 0) {
				rest = chunk.substring(len);
				chunk = chunk.substring(0, len);
			} else {
				chunk = null;
			}
		} else {
			chunk = rest || null;
		}
		callback(null, chunk);
	};
	return transform;
}

module.exports = function(req, res, next) {
	if (req.headers[util.HTTPS_FIELD] || req.socket.isHttps) {//防止socket长连接导致新请求的头部无法加util.HTTPS_FIELD
		req.socket.isHttps = true;
		req.isHttps = true;
		delete req.headers[util.HTTPS_FIELD];
	} else {
		var host = req.headers.host;
		var isHttps = host && host.indexOf(HTTPS_FLAG) == 0 && host.indexOf('.', HTTPS_FLAG_LEN) != -1;
		if (isHttps) {
			host = req.headers.host = host.substring(HTTPS_FLAG_LEN);
			req.isHttps = true;
			var referer = req.headers.referer;
			if (referer) {
				req.headers.referer = referer.replace('http://' + HTTPS_FLAG, 'https://');
			}

			res.on('src', function(_res) {
				var headers = _res.headers;
				if (/^https:\/\//i.test(headers.location)) {
					headers.location = 'http:' + HTTPS_FLAG + util.removeProtocol(headers.location, true);
				}

				var cookies = headers['set-cookie'];
				if (Array.isArray(cookies)) {
					host = host.split(':')[0].split('.');
					host = '.' + host.slice(host.length - 2).join('.');
					headers['set-cookie'] = cookies.map(function(cookie) {
						return cookie.replace(RESET_COOKIE_RE, '') + '; DOMAIN=' + host + ';';
					});
				}

				if (util.supportHtmlTransform(_res)) {
					res.addTextTransform(getTransform(), true);
				}
			});
		}
	}

	next();
};<|endoftext|>


<commit_before>var config = {
  server : "irc.freenode.net",
  botName : "JarvisBot",
};

var irc = require("irc");

var jarvis = new irc.Client(config.server, config.botName, {
  channels : config.channels
});

jarvis.addListener('pm', function (nick, text, message) {
  if(nick === 'thomaslangston'){
    jarvis.say(nick, 'Hello');
  }
});
//Provide talk therapy
<commit_msg>Start to give Jarvis some memory of what is happening<commit_after>var config = {
  server : "irc.freenode.net",
  botName : "JarvisBot",
};

var irc = require("irc");

var jarvis = new irc.Client(config.server, config.botName, {
  channels : config.channels
});

jarvis.addListener('pm', function (nick, text, message) {
  if(IsAllowedNick(nick)){
    Respond(nick, text, message);
  }
});

var knowledge = {
  lastSpokeTo : undefined
};

function IsAllowedNick(nick){
  return nick === 'thomaslangston';
}

function Respond(nick, text, message) {
  if(knowledge.lastSpokeTo) {
    console.log("Error - knowledge based response not implemented.");
  }
  else {
    jarvis.say(nick, "Hello, I don't remember if we've spoke to each other before.");
    jarvis.say(nick, "My name is Jarvis.");
    jarvis.say(nick, "I'm here to help.");
  }
}
<|endoftext|>


<commit_before>/**
 * Created by sanjeevbudha on 6/30/16.
 */

function deleteBreed(id){

    var mode ='delete';

    alert(window.location.href);
    var n = noty({
        layout: 'center',
        text: "Are you sure you want delete? ",
        killer: true,
        buttons: [
            {
                addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {
                n.close();
                $.ajax({
                    type:"POST",
                    url:'../controller/breedHandler.php',
                    data:"mode="+mode+"&id="+id,
                    success:function(data){
                        var data = JSON.parse(data);

                        if(data.message=='success'){
                            displayMessage("Successfully Deleted","success");
                            customReloadWindow(2000)
                        }
                    },error: function (er) {
                        alert("Error while Creating" +er.responseText);
                    }
                });
                return false;
            }
            },
            {
                addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
                n.close();
            }
            }
        ]
    })

}<commit_msg>updated<commit_after>/**
 * Created by sanjeevbudha on 6/30/16.
 */

function deleteBreed(id){

    var mode ='delete';

    var n = noty({
        layout: 'center',
        text: "Are you sure you want delete? ",
        killer: true,
        buttons: [
            {
                addClass: 'btn btn-primary', text: 'Ok', onClick: function ($noty) {
                n.close();
                $.ajax({
                    type:"POST",
                    url:'../controller/breedHandler.php',
                    data:"mode="+mode+"&id="+id,
                    success:function(data){
                        var data = JSON.parse(data);

                        if(data.message=='success'){
                            displayMessage("Successfully Deleted","success");
                            customReloadWindow(2000)
                        }
                    },error: function (er) {
                       console.log(er);
                    }
                });
                return false;
            }
            },
            {
                addClass: 'btn btn-danger', text: 'Cancel', onClick: function ($noty) {
                n.close();
            }
            }
        ]
    })

}<|endoftext|>


<commit_before>'use strict';

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

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

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

module.exports = class deribit extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'deribit',
            'name': 'Deribit',
            'countries': 'NL', // Netherlands
            'version': 'v1',
            'userAgent': undefined,
            'rateLimit': 2000,
            'has': {
                'CORS': true,
                'editOrder': true,
                'fetchOrder': true,
                'fetchOrders': false,
                'fetchOpenOrders': true,
                'fetchClosedOrders': true,
                'fetchTicker': false,
                'fetchTickers': false,
            },
            'timeframes': {},
            'urls': {
                // 'test': 'https://test.deribit.com',
                'logo': 'https://user-images.githubusercontent.com/629338/35326678-d005069c-0110-11e8-8a4c-8c8e201da2a2.png',
                'api': 'https://www.deribit.com',
                'www': 'https://www.deribit.com',
                'doc': [
                    'https://www.deribit.com/pages/docs/api',
                    'https://github.com/deribit',
                ],
                'fees': 'https://www.deribit.com/pages/information/fees',
            },
            'api': {
                'public': {
                    'get': [
                        'test',
                        'getinstruments',
                        'index',
                        'getcurrencies',
                        'getorderbook',
                        'getlasttrades',
                        'getsummary',
                        'stats',
                        'getannouncments',
                    ],
                },
                'private': {
                    'get': [
                        'account',
                        'getopenorders',
                        'positions',
                        'orderhistory',
                        'orderstate',
                        'tradehistory',
                        'newannouncements',
                    ],
                    'post': [
                        'buy',
                        'sell',
                        'edit',
                        'cancel',
                        'cancelall',
                    ],
                },
            },
            'exceptions': {
                'Invalid API Key.': AuthenticationError,
                'Access Denied': PermissionDenied,
            },
            'options': {
                'fetchTickerQuotes': true,
            },
        });
    }

    async fetchMarkets () {
        let marketsResponse = await this.publicGetGetinstruments ();
        let markets = marketsResponse['result'];
        let result = [];
        for (let p = 0; p < markets.length; p++) {
            let market = markets[p];
            let id = market['instrumentName'];
            let base = market['baseCurrency'];
            let quote = market['currency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            result.push ({
                'id': id,
                'symbol': id,
                'base': base,
                'quote': quote,
                'active': market['isActive'],
                'precision': {
                    'amount': market['minTradeSize'],
                    'price': market['tickSize'],
                },
                'limits': {
                    'amount': {
                        'min': market['minTradeSize'],
                    },
                    'price': {
                        'min': market['tickSize'],
                    },
                },
                'type': market['kind'],
                'spot': false,
                'future': market['kind'] === 'future',
                'option': market['kind'] === 'option',
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        let account = await this.privateGetAccount ();
        let result = {
            'BTC': {
                'free': account['result']['availableFunds'],
                'used': account['result']['maintenanceMargin'],
                'total': account['result']['equity'],
            },
        };
        return this.parseBalance (result);
    }

    async fetchDepositAddress (currency, params = {}) {
        let account = await this.privateGetAccount ();
        return {
            'currency': 'BTC',
            'address': account['depositAddress'],
            'status': 'ok',
            'info': account,
        };
    }

    parseTrade (trade, market) {
        return {
            'info': trade,
            'timestamp': trade['timeStamp'],
            'datetime': this.iso8601 (trade['timeStamp']),
            'symbol': market['symbol'],
            'id': trade['tradeId'].toString (),
            'order': undefined,
            'type': undefined,
            'side': trade['direction'],
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'quantity'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'instrument': market['id'],
        };
        if (typeof limit !== 'undefined') {
            request['limit'] = limit;
        } else {
            request['limit'] = 10000;
        }
        let response = await this.publicGetGetlasttrades (this.extend (request, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetGetorderbook ({ 'instrument': market['id'] });
        let timestamp = response['usOut'] / 1000000;
        let orderbook = this.parseOrderBook (response['result'], timestamp, 'bids', 'asks', 'price', 'quantity');
        return this.extend (orderbook, {
            'nonce': this.safeInteger (response, 'tstamp'),
        });
    }

    parseOrder (order) {

        // {
        //     "success": true,  // true or false
        //     "message": "",    // empty or text message, e.g. error message
        //     "result": [       // list of open orders
        //     {
        //             "orderId": 5258039,          // ID of the order
        //             "instrument": "BTC-26MAY17", // instrument name
        //             "direction": "sell",         // order direction, "buy" or "sell"
        //             "price": 1860,               // float, USD for futures, BTC for options
        //             "label": "",                 // label set by the owner, up to 32 chars
        //             "quantity": 10,              // quantity, in contracts ($10 per contract for futures, ฿1 — for options)
        //             "filledQuantity": 3,         // filled quantity, in contracts ($10 per contract for futures, ฿1 — for options)
        //             "avgPrice": 1860,            // average fill price of the order
        //             "commission": -0.000001613,  // in BTC units
        //             "created": 1494491899308,    // creation timestamp
        //             "lastUpdate": 1494491988754, // timestamp of the last order state change
        //                                          // (before this cancelorder of course)
        //             "state": "open",             // open, cancelled, etc
        //             "postOnly": false            // true for post-only orders only
        //         }
        //     ]
        // }

        return {
            'info': order,
            'id': order['orderId'].toString (),
            'timestamp': order['created'],
            'datetime': this.iso8601 (order['created']),
            'lastTradeTimestamp': undefined,
            'symbol': order['instrument'],
            'type': undefined,
            'side': order['direction'].toLowerCase (),
            'price': order['price'],
            'amount': order['quantity'],
            'cost': order['commission'],
            'filled': order['filledQuantity'],
            'remaining': order['quantity'] - order['filledQuantity'],
            'status': order['state'],
            'fee': undefined,
        };
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        let response = await this.privateGetOrderstate ({ 'orderId': id });
        return this.parseOrder (response['result']);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetTradeHistory ({ 'instrument': symbol });
        return this.parseTrades (response['result']);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'instrument': this.marketId (symbol),
            'quantity': amount,
            'type': type,
        };
        if (typeof price !== 'undefined')
            request['price'] = price;
        let handler = (side === 'buy') ? this.privatePostBuy : this.privatePostSell;
        let response = await handler (this.extend (request, params));
        let order = this.parseOrder (response['result']);
        this.orders[order['id']] = order;
        return this.extend ({ 'info': response['result'] }, order);
    }

    async editOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'orderId': id,
        };
        if (typeof amount !== 'undefined')
            request['quantity'] = amount;
        if (typeof price !== 'undefined')
            request['price'] = price;
        let response = await this.privatePostEdit (this.extend (request, params));
        let order = this.parseOrder (response['result']);
        this.orders[order['id']] = order;
        return this.extend ({ 'info': response['result'] }, order);
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostCancel (this.extend ({ 'orderId': id }, params));
        let order = this.parseOrder (response['result']);
        return this.extend ({ 'info': response['result'] }, order);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        params['instrument'] = this.marketId (symbol);
        let response = await this.privateGetGetopenorders (params);
        return this.parseOrders (response['result']);
    }

    async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        params['instrument'] = this.marketId (symbol);
        let response = await this.privateGetOrderhistory (params);
        return this.parseOrders (response['result']);
    }

    async fetchMyTradesOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        params['instrument'] = this.marketId (symbol);
        let response = await this.privateGetGetopenorders (params);
        return this.parseTrades (response['result']);
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let query = '/' + 'api/' + this.version + '/' + api + '/' + path;
        let url = this.urls['api'] + query;
        if (api === 'public') {
            if (Object.keys (params).length) {
                url += '?' + this.urlencode (params);
            }
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let auth = '_=' + nonce + '&_ackey=' + this.apiKey + '&_acsec=' + this.secret + '&_action=' + query;
            if (method === 'POST') {
                params = this.keysort (params);
                auth += '&' + this.urlencode (params);
            }
            let hash = this.hash (this.encode (auth), 'sha256', 'base64');
            let signature = this.apiKey + '.' + nonce + '.' + hash;
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'x-deribit-sig': signature,
            };
            body = this.urlencode (params);
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<commit_msg>deribit parseorder + parseOrderStatus #3133 #334<commit_after>'use strict';

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

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

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

module.exports = class deribit extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'deribit',
            'name': 'Deribit',
            'countries': 'NL', // Netherlands
            'version': 'v1',
            'userAgent': undefined,
            'rateLimit': 2000,
            'has': {
                'CORS': true,
                'editOrder': true,
                'fetchOrder': true,
                'fetchOrders': false,
                'fetchOpenOrders': true,
                'fetchClosedOrders': true,
                'fetchTicker': false,
                'fetchTickers': false,
            },
            'timeframes': {},
            'urls': {
                // 'test': 'https://test.deribit.com',
                'logo': 'https://user-images.githubusercontent.com/629338/35326678-d005069c-0110-11e8-8a4c-8c8e201da2a2.png',
                'api': 'https://www.deribit.com',
                'www': 'https://www.deribit.com',
                'doc': [
                    'https://www.deribit.com/pages/docs/api',
                    'https://github.com/deribit',
                ],
                'fees': 'https://www.deribit.com/pages/information/fees',
            },
            'api': {
                'public': {
                    'get': [
                        'test',
                        'getinstruments',
                        'index',
                        'getcurrencies',
                        'getorderbook',
                        'getlasttrades',
                        'getsummary',
                        'stats',
                        'getannouncments',
                    ],
                },
                'private': {
                    'get': [
                        'account',
                        'getopenorders',
                        'positions',
                        'orderhistory',
                        'orderstate',
                        'tradehistory',
                        'newannouncements',
                    ],
                    'post': [
                        'buy',
                        'sell',
                        'edit',
                        'cancel',
                        'cancelall',
                    ],
                },
            },
            'exceptions': {
                'Invalid API Key.': AuthenticationError,
                'Access Denied': PermissionDenied,
            },
            'options': {
                'fetchTickerQuotes': true,
            },
        });
    }

    async fetchMarkets () {
        let marketsResponse = await this.publicGetGetinstruments ();
        let markets = marketsResponse['result'];
        let result = [];
        for (let p = 0; p < markets.length; p++) {
            let market = markets[p];
            let id = market['instrumentName'];
            let base = market['baseCurrency'];
            let quote = market['currency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            result.push ({
                'id': id,
                'symbol': id,
                'base': base,
                'quote': quote,
                'active': market['isActive'],
                'precision': {
                    'amount': market['minTradeSize'],
                    'price': market['tickSize'],
                },
                'limits': {
                    'amount': {
                        'min': market['minTradeSize'],
                    },
                    'price': {
                        'min': market['tickSize'],
                    },
                },
                'type': market['kind'],
                'spot': false,
                'future': market['kind'] === 'future',
                'option': market['kind'] === 'option',
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        let account = await this.privateGetAccount ();
        let result = {
            'BTC': {
                'free': account['result']['availableFunds'],
                'used': account['result']['maintenanceMargin'],
                'total': account['result']['equity'],
            },
        };
        return this.parseBalance (result);
    }

    async fetchDepositAddress (currency, params = {}) {
        let account = await this.privateGetAccount ();
        return {
            'currency': 'BTC',
            'address': account['depositAddress'],
            'status': 'ok',
            'info': account,
        };
    }

    parseTrade (trade, market = undefined) {
        let id = this.safeString (trade, 'tradeId');
        let symbol = undefined;
        if (typeof market !== 'undefined')
            symbol = market['symbol'];
        let timestamp = this.safeInteger (trade, 'timestamp');
        return {
            'info': trade,
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'order': undefined,
            'type': undefined,
            'side': trade['direction'],
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'quantity'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let request = {
            'instrument': market['id'],
        };
        if (typeof limit !== 'undefined') {
            request['limit'] = limit;
        } else {
            request['limit'] = 10000;
        }
        let response = await this.publicGetGetlasttrades (this.extend (request, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetGetorderbook ({ 'instrument': market['id'] });
        let timestamp = response['usOut'] / 1000000;
        let orderbook = this.parseOrderBook (response['result'], timestamp, 'bids', 'asks', 'price', 'quantity');
        return this.extend (orderbook, {
            'nonce': this.safeInteger (response, 'tstamp'),
        });
    }

    parseOrderStatus (status) {
        const statuses = {
            'open': 'open',
            'cancelled': 'canceled',
            'filled': 'closed',
        };
        if (status in statuses) {
            return statuses['status'];
        }
        return status;
    }

    parseOrder (order) {

        // {
        //     "success": true,  // true or false
        //     "message": "",    // empty or text message, e.g. error message
        //     "result": [       // list of open orders
        //     {
        //             "orderId": 5258039,          // ID of the order
        //             "instrument": "BTC-26MAY17", // instrument name
        //             "direction": "sell",         // order direction, "buy" or "sell"
        //             "price": 1860,               // float, USD for futures, BTC for options
        //             "label": "",                 // label set by the owner, up to 32 chars
        //             "quantity": 10,              // quantity, in contracts ($10 per contract for futures, ฿1 — for options)
        //             "filledQuantity": 3,         // filled quantity, in contracts ($10 per contract for futures, ฿1 — for options)
        //             "avgPrice": 1860,            // average fill price of the order
        //             "commission": -0.000001613,  // in BTC units
        //             "created": 1494491899308,    // creation timestamp
        //             "lastUpdate": 1494491988754, // timestamp of the last order state change
        //                                          // (before this cancelorder of course)
        //             "state": "open",             // open, cancelled, etc
        //             "postOnly": false            // true for post-only orders only
        //         }
        //     ]
        // }

        // {
        //     "success": true,
        //     "result": [ // list of orders from history, filled quantity > 0
        //         {
        //             "orderId": 5258039,         // ID of the order
        //             "instrument": "BTC-26MAY17", // name of the instrument
        //             "direction": "sell",         // direction of the order, "buy" or "sell"
        //             "price": 1860,              // float, USD for futures, BTC for options
        //             "label" : "",               // order label, if present,
        //             "quantity": 10,             // quantity, in contracts ($10 per contract for futures, ฿1 — for options)
        //             "filledQuantity": 3,        // filled quantity, in contracts ($10 per contract for futures, ฿1 — for options)
        //             "avgPrice": 1860,           // average fill price of the order
        //             "commission": -0.000001613, // in ฿
        //             "created": 1494491899308,   // creation timestamp
        //             "tstamp": 1494492913288,    // timestamp of the last order state change
        //             "modified": 1494492913289,  // timestamp of the last db write operation,
        //                                         // e.g. trade that doesn't change order status
        //             "state": "cancelled",       // state of the order "open", "cancelled", "filled"
        //             "postOnly": false,          // true for post-only orders only
        //             "adv": false                // advanced type (false, or "usd" or "implv")
        //        } ....
        //     ]
        // }

        let price = this.safeFloat (order, 'price');
        let amount = this.safeFloat (order, 'amount');
        let filled = this.safeFloat (order, 'filledQuantity');
        let remaining = undefined;
        price = this.safeFloat (order, 'avgPrice', price);
        let cost = undefined;
        if (typeof filled !== 'undefined') {
            if (typeof amount !== 'undefined') {
                remaining = amount - filled;
            }
            if (typeof price !== 'undefined') {
                cost = price * filled;
            }
        }
        let status = this.safeString (order, 'state');
        status = this.parseOrderStatus (status);
        return {
            'info': order,
            'id': order['orderId'].toString (),
            'timestamp': order['created'],
            'datetime': this.iso8601 (order['created']),
            'lastTradeTimestamp': undefined,
            'symbol': order['instrument'],
            'type': undefined,
            'side': order['direction'].toLowerCase (),
            'price': price,
            'amount': amount,
            'cost': cost,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': {
                'cost': this.safeFloat (order, 'commission'),
                'currency': 'BTC',
            },
        };
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        let response = await this.privateGetOrderstate ({ 'orderId': id });
        return this.parseOrder (response['result']);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetTradeHistory ({ 'instrument': symbol });
        return this.parseTrades (response['result']);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'instrument': this.marketId (symbol),
            'quantity': amount,
            'type': type,
        };
        if (typeof price !== 'undefined')
            request['price'] = price;
        let handler = (side === 'buy') ? this.privatePostBuy : this.privatePostSell;
        let response = await handler (this.extend (request, params));
        let order = this.parseOrder (response['result']);
        this.orders[order['id']] = order;
        return this.extend ({ 'info': response['result'] }, order);
    }

    async editOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'orderId': id,
        };
        if (typeof amount !== 'undefined')
            request['quantity'] = amount;
        if (typeof price !== 'undefined')
            request['price'] = price;
        let response = await this.privatePostEdit (this.extend (request, params));
        let order = this.parseOrder (response['result']);
        this.orders[order['id']] = order;
        return this.extend ({ 'info': response['result'] }, order);
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostCancel (this.extend ({ 'orderId': id }, params));
        let order = this.parseOrder (response['result']);
        return this.extend ({ 'info': response['result'] }, order);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        params['instrument'] = this.marketId (symbol);
        let response = await this.privateGetGetopenorders (params);
        return this.parseOrders (response['result']);
    }

    async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        params['instrument'] = this.marketId (symbol);
        let response = await this.privateGetOrderhistory (params);
        return this.parseOrders (response['result']);
    }

    async fetchMyTradesOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        params['instrument'] = this.marketId (symbol);
        let response = await this.privateGetGetopenorders (params);
        return this.parseTrades (response['result']);
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let query = '/' + 'api/' + this.version + '/' + api + '/' + path;
        let url = this.urls['api'] + query;
        if (api === 'public') {
            if (Object.keys (params).length) {
                url += '?' + this.urlencode (params);
            }
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let auth = '_=' + nonce + '&_ackey=' + this.apiKey + '&_acsec=' + this.secret + '&_action=' + query;
            if (method === 'POST') {
                params = this.keysort (params);
                auth += '&' + this.urlencode (params);
            }
            let hash = this.hash (this.encode (auth), 'sha256', 'base64');
            let signature = this.apiKey + '.' + nonce + '.' + hash;
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'x-deribit-sig': signature,
            };
            body = this.urlencode (params);
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<|endoftext|>


<commit_before>chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
       console.log(request);
       console.log(sender);
       getOtherBookmarksChildren(function(other, otherID){
           if (other == null) {
               console.error("'Other Bookmarks' not found.");
               return;
           }
           var folders = retrieveFolders(other, otherID);
           var folder = determineBestFolder(request, folders);
           getUncategorizedFolder(other, otherID, function(uncategorized){
              console.log(uncategorized);
           });
       });
});

function getOtherBookmarksChildren(callback) {
    chrome.bookmarks.getTree(function(results){
        var title = "Other Bookmarks";
        var topLevel = results[0].children;
        for (var nodeKey in topLevel){
           var node = topLevel[nodeKey];
           if (node.title == title)
              return callback(node.children, node.id);
        }
        return callback(null, null);
     });
}

function retrieveFolders(folder) {
    var folders = [];
    for (var nodeKey in folder){
      var node = folder[nodeKey];
      if (!node.hasOwnProperty("url"))
          folders.push(node);
    }
    return folders;
}

function getUncategorizedFolder(folders, otherID, callback){
    for (var folderKey in folders){
        var folder = folders[folderKey];
        if (folder.title == "Uncategorized")
            return callback(folder);
    }
    // Create uncategorized folder
    chrome.bookmarks.create({'parentId': otherID, 'title': 'Uncategorized'},
        function(uncategorizedFolder) {
            callback(uncategorizedFolder);
        }
    );
}

function determineBestFolder(page, folders){

}
<commit_msg>Create bookmark.<commit_after>chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
       getOtherBookmarksChildren(function(other, otherID){
           if (other == null) {
               console.error("'Other Bookmarks' not found.");
               return;
           }
           var folders = retrieveFolders(other, otherID);
           var folder = determineBestFolder(sender.tab, request, folders);
           if (folder == null){
               // Find the uncategorized folder and create bookmark there
               getUncategorizedFolder(other, otherID, function(uncategorized){
                   chrome.bookmarks.create({'parentId': uncategorized.id,
                         'title': sender.tab.title,
                         'url': sender.tab.url});
                   folder = uncategorized;
               });
           }else{
               chrome.bookmarks.create({'parentId': folder.id,
                  'title': sender.tab.title,
                  'url': sender.tab.url});
           }
           // At this point folder will be the folder containing the bookmark
           populateInterface(folder, folders, sender.tab);
       });
});

function getOtherBookmarksChildren(callback) {
    chrome.bookmarks.getTree(function(results){
        var title = "Other Bookmarks";
        var topLevel = results[0].children;
        for (var nodeKey in topLevel){
           var node = topLevel[nodeKey];
           if (node.title == title)
              return callback(node.children, node.id);
        }
        return callback(null, null);
     });
}

function retrieveFolders(folder) {
    var folders = [];
    for (var nodeKey in folder){
      var node = folder[nodeKey];
      if (!node.hasOwnProperty("url"))
          folders.push(node);
    }
    return folders;
}

function getUncategorizedFolder(folders, otherID, callback){
    for (var folderKey in folders){
        var folder = folders[folderKey];
        if (folder.title == "Uncategorized")
            return callback(folder);
    }
    // Create uncategorized folder
    chrome.bookmarks.create({'parentId': otherID, 'title': 'Uncategorized'},
        function(uncategorizedFolder) {
            callback(uncategorizedFolder);
        }
    );
}

function populateInterface(folder, otherFolders, page){

}

function determineBestFolder(page, folders){

}
<|endoftext|>


<commit_before>/**
 * Gamepad Listener
 */
function GamepadListener(options)
{
    EventEmitter.call(this);

    this.options  = typeof(options) === 'object' ? options : {};
    this.frame    = null;
    this.update   = this.update.bind(this);
    this.onAxis   = this.onAxis.bind(this);
    this.onButton = this.onButton.bind(this);
    this.stop     = this.stop.bind(this);
    this.handlers = new Array(4);

    window.addEventListener('error', this.stop);

}

GamepadListener.prototype = Object.create(EventEmitter.prototype);

/**
 * Start
 */
GamepadListener.prototype.start = function()
{
    if (!this.frame) {
        this.update();
    }
};

/**
 * Stop
 */
GamepadListener.prototype.stop = function()
{
    if (this.frame) {
        window.cancelAnimationFrame(this.frame);
        this.frame = null;
    }
};

/**
 * Update
 */
GamepadListener.prototype.update = function()
{
    this.frame = window.requestAnimationFrame(this.update);

    var gamepads = this.getGamepads();

    for (var i = gamepads.length - 1; i >= 0; i--) {
        if (gamepads[i]) {
            if (typeof(gamepads[i].handler) === 'undefined') {
                this.addGamepad(gamepads[i]);
            }

            gamepads[i].handler.update();
        } else if (this.handlers[i]) {
            this.removeGamepad(i);
        }
    }
};

/**
 * Add gamepad
 *
 * @param {Gamepad} gamepad
 */
GamepadListener.prototype.addGamepad = function(gamepad)
{
    console.log('addGamepad', gamepad);

    var handler = new GamepadHandler(gamepad, this.options);

    handler.on('axis', this.onAxis);
    handler.on('button', this.onButton);

    this.emit('gamepad:connected', {gamepad: gamepad, index: gamepad.index});
    this.emit('gamepad:' + gamepad.index + ':connected', {gamepad: gamepad, index: gamepad.index});

    this.handlers[gamepad.index] = handler;
};

/**
 * Add gamepad
 *
 * @param {Gamepad} gamepad
 */
GamepadListener.prototype.removeGamepad = function(index)
{
    var handler = this.handlers[index];

    console.log('removeGamepad', index, handler, handler.gamepad);

    handler.off('axis', this.onAxis);
    handler.off('button', this.onButton);

    this.emit('gamepad:disconnected', {index: index});
    this.emit('gamepad:' + index + ':disconnected', {index: index});

    this.handlers[index] = null;
};

/**
 * On axe
 *
 * @param {Event} event
 */
GamepadListener.prototype.onAxis = function(event)
{
    this.emit('gamepad:axis', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':axis', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':axis:' + event.detail.axis, event.detail);
};

/**
 * On button
 *
 * @param {Event} event
 */
GamepadListener.prototype.onButton = function(event)
{
    this.emit('gamepad:button', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':button', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':button:' + event.detail.index, event.detail);
};

/**
 * Get gampads
 *
 * @return {GamepadList}
 */
GamepadListener.prototype.getGamepads = function()
{
    return typeof(navigator.getGamepads) !== 'undefined' ? navigator.getGamepads() : (typeof(navigator.webkitGetGamepads) !== 'undefined' ? navigator.webkitGetGamepads() : null);
};
<commit_msg>Removed console<commit_after>/**
 * Gamepad Listener
 */
function GamepadListener(options)
{
    EventEmitter.call(this);

    this.options  = typeof(options) === 'object' ? options : {};
    this.frame    = null;
    this.update   = this.update.bind(this);
    this.onAxis   = this.onAxis.bind(this);
    this.onButton = this.onButton.bind(this);
    this.stop     = this.stop.bind(this);
    this.handlers = new Array(4);

    window.addEventListener('error', this.stop);

}

GamepadListener.prototype = Object.create(EventEmitter.prototype);

/**
 * Start
 */
GamepadListener.prototype.start = function()
{
    if (!this.frame) {
        this.update();
    }
};

/**
 * Stop
 */
GamepadListener.prototype.stop = function()
{
    if (this.frame) {
        window.cancelAnimationFrame(this.frame);
        this.frame = null;
    }
};

/**
 * Update
 */
GamepadListener.prototype.update = function()
{
    this.frame = window.requestAnimationFrame(this.update);

    var gamepads = this.getGamepads();

    for (var i = gamepads.length - 1; i >= 0; i--) {
        if (gamepads[i]) {
            if (typeof(gamepads[i].handler) === 'undefined') {
                this.addGamepad(gamepads[i]);
            }

            gamepads[i].handler.update();
        } else if (this.handlers[i]) {
            this.removeGamepad(i);
        }
    }
};

/**
 * Add gamepad
 *
 * @param {Gamepad} gamepad
 */
GamepadListener.prototype.addGamepad = function(gamepad)
{
    var handler = new GamepadHandler(gamepad, this.options);

    handler.on('axis', this.onAxis);
    handler.on('button', this.onButton);

    this.emit('gamepad:connected', {gamepad: gamepad, index: gamepad.index});
    this.emit('gamepad:' + gamepad.index + ':connected', {gamepad: gamepad, index: gamepad.index});

    this.handlers[gamepad.index] = handler;
};

/**
 * Add gamepad
 *
 * @param {Gamepad} gamepad
 */
GamepadListener.prototype.removeGamepad = function(index)
{
    var handler = this.handlers[index];

    handler.off('axis', this.onAxis);
    handler.off('button', this.onButton);

    this.emit('gamepad:disconnected', {index: index});
    this.emit('gamepad:' + index + ':disconnected', {index: index});

    this.handlers[index] = null;
};

/**
 * On axe
 *
 * @param {Event} event
 */
GamepadListener.prototype.onAxis = function(event)
{
    this.emit('gamepad:axis', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':axis', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':axis:' + event.detail.axis, event.detail);
};

/**
 * On button
 *
 * @param {Event} event
 */
GamepadListener.prototype.onButton = function(event)
{
    this.emit('gamepad:button', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':button', event.detail);
    this.emit('gamepad:' + event.detail.gamepad.index + ':button:' + event.detail.index, event.detail);
};

/**
 * Get gampads
 *
 * @return {GamepadList}
 */
GamepadListener.prototype.getGamepads = function()
{
    return typeof(navigator.getGamepads) !== 'undefined' ? navigator.getGamepads() : (typeof(navigator.webkitGetGamepads) !== 'undefined' ? navigator.webkitGetGamepads() : null);
};
<|endoftext|>