<commit_before>const moment = require('moment');
const _ = require('lodash');

const Errors = require('../exchangeErrors');
const marketData = require('./binance-markets.json');
const retry = require('../exchangeUtils').retry;

const Binance = require('binance');

const Trader = function(config) {
  _.bindAll(this, [
    'roundAmount',
    'roundPrice',
    'isValidPrice',
    'isValidLot'
  ]);

  if (_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
    this.currency = config.currency.toUpperCase();
    this.asset = config.asset.toUpperCase();
  }

  let recvWindow = 6000;
  if(config.optimizedConnection) {
    // there is a bug in binance's API
    // where some requests randomly take
    // over a second, this tells binance
    // to bail out after 500ms.
    //
    // As discussed in binance API
    // telegram. TODO add link.
    recvWindow = 500;
  }

  this.pair = this.asset + this.currency;
  this.name = 'binance';

  this.market = _.find(Trader.getCapabilities().markets, (market) => {
    return market.pair[0] === this.currency && market.pair[1] === this.asset
  });

  this.binance = new Binance.BinanceRest({
    key: this.key,
    secret: this.secret,
    timeout: 15000,
    recvWindow,
    disableBeautification: false,
    handleDrift: true,
  });

  if(config.key && config.secret) {
    // Note non standard func:
    //
    // On binance we might pay fees in BNB
    // if we do we CANNOT calculate feePercent
    // since we don't track BNB price (when we
    // are not trading on a BNB market).
    //
    // Though we can deduce feePercent based
    // on user fee tracked through `this.getFee`.
    // Set default here, overwrite in getFee.
    this.fee = 0.1;
    // Set the proper fee asap.
    this.getFee(_.noop);
  }
};

const recoverableErrors = [
  'SOCKETTIMEDOUT',
  'TIMEDOUT',
  'CONNRESET',
  'CONNREFUSED',
  'NOTFOUND',
  'Error -1021',
  'Response code 429',
  'Response code 5',
  'Response code 403',
  'ETIMEDOUT'
];

const includes = (str, list) => {
  if(!_.isString(str))
    return false;

  return _.some(list, item => str.includes(item));
}

Trader.prototype.handleResponse = function(funcName, callback) {
  return (error, body) => {
    if (body && body.code) {
      error = new Error(`Error ${body.code}: ${body.msg}`);
    }

    if(error) {
      if(_.isString(error)) {
        error = new Error(error);
      }

      if(includes(error.message, recoverableErrors)) {
        error.notFatal = true;
      }

      if(funcName === 'cancelOrder' && error.message.includes('UNKNOWN_ORDER')) {
        // order got filled in full before it could be
        // cancelled, meaning it was NOT cancelled.
        return callback(false, {filled: true});
      }

      if(funcName === 'checkOrder' && error.message.includes('Order does not exist.')) {
        // order got filled in full before it could be
        // cancelled, meaning it was NOT cancelled.
        return callback(false, {filled: true});
      }

      return callback(error);
    }

    return callback(undefined, body);
  }
};

Trader.prototype.getTrades = function(since, callback, descending) {
  const processResults = (err, data) => {
    if (err) return callback(err);

    var parsedTrades = [];
    _.each(
      data,
      function(trade) {
        parsedTrades.push({
          tid: trade.aggTradeId,
          date: moment(trade.timestamp).unix(),
          price: parseFloat(trade.price),
          amount: parseFloat(trade.quantity),
        });
      },
      this
    );

    if (descending) callback(null, parsedTrades.reverse());
    else callback(undefined, parsedTrades);
  };

  var reqData = {
    symbol: this.pair,
  };

  if (since) {
    var endTs = moment(since)
      .add(1, 'h')
      .valueOf();
    var nowTs = moment().valueOf();

    reqData.startTime = moment(since).valueOf();
    reqData.endTime = endTs > nowTs ? nowTs : endTs;
  }

  const fetch = cb => this.binance.aggTrades(reqData, this.handleResponse('getTrades', cb));
  retry(undefined, fetch, processResults);
};

Trader.prototype.getPortfolio = function(callback) {
  const setBalance = (err, data) => {
    if (err) return callback(err);

    const findAsset = item => item.asset === this.asset;
    const assetAmount = parseFloat(_.find(data.balances, findAsset).free);

    const findCurrency = item => item.asset === this.currency;
    const currencyAmount = parseFloat(_.find(data.balances, findCurrency).free);

    if (!_.isNumber(assetAmount) || _.isNaN(assetAmount)) {
      assetAmount = 0;
    }

    if (!_.isNumber(currencyAmount) || _.isNaN(currencyAmount)) {
      currencyAmount = 0;
    }

    const portfolio = [
      { name: this.asset, amount: assetAmount },
      { name: this.currency, amount: currencyAmount },
    ];

    return callback(undefined, portfolio);
  };

  const fetch = cb => this.binance.account({}, this.handleResponse('getPortfolio', cb));
  retry(undefined, fetch, setBalance);
};

Trader.prototype.getFee = function(callback) {

  // binance does NOT tell us whether the user is using BNB to pay
  // for fees, which means a discount (effectively lower fees)
  const handle = (err, data) => {
    if(err)  {
      return callback(err);
    }

    const basepoints = data.makerCommission;

    // note non standard func, see constructor
    this.fee = basepoints / 100;

    callback(undefined, basepoints / 100);
  }

  const fetch = cb => this.binance.account({}, this.handleResponse('getFee', cb));
  retry(undefined, fetch, handle);
};

Trader.prototype.getTicker = function(callback) {
  const setTicker = (err, data) => {
    if (err)
      return callback(err);

    var result = _.find(data, ticker => ticker.symbol === this.pair);

    if(!result)
      return callback(new Error(`Market ${this.pair} not found on Binance`));

    var ticker = {
      ask: parseFloat(result.askPrice),
      bid: parseFloat(result.bidPrice),
    };

    callback(undefined, ticker);
  };

  const handler = cb => this.binance._makeRequest({}, this.handleResponse('getTicker', cb), 'api/v1/ticker/allBookTickers');
  retry(undefined, handler, setTicker);
};

// Effectively counts the number of decimal places, so 0.001 or 0.234 results in 3
Trader.prototype.getPrecision = function(tickSize) {
  if (!isFinite(tickSize)) return 0;
  var e = 1, p = 0;
  while (Math.round(tickSize * e) / e !== tickSize) { e *= 10; p++; }
  return p;
};

Trader.prototype.round = function(amount, tickSize) {
  var precision = 100000000;
  var t = this.getPrecision(tickSize);

  if(Number.isInteger(t))
    precision = Math.pow(10, t);

  amount *= precision;
  amount = Math.floor(amount);
  amount /= precision;

  // https://gist.github.com/jiggzson/b5f489af9ad931e3d186
  amount = this.scientificToDecimal(amount);

  return amount;
};

// https://gist.github.com/jiggzson/b5f489af9ad931e3d186
Trader.prototype.scientificToDecimal = function(num) {
  if(/\d+\.?\d*e[\+\-]*\d+/i.test(num)) {
    const zero = '0';
    const parts = String(num).toLowerCase().split('e'); // split into coeff and exponent
    const e = parts.pop(); // store the exponential part
    const l = Math.abs(e); // get the number of zeros
    const sign = e/l;
    const coeff_array = parts[0].split('.');
    if(sign === -1) {
      num = zero + '.' + new Array(l).join(zero) + coeff_array.join('');
    } else {
      const dec = coeff_array[1];
      if(dec) {
        l = l - dec.length;
      }
      num = coeff_array.join('') + new Array(l+1).join(zero);
    }
  } else {
    // make sure we always cast to string
    num = num + '';
  }

  return num;
}

Trader.prototype.roundAmount = function(amount) {
  return this.round(amount, this.market.minimalOrder.amount);
}

Trader.prototype.roundPrice = function(price) {
  return this.round(price, this.market.minimalOrder.price);
}

Trader.prototype.isValidPrice = function(price) {
  return price >= this.market.minimalOrder.price;
}

Trader.prototype.isValidLot = function(price, amount) {
  return amount * price >= this.market.minimalOrder.order;
}

Trader.prototype.outbidPrice = function(price, isUp) {
  let newPrice;

  if(isUp) {
    newPrice = price + this.market.minimalOrder.price;
  } else {
    newPrice = price - this.market.minimalOrder.price;
  }

  return this.roundPrice(newPrice);
}

Trader.prototype.addOrder = function(tradeType, amount, price, callback) {
  const setOrder = (err, data) => {
    if (err) return callback(err);

    const txid = data.orderId;

    callback(undefined, txid);
  };

  const reqData = {
    symbol: this.pair,
    side: tradeType.toUpperCase(),
    type: 'LIMIT',
    timeInForce: 'GTC',
    quantity: amount,
    price: price,
    timestamp: new Date().getTime()
  };

  const handler = cb => this.binance.newOrder(reqData, this.handleResponse('addOrder', cb));
  retry(undefined, handler, setOrder);
};

Trader.prototype.getOrder = function(order, callback) {
  const get = (err, data) => {
    if (err) return callback(err);

    let price = 0;
    let amount = 0;
    let date = moment(0);

    const fees = {};

    const trades = _.filter(data, t => {
      // note: the API returns a string after creating
      return t.orderId == order;
    });

    if(!trades.length) {
      return callback(new Error('Trades not found'));
    }

    _.each(trades, trade => {
      date = moment(trade.time);
      price = ((price * amount) + (+trade.price * trade.qty)) / (+trade.qty + amount);
      amount += +trade.qty;

      if(fees[trade.commissionAsset])
        fees[trade.commissionAsset] += (+trade.commission);
      else
        fees[trade.commissionAsset] = (+trade.commission);
    });

    let feePercent;
    if(_.keys(fees).length === 1) {
      if(fees.BNB && this.asset !== 'BNB' && this.currency !== 'BNB') {
        // we paid fees in BNB, right now that means the fee is always 75%
        // of base fee. We cannot calculate since we do not have the BNB rate.
        feePercent = this.fee * 0.75;
      } else {
        if(fees[this.asset]) {
          feePercent = fees[this.asset] / amount * 100;
        } else if(fees.currency) {
          feePercent = fees[this.currency] / price / amount * 100;
        } else {
          // use user fee of 10 basepoints
          feePercent = this.fee;
        }
      }
    } else {
      // we paid fees in multiple currencies?
      // assume user fee
      feePercent = this.fee;
    }

    callback(undefined, { price, amount, date, fees, feePercent });
  }

  const reqData = {
    symbol: this.pair,
    // if this order was not part of the last 500 trades we won't find it..
    limit: 500,
  };

  const handler = cb => this.binance.myTrades(reqData, this.handleResponse('getOrder', cb));
  retry(undefined, handler, get);
};

Trader.prototype.buy = function(amount, price, callback) {
  this.addOrder('buy', amount, price, callback);
};

Trader.prototype.sell = function(amount, price, callback) {
  this.addOrder('sell', amount, price, callback);
};

Trader.prototype.checkOrder = function(order, callback) {

  const check = (err, data) => {
    if (err) {
      return callback(err);
    }

    if(data.filled === true) {
      // binance responsed with order not found
      return callback(undefined, { executed: true, open: false });
    }

    const status = data.status;

    if(
      status === 'CANCELED' ||
      status === 'REJECTED' ||
      // for good measure: GB does not
      // submit orders that can expire yet
      status === 'EXPIRED'
    ) {
      return callback(undefined, { executed: false, open: false });
    } else if(
      status === 'NEW' ||
      status === 'PARTIALLY_FILLED'
    ) {
      return callback(undefined, { executed: false, open: true, filledAmount: +data.executedQty });
    } else if(status === 'FILLED') {
      return callback(undefined, { executed: true, open: false })
    }

    console.log('what status?', status);
    throw status;
  };

  const reqData = {
    symbol: this.pair,
    orderId: order,
  };

  const fetcher = cb => this.binance.queryOrder(reqData, this.handleResponse('checkOrder', cb));
  retry(undefined, fetcher, check);
};

Trader.prototype.cancelOrder = function(order, callback) {

  const cancel = (err, data) => {
    if(err) {
      return callback(err);
    }

    if(data && data.filled) {
      return callback(undefined, true);
    }

    return callback(undefined, false);
  };

  let reqData = {
    symbol: this.pair,
    orderId: order,
  };

  const fetcher = cb => this.binance.cancelOrder(reqData, this.handleResponse('cancelOrder', cb));
  retry(undefined, fetcher, cancel);
};

Trader.getCapabilities = function() {
  return {
    name: 'Binance',
    slug: 'binance',
    currencies: marketData.currencies,
    assets: marketData.assets,
    markets: marketData.markets,
    requires: ['key', 'secret'],
    providesHistory: 'date',
    providesFullHistory: true,
    tid: 'tid',
    tradable: true,
    gekkoBroker: 0.6
  };
};

module.exports = Trader;
<commit_msg>[GB] catch strange networking error<commit_after>const moment = require('moment');
const _ = require('lodash');

const Errors = require('../exchangeErrors');
const marketData = require('./binance-markets.json');
const retry = require('../exchangeUtils').retry;

const Binance = require('binance');

const Trader = function(config) {
  _.bindAll(this, [
    'roundAmount',
    'roundPrice',
    'isValidPrice',
    'isValidLot'
  ]);

  if (_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
    this.currency = config.currency.toUpperCase();
    this.asset = config.asset.toUpperCase();
  }

  let recvWindow = 6000;
  if(config.optimizedConnection) {
    // there is a bug in binance's API
    // where some requests randomly take
    // over a second, this tells binance
    // to bail out after 500ms.
    //
    // As discussed in binance API
    // telegram. TODO add link.
    recvWindow = 500;
  }

  this.pair = this.asset + this.currency;
  this.name = 'binance';

  this.market = _.find(Trader.getCapabilities().markets, (market) => {
    return market.pair[0] === this.currency && market.pair[1] === this.asset
  });

  this.binance = new Binance.BinanceRest({
    key: this.key,
    secret: this.secret,
    timeout: 15000,
    recvWindow,
    disableBeautification: false,
    handleDrift: true,
  });

  if(config.key && config.secret) {
    // Note non standard func:
    //
    // On binance we might pay fees in BNB
    // if we do we CANNOT calculate feePercent
    // since we don't track BNB price (when we
    // are not trading on a BNB market).
    //
    // Though we can deduce feePercent based
    // on user fee tracked through `this.getFee`.
    // Set default here, overwrite in getFee.
    this.fee = 0.1;
    // Set the proper fee asap.
    this.getFee(_.noop);
  }
};

const recoverableErrors = [
  'SOCKETTIMEDOUT',
  'TIMEDOUT',
  'CONNRESET',
  'CONNREFUSED',
  'NOTFOUND',
  'Error -1021',
  'Response code 429',
  'Response code 5',
  'Response code 403',
  'ETIMEDOUT',
  'EHOSTUNREACH'
];

const includes = (str, list) => {
  if(!_.isString(str))
    return false;

  return _.some(list, item => str.includes(item));
}

Trader.prototype.handleResponse = function(funcName, callback) {
  return (error, body) => {
    if (body && body.code) {
      error = new Error(`Error ${body.code}: ${body.msg}`);
    }

    if(error) {
      if(_.isString(error)) {
        error = new Error(error);
      }

      if(includes(error.message, recoverableErrors)) {
        error.notFatal = true;
      }

      if(funcName === 'cancelOrder' && error.message.includes('UNKNOWN_ORDER')) {
        // order got filled in full before it could be
        // cancelled, meaning it was NOT cancelled.
        return callback(false, {filled: true});
      }

      if(funcName === 'checkOrder' && error.message.includes('Order does not exist.')) {
        // order got filled in full before it could be
        // cancelled, meaning it was NOT cancelled.
        return callback(false, {filled: true});
      }

      return callback(error);
    }

    return callback(undefined, body);
  }
};

Trader.prototype.getTrades = function(since, callback, descending) {
  const processResults = (err, data) => {
    if (err) return callback(err);

    var parsedTrades = [];
    _.each(
      data,
      function(trade) {
        parsedTrades.push({
          tid: trade.aggTradeId,
          date: moment(trade.timestamp).unix(),
          price: parseFloat(trade.price),
          amount: parseFloat(trade.quantity),
        });
      },
      this
    );

    if (descending) callback(null, parsedTrades.reverse());
    else callback(undefined, parsedTrades);
  };

  var reqData = {
    symbol: this.pair,
  };

  if (since) {
    var endTs = moment(since)
      .add(1, 'h')
      .valueOf();
    var nowTs = moment().valueOf();

    reqData.startTime = moment(since).valueOf();
    reqData.endTime = endTs > nowTs ? nowTs : endTs;
  }

  const fetch = cb => this.binance.aggTrades(reqData, this.handleResponse('getTrades', cb));
  retry(undefined, fetch, processResults);
};

Trader.prototype.getPortfolio = function(callback) {
  const setBalance = (err, data) => {
    if (err) return callback(err);

    const findAsset = item => item.asset === this.asset;
    const assetAmount = parseFloat(_.find(data.balances, findAsset).free);

    const findCurrency = item => item.asset === this.currency;
    const currencyAmount = parseFloat(_.find(data.balances, findCurrency).free);

    if (!_.isNumber(assetAmount) || _.isNaN(assetAmount)) {
      assetAmount = 0;
    }

    if (!_.isNumber(currencyAmount) || _.isNaN(currencyAmount)) {
      currencyAmount = 0;
    }

    const portfolio = [
      { name: this.asset, amount: assetAmount },
      { name: this.currency, amount: currencyAmount },
    ];

    return callback(undefined, portfolio);
  };

  const fetch = cb => this.binance.account({}, this.handleResponse('getPortfolio', cb));
  retry(undefined, fetch, setBalance);
};

Trader.prototype.getFee = function(callback) {

  // binance does NOT tell us whether the user is using BNB to pay
  // for fees, which means a discount (effectively lower fees)
  const handle = (err, data) => {
    if(err)  {
      return callback(err);
    }

    const basepoints = data.makerCommission;

    // note non standard func, see constructor
    this.fee = basepoints / 100;

    callback(undefined, basepoints / 100);
  }

  const fetch = cb => this.binance.account({}, this.handleResponse('getFee', cb));
  retry(undefined, fetch, handle);
};

Trader.prototype.getTicker = function(callback) {
  const setTicker = (err, data) => {
    if (err)
      return callback(err);

    var result = _.find(data, ticker => ticker.symbol === this.pair);

    if(!result)
      return callback(new Error(`Market ${this.pair} not found on Binance`));

    var ticker = {
      ask: parseFloat(result.askPrice),
      bid: parseFloat(result.bidPrice),
    };

    callback(undefined, ticker);
  };

  const handler = cb => this.binance._makeRequest({}, this.handleResponse('getTicker', cb), 'api/v1/ticker/allBookTickers');
  retry(undefined, handler, setTicker);
};

// Effectively counts the number of decimal places, so 0.001 or 0.234 results in 3
Trader.prototype.getPrecision = function(tickSize) {
  if (!isFinite(tickSize)) return 0;
  var e = 1, p = 0;
  while (Math.round(tickSize * e) / e !== tickSize) { e *= 10; p++; }
  return p;
};

Trader.prototype.round = function(amount, tickSize) {
  var precision = 100000000;
  var t = this.getPrecision(tickSize);

  if(Number.isInteger(t))
    precision = Math.pow(10, t);

  amount *= precision;
  amount = Math.floor(amount);
  amount /= precision;

  // https://gist.github.com/jiggzson/b5f489af9ad931e3d186
  amount = this.scientificToDecimal(amount);

  return amount;
};

// https://gist.github.com/jiggzson/b5f489af9ad931e3d186
Trader.prototype.scientificToDecimal = function(num) {
  if(/\d+\.?\d*e[\+\-]*\d+/i.test(num)) {
    const zero = '0';
    const parts = String(num).toLowerCase().split('e'); // split into coeff and exponent
    const e = parts.pop(); // store the exponential part
    const l = Math.abs(e); // get the number of zeros
    const sign = e/l;
    const coeff_array = parts[0].split('.');
    if(sign === -1) {
      num = zero + '.' + new Array(l).join(zero) + coeff_array.join('');
    } else {
      const dec = coeff_array[1];
      if(dec) {
        l = l - dec.length;
      }
      num = coeff_array.join('') + new Array(l+1).join(zero);
    }
  } else {
    // make sure we always cast to string
    num = num + '';
  }

  return num;
}

Trader.prototype.roundAmount = function(amount) {
  return this.round(amount, this.market.minimalOrder.amount);
}

Trader.prototype.roundPrice = function(price) {
  return this.round(price, this.market.minimalOrder.price);
}

Trader.prototype.isValidPrice = function(price) {
  return price >= this.market.minimalOrder.price;
}

Trader.prototype.isValidLot = function(price, amount) {
  console.log('isValidLot', this.market.minimalOrder.order, amount * price >= this.market.minimalOrder.order)
  return amount * price >= this.market.minimalOrder.order;
}

Trader.prototype.outbidPrice = function(price, isUp) {
  let newPrice;

  if(isUp) {
    newPrice = price + this.market.minimalOrder.price;
  } else {
    newPrice = price - this.market.minimalOrder.price;
  }

  return this.roundPrice(newPrice);
}

Trader.prototype.addOrder = function(tradeType, amount, price, callback) {
  const setOrder = (err, data) => {
    if (err) return callback(err);

    const txid = data.orderId;

    callback(undefined, txid);
  };

  const reqData = {
    symbol: this.pair,
    side: tradeType.toUpperCase(),
    type: 'LIMIT',
    timeInForce: 'GTC',
    quantity: amount,
    price: price,
    timestamp: new Date().getTime()
  };

  const handler = cb => this.binance.newOrder(reqData, this.handleResponse('addOrder', cb));
  retry(undefined, handler, setOrder);
};

Trader.prototype.getOrder = function(order, callback) {
  const get = (err, data) => {
    if (err) return callback(err);

    let price = 0;
    let amount = 0;
    let date = moment(0);

    const fees = {};

    const trades = _.filter(data, t => {
      // note: the API returns a string after creating
      return t.orderId == order;
    });

    if(!trades.length) {
      return callback(new Error('Trades not found'));
    }

    _.each(trades, trade => {
      date = moment(trade.time);
      price = ((price * amount) + (+trade.price * trade.qty)) / (+trade.qty + amount);
      amount += +trade.qty;

      if(fees[trade.commissionAsset])
        fees[trade.commissionAsset] += (+trade.commission);
      else
        fees[trade.commissionAsset] = (+trade.commission);
    });

    let feePercent;
    if(_.keys(fees).length === 1) {
      if(fees.BNB && this.asset !== 'BNB' && this.currency !== 'BNB') {
        // we paid fees in BNB, right now that means the fee is always 75%
        // of base fee. We cannot calculate since we do not have the BNB rate.
        feePercent = this.fee * 0.75;
      } else {
        if(fees[this.asset]) {
          feePercent = fees[this.asset] / amount * 100;
        } else if(fees.currency) {
          feePercent = fees[this.currency] / price / amount * 100;
        } else {
          // use user fee of 10 basepoints
          feePercent = this.fee;
        }
      }
    } else {
      // we paid fees in multiple currencies?
      // assume user fee
      feePercent = this.fee;
    }

    callback(undefined, { price, amount, date, fees, feePercent });
  }

  const reqData = {
    symbol: this.pair,
    // if this order was not part of the last 500 trades we won't find it..
    limit: 500,
  };

  const handler = cb => this.binance.myTrades(reqData, this.handleResponse('getOrder', cb));
  retry(undefined, handler, get);
};

Trader.prototype.buy = function(amount, price, callback) {
  this.addOrder('buy', amount, price, callback);
};

Trader.prototype.sell = function(amount, price, callback) {
  this.addOrder('sell', amount, price, callback);
};

Trader.prototype.checkOrder = function(order, callback) {

  const check = (err, data) => {
    if (err) {
      return callback(err);
    }

    if(data.filled === true) {
      // binance responsed with order not found
      return callback(undefined, { executed: true, open: false });
    }

    const status = data.status;

    if(
      status === 'CANCELED' ||
      status === 'REJECTED' ||
      // for good measure: GB does not
      // submit orders that can expire yet
      status === 'EXPIRED'
    ) {
      return callback(undefined, { executed: false, open: false });
    } else if(
      status === 'NEW' ||
      status === 'PARTIALLY_FILLED'
    ) {
      return callback(undefined, { executed: false, open: true, filledAmount: +data.executedQty });
    } else if(status === 'FILLED') {
      return callback(undefined, { executed: true, open: false })
    }

    console.log('what status?', status);
    throw status;
  };

  const reqData = {
    symbol: this.pair,
    orderId: order,
  };

  const fetcher = cb => this.binance.queryOrder(reqData, this.handleResponse('checkOrder', cb));
  retry(undefined, fetcher, check);
};

Trader.prototype.cancelOrder = function(order, callback) {

  const cancel = (err, data) => {
    if(err) {
      return callback(err);
    }

    if(data && data.filled) {
      return callback(undefined, true);
    }

    return callback(undefined, false);
  };

  let reqData = {
    symbol: this.pair,
    orderId: order,
  };

  const fetcher = cb => this.binance.cancelOrder(reqData, this.handleResponse('cancelOrder', cb));
  retry(undefined, fetcher, cancel);
};

Trader.getCapabilities = function() {
  return {
    name: 'Binance',
    slug: 'binance',
    currencies: marketData.currencies,
    assets: marketData.assets,
    markets: marketData.markets,
    requires: ['key', 'secret'],
    providesHistory: 'date',
    providesFullHistory: true,
    tid: 'tid',
    tradable: true,
    gekkoBroker: 0.6
  };
};

module.exports = Trader;
<|endoftext|>


<commit_before>// const path = require('path');
// const slug = require('slug');
// const slash = require('slash');
// const { getHumanDate } = require('../utils/date');

// const podcastPageTemplate = path.resolve(
//   process.cwd(),
//   './src/components/podcast.js'
// );
// const postTemplate = path.resolve(
//   process.cwd(),
//   './src/components/podcast-page/index.js'
// );

// exports.createPages = async ({ graphql, boundActionCreators }) => {
//   const { createPage } = boundActionCreators;

//   const result = await graphql(
//     `
//       {
//         allContentfulDrinkcast(
//           limit: 1000
//           sort: { order: DESC, fields: [date] }
//         ) {
//           edges {
//             node {
//               number
//               file
//               title
//               date
//               notes {
//                 notes
//               }
//             }
//           }
//         }
//       }
//     `
//   );
//   if (result.errors) {
//     throw new Error(result.errors);
//   }

//   const finalEdges = result.data.allContentfulDrinkcast.edges.map(edge => {
//     return {
//       node: Object.assign({}, edge.node, {
//         formatedDate: getHumanDate(edge.node.date)
//       })
//     };
//   });

//   createPage({
//     path: '/podcast',
//     component: slash(podcastPageTemplate),
//     context: {
//       data: { episodes: finalEdges }
//     }
//   });

//   finalEdges.forEach(({ node }, id) => {
//     createPage({
//       path: `/podcast/${slug(node.number)}`,
//       component: slash(postTemplate),
//       context: {
//         data: node,
//         id
//       }
//     });
//   });
// };

exports.createPages = async gatsby => {
  await require('./podcast')(gatsby);
  await require('./person')(gatsby);
  return Promise.resolve();
};
<commit_msg>Deleted comments<commit_after>exports.createPages = async gatsby => {
  await require('./podcast')(gatsby);
  await require('./person')(gatsby);
  return Promise.resolve();
};
<|endoftext|>


<commit_before><commit_msg>Eslint<commit_after><|endoftext|>


<commit_before>// Data

var standard_licenses_datasets = [{"label": "Standard license","color":"#185288","value": 166}, {"label": "Non-standard license","color":"#CCCCCC","value": 11806}];
var standard_licenses_occurrences = [{"label": "Standard license","color":"#185288","value": 9899370}, {"label": "Non-standard license","color":"#CCCCCC","value": 405513274}];

// Add charts to HTML

addPieChart("#chart1","Datasets",standard_licenses_datasets);
addPieChart("#chart2","Occurrences",standard_licenses_occurrences);

// Plot the usage per dataset

nv.addGraph(function() {
var chart = nv.models.multiBarChart()
    .x(function(d) {return d.label})
    .y(function(d) {return d.value})
    //.staggerLabels(true)
    //.tooltips(false)
    //.showValues(true)
    .transitionDuration(100)
    .stacked(true);

d3.select("#chart3")
.datum([{'color': '#03AD0F', 'values': [{'value': 905, 'label': 'usage'}, {'value': 647, 'label': 'distribution'}, {'value': 731, 'label': 'derivatives'}, {'value': 582, 'label': 'commercial'}, {'value': 213, 'label': 'attribution'}, {'value': 178, 'label': 'share alike'}, {'value': 738, 'label': 'notification'}], 'key': 'yes'}, {'color': '#9E9E9E', 'values': [{'value': 10980, 'label': 'usage'}, {'value': 10975, 'label': 'distribution'}, {'value': 10998, 'label': 'derivatives'}, {'value': 11098, 'label': 'commercial'}, {'value': 11139, 'label': 'attribution'}, {'value': 11761, 'label': 'share alike'}, {'value': 11056, 'label': 'notification'}], 'key': 'unknown'}, {'color': '#ED0000', 'values': [{'value': 87, 'label': 'usage'}, {'value': 350, 'label': 'distribution'}, {'value': 243, 'label': 'derivatives'}, {'value': 292, 'label': 'commercial'}, {'value': 620, 'label': 'attribution'}, {'value': 33, 'label': 'share alike'}, {'value': 178, 'label': 'notification'}], 'key': 'no'}]
)
.transition()
.duration(500)
.call(chart);

nv.utils.windowResize(chart.update);

return chart;

} );

// Plot the usage per occurrence

nv.addGraph(function() {
var chart = nv.models.multiBarChart()
    .x(function(d) {return d.label})
    .y(function(d) {return d.value})
    //.staggerLabels(true)
    //.tooltips(false)
    //.showValues(true)
    .transitionDuration(100)
    .stacked(true);

d3.select("#chart4")
.datum([{'color': '#03AD0F', 'values': [{'value': 69775276, 'label': 'usage'}, {'value': 54581128, 'label': 'distribution'}, {'value': 62048951, 'label': 'derivatives'}, {'value': 46952477, 'label': 'commercial'}, {'value': 15075888, 'label': 'attribution'}, {'value': 19026470, 'label': 'share alike'}, {'value': 60420353, 'label': 'notification'}], 'key': 'yes'}, {'color': '#9E9E9E', 'values': [{'value': 343204732, 'label': 'usage'}, {'value': 343830898, 'label': 'distribution'}, {'value': 339051254, 'label': 'derivatives'}, {'value': 339168747, 'label': 'commercial'}, {'value': 333938837, 'label': 'attribution'}, {'value': 395366713, 'label': 'share alike'}, {'value': 332509768, 'label': 'notification'}], 'key': 'unknown'}, {'color': '#ED0000', 'values': [{'value': 2432636, 'label': 'usage'}, {'value': 17000618, 'label': 'distribution'}, {'value': 14312439, 'label': 'derivatives'}, {'value': 29291420, 'label': 'commercial'}, {'value': 66397919, 'label': 'attribution'}, {'value': 1019461, 'label': 'share alike'}, {'value': 22482523, 'label': 'notification'}], 'key': 'no'}])
.transition()
.duration(500)
.call(chart);

nv.utils.windowResize(chart.update);

return chart;

} );

// Functions

function addPieChart(element,title,data) {
    // Use this patch for colors to work: https://github.com/novus/nvd3/commit/7dcb8d899bbe6279a71c25e9ea309344924029b9
    nv.addGraph(function() {
        var chart = nv.models.pieChart()
        .x(function(d) {return d.label })
        .y(function(d) {return d.value })
        .valueFormat(d3.format(',.0f'))
        .showLabels(false)
        .donut(true);

        d3.select(element)
        .datum(data)
        .transition()
        .duration(1200)
        .call(chart);

        d3.select(element)
        .append("text")
        .attr("x","50%")
        .attr("y","52%")
        .attr("text-anchor","middle")
        .attr("class","title")
        .text(title);

        return chart;
    });
}
<commit_msg>Move 2 chart functions to one general addBarChart()<commit_after>// Data

var standard_licenses_datasets = [{"label": "Standard license","color":"#185288","value": 166}, {"label": "Non-standard license","color":"#CCCCCC","value": 11806}];
var standard_licenses_occurrences = [{"label": "Standard license","color":"#185288","value": 9899370}, {"label": "Non-standard license","color":"#CCCCCC","value": 405513274}];
var general_use_parameters_datasets = [{'color': '#03AD0F', 'values': [{'value': 905, 'label': 'usage'}, {'value': 647, 'label': 'distribution'}, {'value': 731, 'label': 'derivatives'}, {'value': 582, 'label': 'commercial'}, {'value': 213, 'label': 'attribution'}, {'value': 178, 'label': 'share alike'}, {'value': 738, 'label': 'notification'}], 'key': 'yes'}, {'color': '#9E9E9E', 'values': [{'value': 10980, 'label': 'usage'}, {'value': 10975, 'label': 'distribution'}, {'value': 10998, 'label': 'derivatives'}, {'value': 11098, 'label': 'commercial'}, {'value': 11139, 'label': 'attribution'}, {'value': 11761, 'label': 'share alike'}, {'value': 11056, 'label': 'notification'}], 'key': 'unknown'}, {'color': '#ED0000', 'values': [{'value': 87, 'label': 'usage'}, {'value': 350, 'label': 'distribution'}, {'value': 243, 'label': 'derivatives'}, {'value': 292, 'label': 'commercial'}, {'value': 620, 'label': 'attribution'}, {'value': 33, 'label': 'share alike'}, {'value': 178, 'label': 'notification'}], 'key': 'no'}];
var general_use_parameters_occurrences = [{'color': '#03AD0F', 'values': [{'value': 69775276, 'label': 'usage'}, {'value': 54581128, 'label': 'distribution'}, {'value': 62048951, 'label': 'derivatives'}, {'value': 46952477, 'label': 'commercial'}, {'value': 15075888, 'label': 'attribution'}, {'value': 19026470, 'label': 'share alike'}, {'value': 60420353, 'label': 'notification'}], 'key': 'yes'}, {'color': '#9E9E9E', 'values': [{'value': 343204732, 'label': 'usage'}, {'value': 343830898, 'label': 'distribution'}, {'value': 339051254, 'label': 'derivatives'}, {'value': 339168747, 'label': 'commercial'}, {'value': 333938837, 'label': 'attribution'}, {'value': 395366713, 'label': 'share alike'}, {'value': 332509768, 'label': 'notification'}], 'key': 'unknown'}, {'color': '#ED0000', 'values': [{'value': 2432636, 'label': 'usage'}, {'value': 17000618, 'label': 'distribution'}, {'value': 14312439, 'label': 'derivatives'}, {'value': 29291420, 'label': 'commercial'}, {'value': 66397919, 'label': 'attribution'}, {'value': 1019461, 'label': 'share alike'}, {'value': 22482523, 'label': 'notification'}], 'key': 'no'}];

// Add charts to HTML

addPieChart("#chart1","Datasets",standard_licenses_datasets);
addPieChart("#chart2","Occurrences",standard_licenses_occurrences);
addBarChart("#chart3","Datasets",general_use_parameters_datasets);
addBarChart("#chart4","Occurrences",general_use_parameters_occurrences);

// Functions

function addPieChart(element,title,data) {
    // Use this patch for colors to work: https://github.com/novus/nvd3/commit/7dcb8d899bbe6279a71c25e9ea309344924029b9
    nv.addGraph(function() {
        var chart = nv.models.pieChart()
        .x(function(d) {return d.label })
        .y(function(d) {return d.value })
        .valueFormat(d3.format(',.0f'))
        .showLabels(false)
        .donut(true);

        d3.select(element)
        .datum(data)
        .transition()
        .duration(1200)
        .call(chart);

        d3.select(element)
        .append("text")
        .attr("x","50%")
        .attr("y","52%")
        .attr("text-anchor","middle")
        .attr("class","title")
        .text(title);

        return chart;
    });
}

function addBarChart(element,title,data) {
    nv.addGraph(function() {
        var chart = nv.models.multiBarChart()
        .x(function(d) {return d.label})
        .y(function(d) {return d.value})
        //.staggerLabels(true)
        //.tooltips(false)
        //.showValues(true)
        .transitionDuration(100)
        .stacked(true);

        d3.select(element)
        .datum(data)
        .transition()
        .duration(500)
        .call(chart);

        nv.utils.windowResize(chart.update);

        return chart;
    });
}
<|endoftext|>


<commit_before>function encipher() {
    var plainText = $('#plaintext').val();
    var cipherText = '';
    if ($(':radio[value=caesar]').is(':checked')) {
        var direction = $('input[name=shiftDirection]:checked').val();
        var shift = parseInt($('#inputShift').val());
        cipherText = caesarCipher(direction, shift, plainText);
        console.log(cipherText);
        return;
    }
    if ($(':radio[value=subst]').is(':checked')) {
        cipherText = substCipher(plainText);
        console.log(cipherText);
        return;
    }
}

function substCipher(text) {
    var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var alphaTemp = alpha;
    var randAlpha = '';
    var plainText = text.toUpperCase();
    var cipherText = '';

    //randomizes alphabet
    while (alphaTemp.length > 0) {
        var letter = alphaTemp.charAt(Math.floor(Math.random() * alphaTemp.length));
        randAlpha += letter;
        //remove letter from alphaTemp
        alphaTemp = alphaTemp.replace(letter, '', 'g');
    }

    for (var i = 0; i < plainText.length; i++) {
        var plainLetter = plainText.charAt(i);
        var alphaIndex = alpha.indexOf(plainLetter);
        if (alphaIndex >= 0) {
            cipherText += randAlpha.charAt(alphaIndex);
        }
        else {
            cipherText += plainLetter;
        }
    }
    return cipherText;
}

function caesarCipher(direction, shift, text) {
    var plainText = text.toUpperCase();
    var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var cipherText = '';
    if (direction == "left") {
        shift = -shift;
    }
    for (var i = 0; i < plainText.length; i++) {
        var plainLetter = plainText.charAt(i);
        var alphaIndex = alpha.indexOf(plainLetter);
        if (alphaIndex >= 0) {
            if (alphaIndex + shift >= 0) {
                cipherText += alpha.charAt((alphaIndex + shift) % alpha.length);
            }
            else {
                alphaIndex = alphaIndex + alpha.length;
                cipherText += alpha.charAt((alphaIndex + shift) % alpha.length);
            }
        }
        else {
            cipherText += plainLetter;
        }
    }
    return cipherText;
}
<commit_msg>simplified wraparound code<commit_after>function encipher() {
    var plainText = $('#plaintext').val();
    var cipherText = '';
    if ($(':radio[value=caesar]').is(':checked')) {
        var direction = $('input[name=shiftDirection]:checked').val();
        var shift = parseInt($('#inputShift').val());
        cipherText = caesarCipher(direction, shift, plainText);
        console.log(cipherText);
        return;
    }
    if ($(':radio[value=subst]').is(':checked')) {
        cipherText = substCipher(plainText);
        console.log(cipherText);
        return;
    }
}

function substCipher(text) {
    var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var alphaTemp = alpha;
    var randAlpha = '';
    var plainText = text.toUpperCase();
    var cipherText = '';

    //randomizes alphabet
    while (alphaTemp.length > 0) {
        var letter = alphaTemp.charAt(Math.floor(Math.random() * alphaTemp.length));
        randAlpha += letter;
        //remove letter from alphaTemp
        alphaTemp = alphaTemp.replace(letter, '', 'g');
    }

    for (var i = 0; i < plainText.length; i++) {
        var plainLetter = plainText.charAt(i);
        var alphaIndex = alpha.indexOf(plainLetter);
        if (alphaIndex >= 0) {
            cipherText += randAlpha.charAt(alphaIndex);
        }
        else {
            cipherText += plainLetter;
        }
    }
    return cipherText;
}

function caesarCipher(direction, shift, text) {
    var plainText = text.toUpperCase();
    var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var cipherText = '';
    if (direction == "left") {
        shift = -shift;
    }
    for (var i = 0; i < plainText.length; i++) {
        var plainLetter = plainText.charAt(i);
        var alphaIndex = alpha.indexOf(plainLetter);
        if (alphaIndex >= 0) {
            alphaIndex = alphaIndex + alpha.length;
            cipherText += alpha.charAt((alphaIndex + shift) % alpha.length);
        }
        else {
            cipherText += plainLetter;
        }
    }
    return cipherText;
}
<|endoftext|>


<commit_before>const black =         '#4a4a4a';
const blackLight =    '#636363';
const blue =          '#073e9b';
const blueDark =      '#05317D';
const blueLight =     '#3864af';
const blueMuted =     '#839ecd';
const gray =          '#9e9e9e';
const grayLight =     '#b0b0b0';
const grayLightest =  '#cacaca';
const grayDark =      '#707070';
const green =         '#006634';
const greenLight =    '#32845c';
const greenMuted =    '#99c1ad';
const pink =          '#9b073e';
const white =         '#f8f5f3';
const whiteMed =      '#efe8e3';
const whiteDark =     '#e6dbd3';

module.exports = {
  $black: black,
  $blackLight: blackLight,
  $blackLightest: gray,
  $gray: gray,
  $grayLight: grayLight,
  $grayLightest: grayLightest,
  $green: green,
  $greenLight: greenLight,
  $greenMuted: greenMuted,
  $white: white,
  $whiteMed: whiteMed,
  $whiteDark: whiteDark,
  $blue: blue,
  $blueDark: blueDark,
  $blueLight: blueLight,
  $blueMuted: blueMuted,
  $pink: pink,
  $footerHeight: '200px',
  $linkTransition: 'all 250ms ease',
  $linkTransitionSpeed: '250ms',
  $mapHeight: '300px',
  $marginMd: '20px',
  $marginLg: '30px',
  $btnSubmit: blue,
  $btnAction: green,
  $borderRadius: '5px',
  $map: {
    colors: {
      bar: blueDark,
      food: green,
      fun: greenLight,
      music: blueLight
    }
  }
};
<commit_msg>Greens changed<commit_after>const black =         '#4a4a4a';
const blackLight =    '#636363';
const blue =          '#073e9b';
const blueDark =      '#05317D';
const blueLight =     '#3864af';
const blueMuted =     '#839ecd';
const gray =          '#9e9e9e';
const grayLight =     '#b0b0b0';
const grayLightest =  '#cacaca';
const grayDark =      '#707070';
const green =         '#016735';
const greenLight =    '#4d9471';
const greenMuted =    '#99c1ad';
const pink =          '#9b073e';
const white =         '#f8f5f3';
const whiteMed =      '#efe8e3';
const whiteDark =     '#dccdc3';

module.exports = {
  $black: black,
  $blackLight: blackLight,
  $blackLightest: gray,
  $gray: gray,
  $grayDark: grayDark,
  $grayLight: grayLight,
  $grayLightest: grayLightest,
  $green: green,
  $greenLight: greenLight,
  $greenMuted: greenMuted,
  $white: white,
  $whiteMed: whiteMed,
  $whiteDark: whiteDark,
  $blue: blue,
  $blueDark: blueDark,
  $blueLight: blueLight,
  $blueMuted: blueMuted,
  $pink: pink,
  $footerHeight: '200px',
  $linkTransition: 'all 250ms ease',
  $linkTransitionSpeed: '250ms',
  $mapHeight: '300px',
  $marginMd: '20px',
  $marginLg: '30px',
  $btnSubmit: blue,
  $btnAction: green,
  $borderRadius: '5px',
  $map: {
    colors: {
      bar: blueDark,
      food: green,
      fun: greenLight,
      music: blueLight
    }
  }
};
<|endoftext|>


<commit_before>$(function () {
    // start by hiding icons
    $(".wallItemMainHolder .commentInnerBtn").hide();
    $(".wallItemMainHolder .reactInnerBtn").hide();

    // handle picture opening
    $(".fancybox-image").fancybox({
        'titleShow': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'easingIn': 'easeOutBack',
        'easingOut': 'easeInBack'
    });

    // handle media play global selector
    $('.wallItemMainHolder').on('click', '.multimedia-main-action:not(.fancybox-image)', playMedia);
    $('.wallItemMainHolder').on('click', '.small-multimedia-main-action:not(.fancybox-image)', playMedia);

    $("#Search-form-button").click(function (e) {
        if (!$("#search-form-text").children().first().val()) {
            window.location = "/Search/Index";
            e.preventDefault();
            return false;
        }
    });

    function playMedia(mediaHolderLink) {
        mediaHolderLink.preventDefault();
        var dataSet = $(mediaHolderLink.currentTarget.dataset)[0];
        if (!dataSet) {
            dataSet = $($(mediaHolderLink.currentTarget).parent()).dataset[0];
        }

        var dataSrc = dataSet.contentSrc;
        var dataType = dataSet.contentType;

        var audioPlayer = $('#modalContentPlayerHolder .audio-player');
        var videoPlayer = $('#modalContentPlayerHolder .video-player');

        if (dataType == 'Video') {
            audioPlayer.hide();
            videoPlayer.show().attr('src', dataSrc);

            $('#modalContentPlayerHolder').modal('show');
        }
        else if (dataType == 'Sound') {
            videoPlayer.hide();
            audioPlayer.show().attr('src', dataSrc);

            audioPlayer[0].pause();
            audioPlayer[0].load();//suspends and restores all audio element
            audioPlayer[0].play();

            $('#modalContentPlayerHolder').modal('show');
        }
    }

    // stop media on modal closing
    $("#modalContentPlayerHolder").on('hidden.bs.modal', function () {
        $('#modalContentPlayerHolder .audio-player')[0].pause();
        $('#modalContentPlayerHolder .video-player')[0].pause();
    });

    // click for more
    var skip = 5;
    var contentReciever = $("#main-content-reciever");
    var contentClickBtn = $("#click-for-more-btn");
    contentClickBtn.click(function () {
        contentClickBtn.slideUp();
        contentReciever.append($(''));
        var token = { __RequestVerificationToken: $('#hiddenAjaxPostForm input').val() };

        var url = "/Home/More/" + skip;

        var indexOfDetails = window.location.href.indexOf('Details/');
        if (indexOfDetails >= 0) {
            url = "/Profile/More/" + skip + "/" + window.location.href.substr(window.location.href.indexOf('Details/') + 8, 36);
        }

        $.post(url, token, function (response) {
            contentReciever.children().last().remove();
            contentReciever.append(response);

            $(".fancybox-image").fancybox({
                'titleShow': false,
                'transitionIn': 'elastic',
                'transitionOut': 'elastic',
                'easingIn': 'easeOutBack',
                'easingOut': 'easeInBack'
            });

            contentClickBtn.slideDown();
        });
        skip += 5;
    });

    // animate buttons
    $('body').on('click', ".wallItemMainHolder .commentBtn", function (e) {
        var self = $(this);
        window.wallItemHolderClickedId = self.parent().parent().data("wall-item-id");

        var other = self.parent().parent().children().children('.reactInnerBtn');
        self.parent().parent().children().children('.commentBtn').transition({ x: 0 });;
        $(other[0]).transition({ x: 0 });
        $(other[1]).transition({ x: 100 });
        $(other[2]).transition({ x: 200 });
        other.hide();

        var own = self.siblings().show();
        self.transition({ x: -110 });
        $(own[0]).transition({ x: -90 });
        $(own[1]).transition({ x: 12 });
        $(own[2]).transition({ x: 115 });
    });

    $('body').on('click', ".wallItemMainHolder .reactBtn", function (e) {
        var self = $(this);
        window.wallItemHolderClickedId = self.parent().parent().data("wall-item-id");

        var other = self.parent().parent().children().children('.commentInnerBtn');
        self.parent().parent().children().children('.reactBtn').transition({ x: 0 });
        $(other[0]).transition({ x: 90 });
        $(other[1]).transition({ x: -12 });
        $(other[2]).transition({ x: -115 });
        other.hide();

        var own = self.siblings().show();
        self.transition({ x: 105 });
        $(own[0]).transition({ x: 0 });
        $(own[1]).transition({ x: -100 });
        $(own[2]).transition({ x: -200 });
    });

    // attach events to buttons
    $('body').on('click', '.main-create-comment-holder .voiceBtn', function () {
        initAudio();
        $('#modalVoiceWindowMain').modal('show');
    });

    $('body').on('click', '.new-content-voice', function () {
        initAudio();
    });

    $('body').on('click', '.main-create-comment-holder .pictureBtn', function () {
        $('#modalPictureWindowMain').modal('show');
    });

    $('body').on('click', '.main-create-comment-holder .videoBtn', function () {
        $('#modalVideoWindowMain').modal('show');
    });

    $('body').on('click', '.main-create-comment-holder .likeBtn', function () {
        window.voiceWallAjax.react.like(window.wallItemHolderClickedId);
    });

    $('body').on('click', '.main-create-comment-holder .hateBtn', function () {
        window.voiceWallAjax.react.hate(window.wallItemHolderClickedId);
    });

    $('body').on('click', '.main-create-comment-holder .flagBtn', function () {
        window.voiceWallAjax.react.flag(window.wallItemHolderClickedId);
    });

    $('body').on('click', '.main-comments-holder .flagCommentBtn', function () {
        window.voiceWallAjax.react.flagComment($(this).parent().parent().data("wall-item-comment-id"));
    });

    // upload content
    $('.inputUploadedPictureBtnSrc').click(function (e) {
        e.preventDefault();
        $('.inputUploadedPictureBtn').click();
    });

    $('.sendUploadedPictureBtnSrc').click(function () {
        window.voiceWallAjax.comment.withPicture($(".inputUploadedPictureBtn")[0].files[0], window.wallItemHolderClickedId);
    });

    $('.inputUploadedVideoBtnSrc').click(function (e) {
        e.preventDefault();
        $('.inputUploadedVideoBtn').click();
    });

    $('.sendUploadedVideoBtnSrc').click(function () {
        window.voiceWallAjax.comment.withVideo($(".inputUploadedVideoBtn")[0].files[0], window.wallItemHolderClickedId);
    });

    $('.inputUploadedVoiceBtnSrc').click(function (e) {
        e.preventDefault();
        $('.inputUploadedVoiceBtn').click();
    });

    $('.sendUploadedVoiceBtnSrc').click(function () {
        window.voiceWallAjax.comment.withSound($(".inputUploadedVoiceBtn")[0].files[0], window.wallItemHolderClickedId);
    });

    $("#add-post-btn").click(function () {
        window.wallItemHolderClickedId = undefined;
    });
});<commit_msg>No more content changing of the button added<commit_after>$(function () {
    // start by hiding icons
    $(".wallItemMainHolder .commentInnerBtn").hide();
    $(".wallItemMainHolder .reactInnerBtn").hide();

    // handle picture opening
    $(".fancybox-image").fancybox({
        'titleShow': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'easingIn': 'easeOutBack',
        'easingOut': 'easeInBack'
    });

    // handle media play global selector
    $('.wallItemMainHolder').on('click', '.multimedia-main-action:not(.fancybox-image)', playMedia);
    $('.wallItemMainHolder').on('click', '.small-multimedia-main-action:not(.fancybox-image)', playMedia);

    $("#Search-form-button").click(function (e) {
        if (!$("#search-form-text").children().first().val()) {
            window.location = "/Search/Index";
            e.preventDefault();
            return false;
        }
    });

    function playMedia(mediaHolderLink) {
        mediaHolderLink.preventDefault();
        var dataSet = $(mediaHolderLink.currentTarget.dataset)[0];
        if (!dataSet) {
            dataSet = $($(mediaHolderLink.currentTarget).parent()).dataset[0];
        }

        var dataSrc = dataSet.contentSrc;
        var dataType = dataSet.contentType;

        var audioPlayer = $('#modalContentPlayerHolder .audio-player');
        var videoPlayer = $('#modalContentPlayerHolder .video-player');

        if (dataType == 'Video') {
            audioPlayer.hide();
            videoPlayer.show().attr('src', dataSrc);

            $('#modalContentPlayerHolder').modal('show');
        }
        else if (dataType == 'Sound') {
            videoPlayer.hide();
            audioPlayer.show().attr('src', dataSrc);

            audioPlayer[0].pause();
            audioPlayer[0].load();//suspends and restores all audio element
            audioPlayer[0].play();

            $('#modalContentPlayerHolder').modal('show');
        }
    }

    // stop media on modal closing
    $("#modalContentPlayerHolder").on('hidden.bs.modal', function () {
        $('#modalContentPlayerHolder .audio-player')[0].pause();
        $('#modalContentPlayerHolder .video-player')[0].pause();
    });

    // click for more
    var skip = 5;
    var contentReciever = $("#main-content-reciever");
    var contentClickBtn = $("#click-for-more-btn");
    contentClickBtn.click(function () {
        contentClickBtn.slideUp();
        contentReciever.append($(''));
        var token = { __RequestVerificationToken: $('#hiddenAjaxPostForm input').val() };

        var url = "/Home/More/" + skip;

        var indexOfDetails = window.location.href.indexOf('Details/');
        if (indexOfDetails >= 0) {
            url = "/Profile/More/" + skip + "/" + window.location.href.substr(window.location.href.indexOf('Details/') + 8, 36);
        }

        $.post(url, token, function (response) {
            contentReciever.children().last().remove();
            contentReciever.append(response);

            $(".fancybox-image").fancybox({
                'titleShow': false,
                'transitionIn': 'elastic',
                'transitionOut': 'elastic',
                'easingIn': 'easeOutBack',
                'easingOut': 'easeInBack'
            });

            contentClickBtn.slideDown();

            if (!response) {
                contentClickBtn.text("No more content");
            }
        });
        skip += 5;
    });

    // animate buttons
    $('body').on('click', ".wallItemMainHolder .commentBtn", function (e) {
        var self = $(this);
        window.wallItemHolderClickedId = self.parent().parent().data("wall-item-id");

        var other = self.parent().parent().children().children('.reactInnerBtn');
        self.parent().parent().children().children('.commentBtn').transition({ x: 0 });;
        $(other[0]).transition({ x: 0 });
        $(other[1]).transition({ x: 100 });
        $(other[2]).transition({ x: 200 });
        other.hide();

        var own = self.siblings().show();
        self.transition({ x: -110 });
        $(own[0]).transition({ x: -90 });
        $(own[1]).transition({ x: 12 });
        $(own[2]).transition({ x: 115 });
    });

    $('body').on('click', ".wallItemMainHolder .reactBtn", function (e) {
        var self = $(this);
        window.wallItemHolderClickedId = self.parent().parent().data("wall-item-id");

        var other = self.parent().parent().children().children('.commentInnerBtn');
        self.parent().parent().children().children('.reactBtn').transition({ x: 0 });
        $(other[0]).transition({ x: 90 });
        $(other[1]).transition({ x: -12 });
        $(other[2]).transition({ x: -115 });
        other.hide();

        var own = self.siblings().show();
        self.transition({ x: 105 });
        $(own[0]).transition({ x: 0 });
        $(own[1]).transition({ x: -100 });
        $(own[2]).transition({ x: -200 });
    });

    // attach events to buttons
    $('body').on('click', '.main-create-comment-holder .voiceBtn', function () {
        initAudio();
        $('#modalVoiceWindowMain').modal('show');
    });

    $('body').on('click', '.new-content-voice', function () {
        initAudio();
    });

    $('body').on('click', '.main-create-comment-holder .pictureBtn', function () {
        $('#modalPictureWindowMain').modal('show');
    });

    $('body').on('click', '.main-create-comment-holder .videoBtn', function () {
        $('#modalVideoWindowMain').modal('show');
    });

    $('body').on('click', '.main-create-comment-holder .likeBtn', function () {
        window.voiceWallAjax.react.like(window.wallItemHolderClickedId);
    });

    $('body').on('click', '.main-create-comment-holder .hateBtn', function () {
        window.voiceWallAjax.react.hate(window.wallItemHolderClickedId);
    });

    $('body').on('click', '.main-create-comment-holder .flagBtn', function () {
        window.voiceWallAjax.react.flag(window.wallItemHolderClickedId);
    });

    $('body').on('click', '.main-comments-holder .flagCommentBtn', function () {
        window.voiceWallAjax.react.flagComment($(this).parent().parent().data("wall-item-comment-id"));
    });

    // upload content
    $('.inputUploadedPictureBtnSrc').click(function (e) {
        e.preventDefault();
        $('.inputUploadedPictureBtn').click();
    });

    $('.sendUploadedPictureBtnSrc').click(function () {
        window.voiceWallAjax.comment.withPicture($(".inputUploadedPictureBtn")[0].files[0], window.wallItemHolderClickedId);
    });

    $('.inputUploadedVideoBtnSrc').click(function (e) {
        e.preventDefault();
        $('.inputUploadedVideoBtn').click();
    });

    $('.sendUploadedVideoBtnSrc').click(function () {
        window.voiceWallAjax.comment.withVideo($(".inputUploadedVideoBtn")[0].files[0], window.wallItemHolderClickedId);
    });

    $('.inputUploadedVoiceBtnSrc').click(function (e) {
        e.preventDefault();
        $('.inputUploadedVoiceBtn').click();
    });

    $('.sendUploadedVoiceBtnSrc').click(function () {
        window.voiceWallAjax.comment.withSound($(".inputUploadedVoiceBtn")[0].files[0], window.wallItemHolderClickedId);
    });

    $("#add-post-btn").click(function () {
        window.wallItemHolderClickedId = undefined;
    });
});<|endoftext|>


<commit_before>/*
 Copyright 2014-2015 by CLEARWAVE DESIGNS, LLC.

 Licensed under the Apache License, Version 2.0
 http://www.apache.org/licenses/LICENSE-2.0

 Author:        Adam Carson
 Website:       http://clearwavedesigns.com
 Dependencies:  jquery.js (1.8.3+)

 Name(s):       FlagstoneJS (flagstone.js)
 Version:       1.2.20150720
 Slogan:        "Responsive tiling."
 Description:   Responsively tiles HTML elements left to right, top to bottom, and where there's the most room.
 */

var FLAGSTONE = function(settings) {

  var that = this;

  var o = settings || {};
  // AREA (CONTAINER)
  this.areaStr = o.area || '[flagstones]';
  this.area = $(this.areaStr);
  this.areaMargin = o.margin || o.margin === 0 ? o.margin : o.areaMargin || o.areaMargin === 0 ? o.areaMargin : 10;
  this.areaWidth = this.area.outerWidth();
  this.areaHeight = this.area.outerHeight();
  // MIN WIDTH
  this.minWidth = o.minWidth || 280;
  // COLUMNS
  this.maxColumns = o.maxColumns || 1920;
  this.calcColumns = Math.floor(this.areaWidth / this.minWidth);
  this.columns = this.calcColumns > this.maxColumns ? this.maxColumns : this.calcColumns;
  // MARGIN
  this.margin = o.margin || o.margin === 0 ? o.margin : 10;
  // FLAGSTONES
  this.flagstonesStr = o.flagstones || '[flagstone]';
  this.flagstones = $(this.flagstonesStr);
  this.flagstonesMargin = o.margin || o.margin === 0 ? o.margin : o.flagstonesMargin || o.flagstonesMargin === 0 ? o.flagstonesMargin : 10;
  this.flagstoneHeights = [];
  this.flagstoneWidth = (this.areaWidth / this.columns) - ((this.margin * (this.columns + 1)) / this.columns);
  // DIRECTION
  this.direction = o.direction ? o.direction.toLowerCase() : 'left';
  // ANIMATION
  this.duration = o.duration / 1000 || 0;
  this.jqueryAnimation = o.jqueryAnimation;
  // RESIZE/RESET DELAY
  this.resizeDelay = o.resizeDelay || 0;
  // HIDE (for Developers as well when then are injecting new content onto their page, so they can hide the flagstones before they get a change to re-calculate);
  this.hide = function() {
    // Must use "that" because "this" binding only works inside the function and not when call by the Dev outside of it using their instance of it
    this.area.addClass('flagstones-hidden');
  };

  // RUN
  this.run = function() {
    var columnHeights = new Array(this.columns);
    for (var i = 0, l = this.flagstoneHeights.length; i < l; i++) {
      if (i < this.columns) {
        // First "row"
        for (var ii = 0, ll = this.columns; ii < ll; ii++) {
          if (this.jqueryAnimation) {
            this.flagstones.eq(ii).animate({
              'top': this.areaMargin + 'px',
              'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px',
              'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px'
            }, this.duration * 1000);
          } else {
            this.flagstones.eq(ii).css({
              'top': this.areaMargin + 'px',
              'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px',
              'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px'
            });
          }
          columnHeights[ii] = this.flagstoneHeights[ii] + this.areaMargin;
        }
      } else {
        // Every other "row"
        var smallestColumnHeight = Math.min.apply(null, columnHeights);
        var smallestColumn = columnHeights.indexOf(smallestColumnHeight);
        if (this.jqueryAnimation) {
          this.flagstones.eq(i).animate({
            'top': (smallestColumnHeight + this.flagstonesMargin) + 'px',
            'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px',
            'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px'
          }, this.duration * 1000);
        } else {
          this.flagstones.eq(i).css({
            'top': (smallestColumnHeight + this.flagstonesMargin) + 'px',
            'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px',
            'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px'
          });
        }
        columnHeights[smallestColumn] += this.flagstoneHeights[i] + this.flagstonesMargin;
      }
      this.area.css('height', (Math.max.apply(null, columnHeights) || this.flagstoneHeights[0] + this.areaMargin) + this.areaMargin + 'px');
    }
    setTimeout(function() {
      that.area.removeClass('flagstones-hidden');
    }, 0);
  };
  // RESIZE AND RESET
  this.resetDelay1;
  this.resetDelay2;
  this.resetDelay3;
  this.reset = function() {
    // Must use "that" because "this" binding only works inside the function and not when call by the Dev outside of it using their instance of it
    that.areaWidth = that.area.outerWidth();
    if (that.areaWidth < that.minWidth + (this.areaMargin ? that.areaMargin * 2 : 0)) {
      that.areaWidth = that.minWidth;
    }
    that.calcColumns = Math.floor(that.areaWidth / that.minWidth);
    that.columns = that.calcColumns > that.maxColumns ? that.maxColumns : that.calcColumns;
    that.flagstoneWidth = (that.areaWidth / that.columns) - ((that.flagstonesMargin * (that.columns - 1) + (that.areaMargin * 2)) / that.columns);
    while (that.flagstoneHeights.length > 0) {
      that.flagstoneHeights.pop();
    }
    that.flagstones.each(function() {
      var self = $(this);
      if (that.jqueryAnimation) {
        self.animate({
          'width': that.flagstoneWidth + 'px'
        }, that.duration * 1000);
      } else {
        self.css('width', that.flagstoneWidth + 'px');
      }
      that.flagstoneHeights.push(self.outerHeight());
    });
    that.run();
  };
  // DYNAMIC CONTENT RESET / HARD RESET
  this.hardReset = function() {
    // Must use "that" because "this" binding only works inside the function and not when call by the Dev outside of it using their instance of it
    that.hide();
    setTimeout(function() {
      that.flagstones = $(that.flagstonesStr);
      that.reset();
    }, 0);
  };
  // INITIALIZE THE oECT
  this.init = function() {
    this.hide();
    var head = $('head');
    // Setup box-sizing
    head.append('<style>' + this.areaStr + '{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;min-width:' + (this.minWidth + (this.margin * 2)) + 'px;}' + this.flagstonesStr + '{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;top:0px;' + this.direction + ':0px;}' + this.areaStr + '.flagstones-hidden{visibility:hidden;}</style>');
    // Setup CSS animation if enabled
    if (!this.jqueryAnimation) {
      head.append('<style>' + this.areaStr + '{-webkit-transition-duration:' + that.duration + 's;-moz-transition-duration:' + that.duration + 's;-ms-transition-duration:' + that.duration + 's;-o-transition-duration:' + that.duration + 's;transition-duration:' + that.duration + 's;}' + this.flagstonesStr + '{-webkit-transition-duration:' + that.duration + 's;-moz-transition-duration:' + that.duration + 's;-ms-transition-duration:' + that.duration + 's;-o-transition-duration:' + that.duration + 's;transition-duration:' + that.duration + 's;}</style>');
    };
    // Resize listener
    $(window).on('resize', function() {
      // if (!that.duration) {}
      clearTimeout(that.resetDelay1);
      clearTimeout(that.resetDelay2);
      clearTimeout(that.resetDelay3);
      that.resetDelay1 = setTimeout(that.reset.bind(that), that.resizeDelay);
      that.resetDelay2 = setTimeout(that.reset.bind(that), that.duration + that.resizeDelay + 1000); // Makes CSS & jQuery animation top align correctly
      that.resetDelay3 = setTimeout(that.reset.bind(that), that.duration + that.resizeDelay + 2000); // Makes CSS & jQuery animation top align correctly
    });
    // Run reset to calculate and run flagstone!
    setTimeout(this.reset.bind(this), 0);
    // Reset immediately after resources have loaded to get correct heights
    setTimeout(function() {
      that.area.find('img,iframe,video,audio,oect,embed').on('load', function() {
        that.reset();
      });
    }, 0);
  };
  this.init();
}; // end FLAGSTONEJS
<commit_msg>Fixed reset bug and Safari initial positioning issues<commit_after>/*
 Copyright 2014-2015 by CLEARWAVE DESIGNS, LLC.

 Licensed under the Apache License, Version 2.0
 http://www.apache.org/licenses/LICENSE-2.0

 Author:        Adam Carson
 Website:       http://clearwavedesigns.com
 Dependencies:  jquery.js (1.8.3+)

 Name(s):       FlagstoneJS (flagstone.js)
 Version:       1.3.20150723
 Slogan:        "Responsive tiling."
 Description:   Responsively tiles HTML elements left to right, top to bottom, and where there's the most room.
 */

var FLAGSTONE = function(settings) {

  var that = this;

  var o = settings || {};
  // AREA (CONTAINER)
  this.areaStr = o.area || '[flagstones]';
  this.area = $(this.areaStr);
  this.areaMargin = o.margin || o.margin === 0 ? o.margin : o.areaMargin || o.areaMargin === 0 ? o.areaMargin : 10;
  this.areaWidth = this.area.outerWidth();
  this.areaHeight = this.area.outerHeight();
  // MIN WIDTH
  this.minWidth = o.minWidth || 280;
  // COLUMNS
  this.maxColumns = o.maxColumns || 1920;
  this.calcColumns = Math.floor(this.areaWidth / this.minWidth);
  this.columns = this.calcColumns > this.maxColumns ? this.maxColumns : this.calcColumns;
  // MARGIN
  this.margin = o.margin || o.margin === 0 ? o.margin : 10;
  // FLAGSTONES
  this.flagstonesStr = o.flagstones || '[flagstone]';
  this.flagstones = $(this.flagstonesStr);
  this.flagstonesMargin = o.margin || o.margin === 0 ? o.margin : o.flagstonesMargin || o.flagstonesMargin === 0 ? o.flagstonesMargin : 10;
  this.flagstoneHeights = [];
  this.flagstoneWidth = (this.areaWidth / this.columns) - ((this.margin * (this.columns + 1)) / this.columns);
  // DIRECTION
  this.direction = o.direction ? o.direction.toLowerCase() : 'left';
  // ANIMATION
  this.duration = o.duration / 1000 || 0;
  this.jqueryAnimation = o.jqueryAnimation;
  // RESIZE/RESET DELAY
  this.resizeDelay = o.resizeDelay || 0;
  // HIDE (for Developers as well when then are injecting new content onto their page, so they can hide the flagstones before they get a change to re-calculate);
  this.hide = function() {
    // Must use "that" because "this" binding only works inside the function and not when call by the Dev outside of it using their instance of it
    this.area.addClass('flagstones-hidden');
  };

  // RUN
  this.run = function() {
    var columnHeights = new Array(this.columns);
    for (var i = 0, l = this.flagstoneHeights.length; i < l; i++) {
      if (i < this.columns) {
        // First "row"
        for (var ii = 0, ll = this.columns; ii < ll; ii++) {
          if (this.jqueryAnimation) {
            this.flagstones.eq(ii).animate({
              'top': this.areaMargin + 'px',
              'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px',
              'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px'
            }, this.duration * 1000);
          } else {
            this.flagstones.eq(ii).css({
              'top': this.areaMargin + 'px',
              'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px',
              'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * ii + (ii ? this.flagstonesMargin * ii + this.areaMargin : this.areaMargin)) + 'px'
            });
          }
          columnHeights[ii] = this.flagstoneHeights[ii] + this.areaMargin;
        }
      } else {
        // Every other "row"
        var smallestColumnHeight = Math.min.apply(null, columnHeights);
        var smallestColumn = columnHeights.indexOf(smallestColumnHeight);
        if (this.jqueryAnimation) {
          this.flagstones.eq(i).animate({
            'top': (smallestColumnHeight + this.flagstonesMargin) + 'px',
            'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px',
            'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px'
          }, this.duration * 1000);
        } else {
          this.flagstones.eq(i).css({
            'top': (smallestColumnHeight + this.flagstonesMargin) + 'px',
            'left': this.direction === 'right' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px',
            'right': this.direction === 'left' ? 'auto' : (this.flagstoneWidth * smallestColumn + (smallestColumn ? this.flagstonesMargin * smallestColumn + this.areaMargin : this.areaMargin)) + 'px'
          });
        }
        columnHeights[smallestColumn] += this.flagstoneHeights[i] + this.flagstonesMargin;
      }
      this.area.css('height', (Math.max.apply(null, columnHeights) || this.flagstoneHeights[0] + this.areaMargin) + this.areaMargin + 'px');
    }
    setTimeout(function() {
      that.area.removeClass('flagstones-hidden');
    }, 0);
  };
  // RESIZE AND RESET
  this.resetDelay1;
  this.resetDelay2;
  this.resetDelay3;
  this.reset = function() {
    // Must use "that" because "this" binding only works inside the function and not when call by the Dev outside of it using their instance of it
    that.areaWidth = that.area.outerWidth();
    if (that.areaWidth < that.minWidth + (this.areaMargin ? that.areaMargin * 2 : 0)) {
      that.areaWidth = that.minWidth;
    }
    that.calcColumns = Math.floor(that.areaWidth / that.minWidth);
    that.columns = that.calcColumns > that.maxColumns ? that.maxColumns : that.calcColumns;
    that.flagstoneWidth = (that.areaWidth / that.columns) - ((that.flagstonesMargin * (that.columns - 1) + (that.areaMargin * 2)) / that.columns);
    while (that.flagstoneHeights.length > 0) {
      that.flagstoneHeights.pop();
    }
    that.flagstones.each(function() {
      var self = $(this);
      if (that.jqueryAnimation) {
        self.animate({
          'width': that.flagstoneWidth + 'px'
        }, that.duration * 1000);
      } else {
        self.css('width', that.flagstoneWidth + 'px');
      }
      that.flagstoneHeights.push(self.outerHeight());
    });
    that.run();
  };
  // DYNAMIC CONTENT RESET / HARD RESET
  this.hardReset = function() {
    // Must use "that" because "this" binding only works inside the function and not when call by the Dev outside of it using their instance of it
    that.hide();
    setTimeout(function() {
      that.flagstones = $(that.flagstonesStr);
      that.reset();
    }, 0);
  };
  // RESETS (ADDRESSES ISSUES WITH POSITIONING WHEN CSS ANIMATIONS ARE USED, THAT'S WHY THERE ARE 3 RESETS)
  this.resets = function() {
      clearTimeout(that.resetDelay1);
      clearTimeout(that.resetDelay2);
      clearTimeout(that.resetDelay3);
      that.resetDelay1 = setTimeout(that.reset.bind(that), that.resizeDelay);
      that.resetDelay2 = setTimeout(that.reset.bind(that), (that.duration * 1000) + that.resizeDelay);
      that.resetDelay3 = setTimeout(that.reset.bind(that), (that.duration * 2000) + that.resizeDelay);
  };
  // INITIALIZE
  this.init = function() {
    this.hide();
    var head = $('head');
    // Setup box-sizing
    head.append('<style>' + this.areaStr + '{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;min-width:' + (this.minWidth + (this.margin * 2)) + 'px;}' + this.flagstonesStr + '{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;top:0px;' + this.direction + ':0px;}' + this.areaStr + '.flagstones-hidden{visibility:hidden;}</style>');
    // Setup CSS animation if enabled
    if (!this.jqueryAnimation) {
      head.append('<style>' + this.areaStr + '{-webkit-transition-duration:' + that.duration + 's;-moz-transition-duration:' + that.duration + 's;-ms-transition-duration:' + that.duration + 's;-o-transition-duration:' + that.duration + 's;transition-duration:' + that.duration + 's;}' + this.flagstonesStr + '{-webkit-transition-duration:' + that.duration + 's;-moz-transition-duration:' + that.duration + 's;-ms-transition-duration:' + that.duration + 's;-o-transition-duration:' + that.duration + 's;transition-duration:' + that.duration + 's;}</style>');
    };
    // Run reset to calculate and run flagstone!
    setTimeout(that.reset, 0);
    // Reset immediately after resources have loaded to get correct heights
    setTimeout(window.addEventListener('load', that.resets), 0);
    // Resize listener
    window.addEventListener('resize', that.resets);
  };
  this.init();
}; // end FLAGSTONEJS
<|endoftext|>


<commit_before>net = require('net');

exports.listen = function(rpc_functions, port) {
	net.createServer(function (socket) {

		socket.uwsgi = new Buffer(0);
		// parse the uwsgi request
		socket.on('data', function(data) {
			socket.uwsgi = Buffer.concat([socket.uwsgi, data]);
			if (call_rpc() == -1) socket.destroy();
		});

		function call_rpc() {
			if (socket.uwsgi.length >= 4) {
				var modifier1 = socket.uwsgi.readUInt8(0);
				var pktsize = socket.uwsgi.readUInt16LE(1);
				var modifier2 = socket.uwsgi.readUInt8(3);

				if (socket.uwsgi.length - 4 < pktsize) return 0;
				var args = new Array();
				// here we parse the uwsgi packet
				for(var i=0;i<pktsize;i++) {
					item_len = socket.uwsgi.readUInt16LE(4 + i);
                                	var base = 4 + i + 2;
					var item = socket.uwsgi.toString('utf8', base, base + item_len);
					args.push(item);
					i += 1 + item_len;
				}

				// check if the functions is defined
				if (args.length == 0) return -1;
				if (!(args[0] in rpc_functions)) return -1;

				var func_name = args.shift();
				var value = rpc_functions[func_name].apply(this, args);
				// build teh response packet
				var response = new Buffer(4 + value.length);
				response.writeUInt8(173, 0);
				response.writeUInt16LE(value.length, 1);
				response.writeUInt8(0, 3);
				response.write(value, 4);
				socket.write(response, 'utf8', function() { socket.destroy();});
			}
			return 0;
		}

	}).listen(port);
	console.log("RPC server started...");
};
<commit_msg>added 64bit support<commit_after>net = require('net');

exports.listen = function(rpc_functions, port) {
	net.createServer(function (socket) {

		socket.uwsgi = new Buffer(0);
		// parse the uwsgi request
		socket.on('data', function(data) {
			socket.uwsgi = Buffer.concat([socket.uwsgi, data]);
			if (call_rpc() == -1) socket.destroy();
		});

		function call_rpc() {
			if (socket.uwsgi.length >= 4) {
				var modifier1 = socket.uwsgi.readUInt8(0);
				var pktsize = socket.uwsgi.readUInt16LE(1);
				var modifier2 = socket.uwsgi.readUInt8(3);

				if (socket.uwsgi.length - 4 < pktsize) return 0;
				var args = new Array();
				// here we parse the uwsgi packet
				for(var i=0;i<pktsize;i++) {
					item_len = socket.uwsgi.readUInt16LE(4 + i);
                                	var base = 4 + i + 2;
					var item = socket.uwsgi.toString('utf8', base, base + item_len);
					args.push(item);
					i += 1 + item_len;
				}

				// check if the functions is defined
				if (args.length == 0) return -1;
				if (!(args[0] in rpc_functions)) return -1;

				var func_name = args.shift();
				var value = rpc_functions[func_name].apply(this, args);
				// build the response packet
				// 64bit version
				if (value.length > 65535) {
					var str_length = '' + value.length;
					var content_length = 'CONTENT_LENGTH';
					var dict_length = 2 + content_length.length + 2 + str_length.length;
					var response = new Buffer(4 + dict_length);
					response.writeUInt8(173, 0);
					response.writeUInt16LE(dict_length, 1);
					response.writeUInt8(5, 3);
					response.writeUInt16LE(content_length.length, 4)
					response.write(content_length, 6)
					response.writeUInt16LE(str_length.length, 6 + content_length.length)
					response.write(str_length, 6 + content_length.length + 2)
					socket.write(response, 'utf8', function() {
						socket.write(value, 'utf8', function() { socket.destroy();});
					});
				}
				// 16bit version
				else {
					var response = new Buffer(4 + value.length);
					response.writeUInt8(173, 0);
					response.writeUInt16LE(value.length, 1);
					response.writeUInt8(0, 3);
					response.write(value, 4);
					socket.write(response, 'utf8', function() { socket.destroy();});
				}
			}
			return 0;
		}

	}).listen(port);
	console.log("RPC server started...");
};
<|endoftext|>


<commit_before>/* eslint no-underscore-dangle: 0 */

import React, { Fragment, Component, createElement } from 'react';
import { isForwardRef } from 'react-is';
import { polyfill } from 'react-lifecycles-compat';
import PropTypes from 'prop-types';
import global from 'global';

import marksy from 'marksy';
import jsxToString from 'react-element-to-jsx-string';
import { Code } from './markdown';
import { getDisplayName, getType } from '../react-utils';

global.STORYBOOK_REACT_CLASSES = global.STORYBOOK_REACT_CLASSES || [];
const { STORYBOOK_REACT_CLASSES } = global;

const stylesheetBase = {
  button: {
    base: {
      fontFamily: 'sans-serif',
      fontSize: '12px',
      display: 'block',
      position: 'fixed',
      border: 'none',
      background: '#027ac5',
      color: '#fff',
      padding: '5px 15px',
      cursor: 'pointer',
    },
    topRight: {
      top: 0,
      right: 0,
      borderRadius: '0 0 0 5px',
    },
  },
  info: {
    position: 'fixed',
    background: 'white',
    top: 0,
    left: 0,
    height: '100vh',
    width: '100vw',
    overflow: 'auto',
    zIndex: 99999,
  },
  children: {
    position: 'relative',
    zIndex: 0,
  },
  infoBody: {
    fontFamily: 'Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif',
    color: 'black',
    fontWeight: 300,
    lineHeight: 1.45,
    fontSize: '15px',
    padding: '20px 40px 40px',
    borderRadius: '2px',
    backgroundColor: '#fff',
  },
  infoContent: {
    marginBottom: 0,
  },
  infoStory: {},
  jsxInfoContent: {
    borderTop: '1px solid #eee',
    margin: '20px 0 0 0',
  },
  header: {
    h1: {
      margin: 0,
      padding: 0,
      fontSize: '35px',
    },
    h2: {
      margin: '0 0 10px 0',
      padding: 0,
      fontWeight: 400,
      fontSize: '22px',
    },
    h3: {
      margin: '0 0 10px 0',
      padding: 0,
      fontWeight: 400,
      fontSize: '18px',
    },
    body: {
      borderBottom: '1px solid #eee',
      paddingTop: 10,
      marginBottom: 10,
    },
  },
  source: {
    h1: {
      margin: '20px 0 0 0',
      padding: '0 0 5px 0',
      fontSize: '25px',
      borderBottom: '1px solid #EEE',
    },
  },
  propTableHead: {
    margin: '20px 0 0 0',
  },
};

class Story extends Component {
  constructor(props, ...args) {
    super(props, ...args);
    this.state = {
      open: false,
    };
    this.marksy = marksy({
      createElement,
      elements: props.components,
    });
  }

  _renderStory() {
    const { stylesheet } = this.state;
    const { children } = this.props;

    return (

        {children}

    );
  }

  _renderInline() {
    const { stylesheet } = this.state;

    return (
      <Fragment>
        {this._renderInlineHeader()}
        {this._renderStory()}

            {this._getInfoContent()}
            {this._getComponentDescription()}
            {this._getSourceCode()}
            {this._getPropTables()}

      </Fragment>
    );
  }

  _renderInlineHeader() {
    const { stylesheet } = this.state;

    const infoHeader = this._getInfoHeader();

    return (
      infoHeader && (

{infoHeader}

      )
    );
  }

  _renderOverlay() {
    const { stylesheet, open } = this.state;
    const { children } = this.props;

    const buttonStyle = {
      ...stylesheet.button.base,
      ...stylesheet.button.topRight,
    };

    const infoStyle = Object.assign({}, stylesheet.info);
    if (!open) {
      infoStyle.display = 'none';
    }

    const openOverlay = () => {
      this.setState({ open: true });
      return false;
    };

    const closeOverlay = () => {
      this.setState({ open: false });
      return false;
    };

    return (
      <Fragment>

{children}

        <button
          type="button"
          style={buttonStyle}
          onClick={openOverlay}
          className="info__show-button"
        >
          Show Info
        </button>
        {open ? (

            <button
              type="button"
              style={buttonStyle}
              onClick={closeOverlay}
              className="info__close-button"
            >
              ×
            </button>

                {this._getInfoHeader()}
                {this._getInfoContent()}
                {this._getComponentDescription()}
                {this._getSourceCode()}
                {this._getPropTables()}

        ) : null}
      </Fragment>
    );
  }

  _getInfoHeader() {
    const { stylesheet } = this.state;
    const { context, showHeader } = this.props;

    if (!context || !showHeader) {
      return null;
    }

    return (

{context.kind}

{context.name}

    );
  }

  _getInfoContent() {
    const { info, showInline } = this.props;
    const { stylesheet } = this.state;

    if (!info) {
      return '';
    }

    if (React.isValidElement(info)) {
      return (

{info}

      );
    }

    const lines = info.split('\n');
    while (lines[0].trim() === '') {
      lines.shift();
    }
    let padding = 0;
    const matches = lines[0].match(/^ */);
    if (matches) {
      padding = matches[0].length;
    }
    const source = lines.map(s => s.slice(padding)).join('\n');

    return <Fragment>{this.marksy(source).tree}</Fragment>;
  }

  _getComponentDescription() {
    const {
      context: { kind, name },
    } = this.props;
    let retDiv = null;

    const validMatches = [kind, name];

    if (Object.keys(STORYBOOK_REACT_CLASSES).length) {
      Object.keys(STORYBOOK_REACT_CLASSES).forEach(key => {
        if (validMatches.includes(STORYBOOK_REACT_CLASSES[key].name)) {
          const componentDescription = STORYBOOK_REACT_CLASSES[key].docgenInfo.description;
          retDiv = <Fragment>{this.marksy(componentDescription).tree}</Fragment>;
        }
      });
    }

    return retDiv;
  }

  _getSourceCode() {
    const { showSource, children } = this.props;
    const { stylesheet } = this.state;

    if (!showSource) {
      return null;
    }

    return (
      <Fragment>

Story Source

      </Fragment>
    );
  }

  _getPropTables() {
    const {
      children,
      propTablesExclude,
      maxPropObjectKeys,
      maxPropArrayLength,
      maxPropStringLength,
      excludedPropTypes,
    } = this.props;
    let { propTables } = this.props;
    const { stylesheet } = this.state;
    const types = new Map();

    if (!propTables) {
      return null;
    }

    if (!children) {
      return null;
    }

    if (Array.isArray(propTables)) {
      propTables.forEach(type => {
        types.set(type, true);
      });
    }

    // depth-first traverse and collect types
    const extract = innerChildren => {
      if (!innerChildren) {
        return;
      }
      if (Array.isArray(innerChildren)) {
        innerChildren.forEach(extract);
        return;
      }
      if (innerChildren.props && innerChildren.props.children) {
        extract(innerChildren.props.children);
      }
      if (isForwardRef(innerChildren)) {
        try {
          // this might fail because of hooks being used
          extract(innerChildren.type.render(innerChildren.props));
        } catch (e) {
          // do nothing
        }
      }
      if (
        typeof innerChildren === 'string' ||
        typeof innerChildren.type === 'string' ||
        (Array.isArray(propTables) &&
        propTables.length > 0 && // if propTables is set and has items in it
          !propTables.includes(innerChildren.type)) || // ignore types that are missing from propTables
        (Array.isArray(propTablesExclude) && // also ignore excluded types
          ~propTablesExclude.indexOf(innerChildren.type)) // eslint-disable-line no-bitwise
      ) {
        return;
      }

      if (innerChildren.type && !types.has(innerChildren.type)) {
        types.set(innerChildren.type, true);
      }
    };

    // extract components from children
    extract(children);

    const array = Array.from(types.keys());
    array.sort((a, b) => (getDisplayName(a) > getDisplayName(b) ? 1 : -1));

    propTables = array.map((type, i) => (
      // eslint-disable-next-line react/no-array-index-key
      <div key={`${getDisplayName(type)}_${i}`}>

"{getDisplayName(type)}" Component

        <this.props.PropTable
          type={getType(type)}
          maxPropObjectKeys={maxPropObjectKeys}
          maxPropArrayLength={maxPropArrayLength}
          maxPropStringLength={maxPropStringLength}
          excludedPropTypes={excludedPropTypes}
        />

    ));

    if (!propTables || propTables.length === 0) {
      return null;
    }

    return (
      <Fragment>

Prop Types

        {propTables}
      </Fragment>
    );
  }

  render() {
    const { showInline } = this.props;
    return showInline ? this._renderInline() : this._renderOverlay();
  }
}

Story.getDerivedStateFromProps = ({ styles }) => ({ stylesheet: styles(stylesheetBase) });

Story.displayName = 'Story';

Story.propTypes = {
  context: PropTypes.shape({
    kind: PropTypes.string,
    name: PropTypes.string,
  }),
  info: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  propTables: PropTypes.arrayOf(PropTypes.func),
  propTablesExclude: PropTypes.arrayOf(PropTypes.func),
  showInline: PropTypes.bool,
  showHeader: PropTypes.bool,
  showSource: PropTypes.bool,
  // eslint-disable-next-line react/no-unused-prop-types
  styles: PropTypes.func.isRequired,
  children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  components: PropTypes.shape({}),
  maxPropObjectKeys: PropTypes.number.isRequired,
  maxPropArrayLength: PropTypes.number.isRequired,
  maxPropStringLength: PropTypes.number.isRequired,
  excludedPropTypes: PropTypes.arrayOf(PropTypes.string),
};

Story.defaultProps = {
  context: null,
  info: '',
  children: null,
  propTables: null,
  propTablesExclude: [],
  showInline: false,
  showHeader: true,
  showSource: true,
  components: {},
  excludedPropTypes: [],
};

polyfill(Story);

export default Story;
<commit_msg>fix deepscan issue<commit_after>/* eslint no-underscore-dangle: 0 */

import React, { Fragment, Component, createElement } from 'react';
import { isForwardRef } from 'react-is';
import { polyfill } from 'react-lifecycles-compat';
import PropTypes from 'prop-types';
import global from 'global';

import marksy from 'marksy';
import jsxToString from 'react-element-to-jsx-string';
import { Code } from './markdown';
import { getDisplayName, getType } from '../react-utils';

global.STORYBOOK_REACT_CLASSES = global.STORYBOOK_REACT_CLASSES || [];
const { STORYBOOK_REACT_CLASSES } = global;

const stylesheetBase = {
  button: {
    base: {
      fontFamily: 'sans-serif',
      fontSize: '12px',
      display: 'block',
      position: 'fixed',
      border: 'none',
      background: '#027ac5',
      color: '#fff',
      padding: '5px 15px',
      cursor: 'pointer',
    },
    topRight: {
      top: 0,
      right: 0,
      borderRadius: '0 0 0 5px',
    },
  },
  info: {
    position: 'fixed',
    background: 'white',
    top: 0,
    left: 0,
    height: '100vh',
    width: '100vw',
    overflow: 'auto',
    zIndex: 99999,
  },
  children: {
    position: 'relative',
    zIndex: 0,
  },
  infoBody: {
    fontFamily: 'Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif',
    color: 'black',
    fontWeight: 300,
    lineHeight: 1.45,
    fontSize: '15px',
    padding: '20px 40px 40px',
    borderRadius: '2px',
    backgroundColor: '#fff',
  },
  infoContent: {
    marginBottom: 0,
  },
  infoStory: {},
  jsxInfoContent: {
    borderTop: '1px solid #eee',
    margin: '20px 0 0 0',
  },
  header: {
    h1: {
      margin: 0,
      padding: 0,
      fontSize: '35px',
    },
    h2: {
      margin: '0 0 10px 0',
      padding: 0,
      fontWeight: 400,
      fontSize: '22px',
    },
    h3: {
      margin: '0 0 10px 0',
      padding: 0,
      fontWeight: 400,
      fontSize: '18px',
    },
    body: {
      borderBottom: '1px solid #eee',
      paddingTop: 10,
      marginBottom: 10,
    },
  },
  source: {
    h1: {
      margin: '20px 0 0 0',
      padding: '0 0 5px 0',
      fontSize: '25px',
      borderBottom: '1px solid #EEE',
    },
  },
  propTableHead: {
    margin: '20px 0 0 0',
  },
};

class Story extends Component {
  constructor(props, ...args) {
    super(props, ...args);
    this.state = {
      open: false,
    };
    this.marksy = marksy({
      createElement,
      elements: props.components,
    });
  }

  _renderStory() {
    const { stylesheet } = this.state;
    const { children } = this.props;

    return (

        {children}

    );
  }

  _renderInline() {
    const { stylesheet } = this.state;

    return (
      <Fragment>
        {this._renderInlineHeader()}
        {this._renderStory()}

            {this._getInfoContent()}
            {this._getComponentDescription()}
            {this._getSourceCode()}
            {this._getPropTables()}

      </Fragment>
    );
  }

  _renderInlineHeader() {
    const { stylesheet } = this.state;

    const infoHeader = this._getInfoHeader();

    return (
      infoHeader && (

{infoHeader}

      )
    );
  }

  _renderOverlay() {
    const { stylesheet, open } = this.state;
    const { children } = this.props;

    const buttonStyle = {
      ...stylesheet.button.base,
      ...stylesheet.button.topRight,
    };

    const infoStyle = Object.assign({}, stylesheet.info);
    if (!open) {
      infoStyle.display = 'none';
    }

    const openOverlay = () => {
      this.setState({ open: true });
      return false;
    };

    const closeOverlay = () => {
      this.setState({ open: false });
      return false;
    };

    return (
      <Fragment>

{children}

        <button
          type="button"
          style={buttonStyle}
          onClick={openOverlay}
          className="info__show-button"
        >
          Show Info
        </button>
        {open ? (

            <button
              type="button"
              style={buttonStyle}
              onClick={closeOverlay}
              className="info__close-button"
            >
              ×
            </button>

                {this._getInfoHeader()}
                {this._getInfoContent()}
                {this._getComponentDescription()}
                {this._getSourceCode()}
                {this._getPropTables()}

        ) : null}
      </Fragment>
    );
  }

  _getInfoHeader() {
    const { stylesheet } = this.state;
    const { context, showHeader } = this.props;

    if (!context || !showHeader) {
      return null;
    }

    return (

{context.kind}

{context.name}

    );
  }

  _getInfoContent() {
    const { info, showInline } = this.props;
    const { stylesheet } = this.state;

    if (!info) {
      return '';
    }

    if (React.isValidElement(info)) {
      return (

{info}

      );
    }

    const lines = info.split('\n');
    while (lines[0].trim() === '') {
      lines.shift();
    }
    let padding = 0;
    const matches = lines[0].match(/^ */);
    if (matches) {
      padding = matches[0].length;
    }
    const source = lines.map(s => s.slice(padding)).join('\n');

    return <Fragment>{this.marksy(source).tree}</Fragment>;
  }

  _getComponentDescription() {
    const {
      context: { kind, name },
    } = this.props;
    let retDiv = null;

    const validMatches = [kind, name];

    if (Object.keys(STORYBOOK_REACT_CLASSES).length) {
      Object.keys(STORYBOOK_REACT_CLASSES).forEach(key => {
        if (validMatches.includes(STORYBOOK_REACT_CLASSES[key].name)) {
          const componentDescription = STORYBOOK_REACT_CLASSES[key].docgenInfo.description;
          retDiv = <Fragment>{this.marksy(componentDescription).tree}</Fragment>;
        }
      });
    }

    return retDiv;
  }

  _getSourceCode() {
    const { showSource, children } = this.props;
    const { stylesheet } = this.state;

    if (!showSource) {
      return null;
    }

    return (
      <Fragment>

Story Source

      </Fragment>
    );
  }

  _getPropTables() {
    const {
      children,
      propTablesExclude,
      maxPropObjectKeys,
      maxPropArrayLength,
      maxPropStringLength,
      excludedPropTypes,
    } = this.props;
    let { propTables } = this.props;
    const { stylesheet } = this.state;
    const types = new Map();

    if (!propTables) {
      return null;
    }

    if (!children) {
      return null;
    }

    if (propTables) {
      propTables.forEach(type => {
        types.set(type, true);
      });
    }

    // depth-first traverse and collect types
    const extract = innerChildren => {
      if (!innerChildren) {
        return;
      }
      if (Array.isArray(innerChildren)) {
        innerChildren.forEach(extract);
        return;
      }
      if (innerChildren.props && innerChildren.props.children) {
        extract(innerChildren.props.children);
      }
      if (isForwardRef(innerChildren)) {
        try {
          // this might fail because of hooks being used
          extract(innerChildren.type.render(innerChildren.props));
        } catch (e) {
          // do nothing
        }
      }
      if (
        typeof innerChildren === 'string' ||
        typeof innerChildren.type === 'string' ||
        (Array.isArray(propTables) &&
        propTables.length > 0 && // if propTables is set and has items in it
          !propTables.includes(innerChildren.type)) || // ignore types that are missing from propTables
        (Array.isArray(propTablesExclude) && // also ignore excluded types
          ~propTablesExclude.indexOf(innerChildren.type)) // eslint-disable-line no-bitwise
      ) {
        return;
      }

      if (innerChildren.type && !types.has(innerChildren.type)) {
        types.set(innerChildren.type, true);
      }
    };

    // extract components from children
    extract(children);

    const array = Array.from(types.keys());
    array.sort((a, b) => (getDisplayName(a) > getDisplayName(b) ? 1 : -1));

    propTables = array.map((type, i) => (
      // eslint-disable-next-line react/no-array-index-key
      <div key={`${getDisplayName(type)}_${i}`}>

"{getDisplayName(type)}" Component

        <this.props.PropTable
          type={getType(type)}
          maxPropObjectKeys={maxPropObjectKeys}
          maxPropArrayLength={maxPropArrayLength}
          maxPropStringLength={maxPropStringLength}
          excludedPropTypes={excludedPropTypes}
        />

    ));

    if (!propTables || propTables.length === 0) {
      return null;
    }

    return (
      <Fragment>

Prop Types

        {propTables}
      </Fragment>
    );
  }

  render() {
    const { showInline } = this.props;
    return showInline ? this._renderInline() : this._renderOverlay();
  }
}

Story.getDerivedStateFromProps = ({ styles }) => ({ stylesheet: styles(stylesheetBase) });

Story.displayName = 'Story';

Story.propTypes = {
  context: PropTypes.shape({
    kind: PropTypes.string,
    name: PropTypes.string,
  }),
  info: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  propTables: PropTypes.arrayOf(PropTypes.func),
  propTablesExclude: PropTypes.arrayOf(PropTypes.func),
  showInline: PropTypes.bool,
  showHeader: PropTypes.bool,
  showSource: PropTypes.bool,
  // eslint-disable-next-line react/no-unused-prop-types
  styles: PropTypes.func.isRequired,
  children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  components: PropTypes.shape({}),
  maxPropObjectKeys: PropTypes.number.isRequired,
  maxPropArrayLength: PropTypes.number.isRequired,
  maxPropStringLength: PropTypes.number.isRequired,
  excludedPropTypes: PropTypes.arrayOf(PropTypes.string),
};

Story.defaultProps = {
  context: null,
  info: '',
  children: null,
  propTables: null,
  propTablesExclude: [],
  showInline: false,
  showHeader: true,
  showSource: true,
  components: {},
  excludedPropTypes: [],
};

polyfill(Story);

export default Story;
<|endoftext|>


<commit_before><commit_msg>migration code<commit_after><|endoftext|>